babylon.max.js 2.3 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || function (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. MathTools.WithinEpsilon = function (a, b, epsilon) {
  22. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  23. var num = a - b;
  24. return -epsilon <= num && num <= epsilon;
  25. };
  26. MathTools.ToHex = function (i) {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. };
  33. // Returns -1 when value is a negative number and
  34. // +1 when value is a positive number.
  35. MathTools.Sign = function (value) {
  36. value = +value; // convert to a number
  37. if (value === 0 || isNaN(value))
  38. return value;
  39. return value > 0 ? 1 : -1;
  40. };
  41. MathTools.Clamp = function (value, min, max) {
  42. if (min === void 0) { min = 0; }
  43. if (max === void 0) { max = 1; }
  44. return Math.min(max, Math.max(min, value));
  45. };
  46. return MathTools;
  47. })();
  48. BABYLON.MathTools = MathTools;
  49. var Color3 = (function () {
  50. function Color3(r, g, b) {
  51. if (r === void 0) { r = 0; }
  52. if (g === void 0) { g = 0; }
  53. if (b === void 0) { b = 0; }
  54. this.r = r;
  55. this.g = g;
  56. this.b = b;
  57. }
  58. Color3.prototype.toString = function () {
  59. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  60. };
  61. // Operators
  62. Color3.prototype.toArray = function (array, index) {
  63. if (index === undefined) {
  64. index = 0;
  65. }
  66. array[index] = this.r;
  67. array[index + 1] = this.g;
  68. array[index + 2] = this.b;
  69. return this;
  70. };
  71. Color3.prototype.toColor4 = function (alpha) {
  72. if (alpha === void 0) { alpha = 1; }
  73. return new Color4(this.r, this.g, this.b, alpha);
  74. };
  75. Color3.prototype.asArray = function () {
  76. var result = [];
  77. this.toArray(result, 0);
  78. return result;
  79. };
  80. Color3.prototype.toLuminance = function () {
  81. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  82. };
  83. Color3.prototype.multiply = function (otherColor) {
  84. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  85. };
  86. Color3.prototype.multiplyToRef = function (otherColor, result) {
  87. result.r = this.r * otherColor.r;
  88. result.g = this.g * otherColor.g;
  89. result.b = this.b * otherColor.b;
  90. return this;
  91. };
  92. Color3.prototype.equals = function (otherColor) {
  93. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  94. };
  95. Color3.prototype.equalsFloats = function (r, g, b) {
  96. return this.r === r && this.g === g && this.b === b;
  97. };
  98. Color3.prototype.scale = function (scale) {
  99. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  100. };
  101. Color3.prototype.scaleToRef = function (scale, result) {
  102. result.r = this.r * scale;
  103. result.g = this.g * scale;
  104. result.b = this.b * scale;
  105. return this;
  106. };
  107. Color3.prototype.add = function (otherColor) {
  108. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  109. };
  110. Color3.prototype.addToRef = function (otherColor, result) {
  111. result.r = this.r + otherColor.r;
  112. result.g = this.g + otherColor.g;
  113. result.b = this.b + otherColor.b;
  114. return this;
  115. };
  116. Color3.prototype.subtract = function (otherColor) {
  117. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  118. };
  119. Color3.prototype.subtractToRef = function (otherColor, result) {
  120. result.r = this.r - otherColor.r;
  121. result.g = this.g - otherColor.g;
  122. result.b = this.b - otherColor.b;
  123. return this;
  124. };
  125. Color3.prototype.clone = function () {
  126. return new Color3(this.r, this.g, this.b);
  127. };
  128. Color3.prototype.copyFrom = function (source) {
  129. this.r = source.r;
  130. this.g = source.g;
  131. this.b = source.b;
  132. return this;
  133. };
  134. Color3.prototype.copyFromFloats = function (r, g, b) {
  135. this.r = r;
  136. this.g = g;
  137. this.b = b;
  138. return this;
  139. };
  140. Color3.prototype.toHexString = function () {
  141. var intR = (this.r * 255) | 0;
  142. var intG = (this.g * 255) | 0;
  143. var intB = (this.b * 255) | 0;
  144. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  145. };
  146. Color3.prototype.toLinearSpace = function () {
  147. var convertedColor = new Color3();
  148. this.toLinearSpaceToRef(convertedColor);
  149. return convertedColor;
  150. };
  151. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  152. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  153. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  154. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  155. return this;
  156. };
  157. Color3.prototype.toGammaSpace = function () {
  158. var convertedColor = new Color3();
  159. this.toGammaSpaceToRef(convertedColor);
  160. return convertedColor;
  161. };
  162. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  163. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  164. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  165. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  166. return this;
  167. };
  168. // Statics
  169. Color3.FromHexString = function (hex) {
  170. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  171. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  172. return new Color3(0, 0, 0);
  173. }
  174. var r = parseInt(hex.substring(1, 3), 16);
  175. var g = parseInt(hex.substring(3, 5), 16);
  176. var b = parseInt(hex.substring(5, 7), 16);
  177. return Color3.FromInts(r, g, b);
  178. };
  179. Color3.FromArray = function (array, offset) {
  180. if (offset === void 0) { offset = 0; }
  181. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  182. };
  183. Color3.FromInts = function (r, g, b) {
  184. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  185. };
  186. Color3.Lerp = function (start, end, amount) {
  187. var r = start.r + ((end.r - start.r) * amount);
  188. var g = start.g + ((end.g - start.g) * amount);
  189. var b = start.b + ((end.b - start.b) * amount);
  190. return new Color3(r, g, b);
  191. };
  192. Color3.Red = function () { return new Color3(1, 0, 0); };
  193. Color3.Green = function () { return new Color3(0, 1, 0); };
  194. Color3.Blue = function () { return new Color3(0, 0, 1); };
  195. Color3.Black = function () { return new Color3(0, 0, 0); };
  196. Color3.White = function () { return new Color3(1, 1, 1); };
  197. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  198. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  199. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  200. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  201. return Color3;
  202. })();
  203. BABYLON.Color3 = Color3;
  204. var Color4 = (function () {
  205. function Color4(r, g, b, a) {
  206. this.r = r;
  207. this.g = g;
  208. this.b = b;
  209. this.a = a;
  210. }
  211. // Operators
  212. Color4.prototype.addInPlace = function (right) {
  213. this.r += right.r;
  214. this.g += right.g;
  215. this.b += right.b;
  216. this.a += right.a;
  217. return this;
  218. };
  219. Color4.prototype.asArray = function () {
  220. var result = [];
  221. this.toArray(result, 0);
  222. return result;
  223. };
  224. Color4.prototype.toArray = function (array, index) {
  225. if (index === undefined) {
  226. index = 0;
  227. }
  228. array[index] = this.r;
  229. array[index + 1] = this.g;
  230. array[index + 2] = this.b;
  231. array[index + 3] = this.a;
  232. return this;
  233. };
  234. Color4.prototype.add = function (right) {
  235. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  236. };
  237. Color4.prototype.subtract = function (right) {
  238. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  239. };
  240. Color4.prototype.subtractToRef = function (right, result) {
  241. result.r = this.r - right.r;
  242. result.g = this.g - right.g;
  243. result.b = this.b - right.b;
  244. result.a = this.a - right.a;
  245. return this;
  246. };
  247. Color4.prototype.scale = function (scale) {
  248. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  249. };
  250. Color4.prototype.scaleToRef = function (scale, result) {
  251. result.r = this.r * scale;
  252. result.g = this.g * scale;
  253. result.b = this.b * scale;
  254. result.a = this.a * scale;
  255. return this;
  256. };
  257. Color4.prototype.toString = function () {
  258. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  259. };
  260. Color4.prototype.clone = function () {
  261. return new Color4(this.r, this.g, this.b, this.a);
  262. };
  263. Color4.prototype.copyFrom = function (source) {
  264. this.r = source.r;
  265. this.g = source.g;
  266. this.b = source.b;
  267. this.a = source.a;
  268. return this;
  269. };
  270. Color4.prototype.toHexString = function () {
  271. var intR = (this.r * 255) | 0;
  272. var intG = (this.g * 255) | 0;
  273. var intB = (this.b * 255) | 0;
  274. var intA = (this.a * 255) | 0;
  275. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  276. };
  277. // Statics
  278. Color4.FromHexString = function (hex) {
  279. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  280. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  281. return new Color4(0, 0, 0, 0);
  282. }
  283. var r = parseInt(hex.substring(1, 3), 16);
  284. var g = parseInt(hex.substring(3, 5), 16);
  285. var b = parseInt(hex.substring(5, 7), 16);
  286. var a = parseInt(hex.substring(7, 9), 16);
  287. return Color4.FromInts(r, g, b, a);
  288. };
  289. Color4.Lerp = function (left, right, amount) {
  290. var result = new Color4(0, 0, 0, 0);
  291. Color4.LerpToRef(left, right, amount, result);
  292. return result;
  293. };
  294. Color4.LerpToRef = function (left, right, amount, result) {
  295. result.r = left.r + (right.r - left.r) * amount;
  296. result.g = left.g + (right.g - left.g) * amount;
  297. result.b = left.b + (right.b - left.b) * amount;
  298. result.a = left.a + (right.a - left.a) * amount;
  299. };
  300. Color4.FromArray = function (array, offset) {
  301. if (offset === void 0) { offset = 0; }
  302. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  303. };
  304. Color4.FromInts = function (r, g, b, a) {
  305. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  306. };
  307. Color4.CheckColors4 = function (colors, count) {
  308. // Check if color3 was used
  309. if (colors.length === count * 3) {
  310. var colors4 = [];
  311. for (var index = 0; index < colors.length; index += 3) {
  312. var newIndex = (index / 3) * 4;
  313. colors4[newIndex] = colors[index];
  314. colors4[newIndex + 1] = colors[index + 1];
  315. colors4[newIndex + 2] = colors[index + 2];
  316. colors4[newIndex + 3] = 1.0;
  317. }
  318. return colors4;
  319. }
  320. return colors;
  321. };
  322. return Color4;
  323. })();
  324. BABYLON.Color4 = Color4;
  325. var Vector2 = (function () {
  326. function Vector2(x, y) {
  327. this.x = x;
  328. this.y = y;
  329. }
  330. Vector2.prototype.toString = function () {
  331. return "{X: " + this.x + " Y:" + this.y + "}";
  332. };
  333. // Operators
  334. Vector2.prototype.toArray = function (array, index) {
  335. if (index === void 0) { index = 0; }
  336. array[index] = this.x;
  337. array[index + 1] = this.y;
  338. return this;
  339. };
  340. Vector2.prototype.asArray = function () {
  341. var result = [];
  342. this.toArray(result, 0);
  343. return result;
  344. };
  345. Vector2.prototype.copyFrom = function (source) {
  346. this.x = source.x;
  347. this.y = source.y;
  348. return this;
  349. };
  350. Vector2.prototype.copyFromFloats = function (x, y) {
  351. this.x = x;
  352. this.y = y;
  353. return this;
  354. };
  355. Vector2.prototype.add = function (otherVector) {
  356. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  357. };
  358. Vector2.prototype.addVector3 = function (otherVector) {
  359. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  360. };
  361. Vector2.prototype.subtract = function (otherVector) {
  362. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  363. };
  364. Vector2.prototype.subtractInPlace = function (otherVector) {
  365. this.x -= otherVector.x;
  366. this.y -= otherVector.y;
  367. return this;
  368. };
  369. Vector2.prototype.multiplyInPlace = function (otherVector) {
  370. this.x *= otherVector.x;
  371. this.y *= otherVector.y;
  372. return this;
  373. };
  374. Vector2.prototype.multiply = function (otherVector) {
  375. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  376. };
  377. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  378. result.x = this.x * otherVector.x;
  379. result.y = this.y * otherVector.y;
  380. return this;
  381. };
  382. Vector2.prototype.multiplyByFloats = function (x, y) {
  383. return new Vector2(this.x * x, this.y * y);
  384. };
  385. Vector2.prototype.divide = function (otherVector) {
  386. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  387. };
  388. Vector2.prototype.divideToRef = function (otherVector, result) {
  389. result.x = this.x / otherVector.x;
  390. result.y = this.y / otherVector.y;
  391. return this;
  392. };
  393. Vector2.prototype.negate = function () {
  394. return new Vector2(-this.x, -this.y);
  395. };
  396. Vector2.prototype.scaleInPlace = function (scale) {
  397. this.x *= scale;
  398. this.y *= scale;
  399. return this;
  400. };
  401. Vector2.prototype.scale = function (scale) {
  402. return new Vector2(this.x * scale, this.y * scale);
  403. };
  404. Vector2.prototype.equals = function (otherVector) {
  405. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  406. };
  407. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  408. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  409. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  410. };
  411. // Properties
  412. Vector2.prototype.length = function () {
  413. return Math.sqrt(this.x * this.x + this.y * this.y);
  414. };
  415. Vector2.prototype.lengthSquared = function () {
  416. return (this.x * this.x + this.y * this.y);
  417. };
  418. // Methods
  419. Vector2.prototype.normalize = function () {
  420. var len = this.length();
  421. if (len === 0)
  422. return this;
  423. var num = 1.0 / len;
  424. this.x *= num;
  425. this.y *= num;
  426. return this;
  427. };
  428. Vector2.prototype.clone = function () {
  429. return new Vector2(this.x, this.y);
  430. };
  431. // Statics
  432. Vector2.Zero = function () {
  433. return new Vector2(0, 0);
  434. };
  435. Vector2.FromArray = function (array, offset) {
  436. if (offset === void 0) { offset = 0; }
  437. return new Vector2(array[offset], array[offset + 1]);
  438. };
  439. Vector2.FromArrayToRef = function (array, offset, result) {
  440. result.x = array[offset];
  441. result.y = array[offset + 1];
  442. };
  443. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  444. var squared = amount * amount;
  445. var cubed = amount * squared;
  446. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  447. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  448. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  449. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  450. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  451. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  452. return new Vector2(x, y);
  453. };
  454. Vector2.Clamp = function (value, min, max) {
  455. var x = value.x;
  456. x = (x > max.x) ? max.x : x;
  457. x = (x < min.x) ? min.x : x;
  458. var y = value.y;
  459. y = (y > max.y) ? max.y : y;
  460. y = (y < min.y) ? min.y : y;
  461. return new Vector2(x, y);
  462. };
  463. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  464. var squared = amount * amount;
  465. var cubed = amount * squared;
  466. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  467. var part2 = (-2.0 * cubed) + (3.0 * squared);
  468. var part3 = (cubed - (2.0 * squared)) + amount;
  469. var part4 = cubed - squared;
  470. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  471. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  472. return new Vector2(x, y);
  473. };
  474. Vector2.Lerp = function (start, end, amount) {
  475. var x = start.x + ((end.x - start.x) * amount);
  476. var y = start.y + ((end.y - start.y) * amount);
  477. return new Vector2(x, y);
  478. };
  479. Vector2.Dot = function (left, right) {
  480. return left.x * right.x + left.y * right.y;
  481. };
  482. Vector2.Normalize = function (vector) {
  483. var newVector = vector.clone();
  484. newVector.normalize();
  485. return newVector;
  486. };
  487. Vector2.Minimize = function (left, right) {
  488. var x = (left.x < right.x) ? left.x : right.x;
  489. var y = (left.y < right.y) ? left.y : right.y;
  490. return new Vector2(x, y);
  491. };
  492. Vector2.Maximize = function (left, right) {
  493. var x = (left.x > right.x) ? left.x : right.x;
  494. var y = (left.y > right.y) ? left.y : right.y;
  495. return new Vector2(x, y);
  496. };
  497. Vector2.Transform = function (vector, transformation) {
  498. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  499. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  500. return new Vector2(x, y);
  501. };
  502. Vector2.Distance = function (value1, value2) {
  503. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  504. };
  505. Vector2.DistanceSquared = function (value1, value2) {
  506. var x = value1.x - value2.x;
  507. var y = value1.y - value2.y;
  508. return (x * x) + (y * y);
  509. };
  510. return Vector2;
  511. })();
  512. BABYLON.Vector2 = Vector2;
  513. var Vector3 = (function () {
  514. function Vector3(x, y, z) {
  515. this.x = x;
  516. this.y = y;
  517. this.z = z;
  518. }
  519. Vector3.prototype.toString = function () {
  520. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  521. };
  522. // Operators
  523. Vector3.prototype.asArray = function () {
  524. var result = [];
  525. this.toArray(result, 0);
  526. return result;
  527. };
  528. Vector3.prototype.toArray = function (array, index) {
  529. if (index === void 0) { index = 0; }
  530. array[index] = this.x;
  531. array[index + 1] = this.y;
  532. array[index + 2] = this.z;
  533. return this;
  534. };
  535. Vector3.prototype.toQuaternion = function () {
  536. var result = new Quaternion(0, 0, 0, 1);
  537. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  538. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  539. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  540. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  541. var cosy = Math.cos(this.y * 0.5);
  542. var siny = Math.sin(this.y * 0.5);
  543. result.x = coszMinusx * siny;
  544. result.y = -sinzMinusx * siny;
  545. result.z = sinxPlusz * cosy;
  546. result.w = cosxPlusz * cosy;
  547. return result;
  548. };
  549. Vector3.prototype.addInPlace = function (otherVector) {
  550. this.x += otherVector.x;
  551. this.y += otherVector.y;
  552. this.z += otherVector.z;
  553. return this;
  554. };
  555. Vector3.prototype.add = function (otherVector) {
  556. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  557. };
  558. Vector3.prototype.addToRef = function (otherVector, result) {
  559. result.x = this.x + otherVector.x;
  560. result.y = this.y + otherVector.y;
  561. result.z = this.z + otherVector.z;
  562. return this;
  563. };
  564. Vector3.prototype.subtractInPlace = function (otherVector) {
  565. this.x -= otherVector.x;
  566. this.y -= otherVector.y;
  567. this.z -= otherVector.z;
  568. return this;
  569. };
  570. Vector3.prototype.subtract = function (otherVector) {
  571. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  572. };
  573. Vector3.prototype.subtractToRef = function (otherVector, result) {
  574. result.x = this.x - otherVector.x;
  575. result.y = this.y - otherVector.y;
  576. result.z = this.z - otherVector.z;
  577. return this;
  578. };
  579. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  580. return new Vector3(this.x - x, this.y - y, this.z - z);
  581. };
  582. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  583. result.x = this.x - x;
  584. result.y = this.y - y;
  585. result.z = this.z - z;
  586. return this;
  587. };
  588. Vector3.prototype.negate = function () {
  589. return new Vector3(-this.x, -this.y, -this.z);
  590. };
  591. Vector3.prototype.scaleInPlace = function (scale) {
  592. this.x *= scale;
  593. this.y *= scale;
  594. this.z *= scale;
  595. return this;
  596. };
  597. Vector3.prototype.scale = function (scale) {
  598. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  599. };
  600. Vector3.prototype.scaleToRef = function (scale, result) {
  601. result.x = this.x * scale;
  602. result.y = this.y * scale;
  603. result.z = this.z * scale;
  604. };
  605. Vector3.prototype.equals = function (otherVector) {
  606. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  607. };
  608. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  609. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  610. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  611. };
  612. Vector3.prototype.equalsToFloats = function (x, y, z) {
  613. return this.x === x && this.y === y && this.z === z;
  614. };
  615. Vector3.prototype.multiplyInPlace = function (otherVector) {
  616. this.x *= otherVector.x;
  617. this.y *= otherVector.y;
  618. this.z *= otherVector.z;
  619. return this;
  620. };
  621. Vector3.prototype.multiply = function (otherVector) {
  622. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  623. };
  624. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  625. result.x = this.x * otherVector.x;
  626. result.y = this.y * otherVector.y;
  627. result.z = this.z * otherVector.z;
  628. return this;
  629. };
  630. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  631. return new Vector3(this.x * x, this.y * y, this.z * z);
  632. };
  633. Vector3.prototype.divide = function (otherVector) {
  634. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  635. };
  636. Vector3.prototype.divideToRef = function (otherVector, result) {
  637. result.x = this.x / otherVector.x;
  638. result.y = this.y / otherVector.y;
  639. result.z = this.z / otherVector.z;
  640. return this;
  641. };
  642. Vector3.prototype.MinimizeInPlace = function (other) {
  643. if (other.x < this.x)
  644. this.x = other.x;
  645. if (other.y < this.y)
  646. this.y = other.y;
  647. if (other.z < this.z)
  648. this.z = other.z;
  649. return this;
  650. };
  651. Vector3.prototype.MaximizeInPlace = function (other) {
  652. if (other.x > this.x)
  653. this.x = other.x;
  654. if (other.y > this.y)
  655. this.y = other.y;
  656. if (other.z > this.z)
  657. this.z = other.z;
  658. return this;
  659. };
  660. // Properties
  661. Vector3.prototype.length = function () {
  662. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  663. };
  664. Vector3.prototype.lengthSquared = function () {
  665. return (this.x * this.x + this.y * this.y + this.z * this.z);
  666. };
  667. // Methods
  668. Vector3.prototype.normalize = function () {
  669. var len = this.length();
  670. if (len === 0 || len === 1.0)
  671. return this;
  672. var num = 1.0 / len;
  673. this.x *= num;
  674. this.y *= num;
  675. this.z *= num;
  676. return this;
  677. };
  678. Vector3.prototype.clone = function () {
  679. return new Vector3(this.x, this.y, this.z);
  680. };
  681. Vector3.prototype.copyFrom = function (source) {
  682. this.x = source.x;
  683. this.y = source.y;
  684. this.z = source.z;
  685. return this;
  686. };
  687. Vector3.prototype.copyFromFloats = function (x, y, z) {
  688. this.x = x;
  689. this.y = y;
  690. this.z = z;
  691. return this;
  692. };
  693. // Statics
  694. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  695. var d0 = Vector3.Dot(vector0, axis) - size;
  696. var d1 = Vector3.Dot(vector1, axis) - size;
  697. var s = d0 / (d0 - d1);
  698. return s;
  699. };
  700. Vector3.FromArray = function (array, offset) {
  701. if (!offset) {
  702. offset = 0;
  703. }
  704. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  705. };
  706. Vector3.FromFloatArray = function (array, offset) {
  707. if (!offset) {
  708. offset = 0;
  709. }
  710. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  711. };
  712. Vector3.FromArrayToRef = function (array, offset, result) {
  713. result.x = array[offset];
  714. result.y = array[offset + 1];
  715. result.z = array[offset + 2];
  716. };
  717. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  718. result.x = array[offset];
  719. result.y = array[offset + 1];
  720. result.z = array[offset + 2];
  721. };
  722. Vector3.FromFloatsToRef = function (x, y, z, result) {
  723. result.x = x;
  724. result.y = y;
  725. result.z = z;
  726. };
  727. Vector3.Zero = function () {
  728. return new Vector3(0, 0, 0);
  729. };
  730. Vector3.Up = function () {
  731. return new Vector3(0, 1.0, 0);
  732. };
  733. Vector3.TransformCoordinates = function (vector, transformation) {
  734. var result = Vector3.Zero();
  735. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  736. return result;
  737. };
  738. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  739. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  740. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  741. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  742. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  743. result.x = x / w;
  744. result.y = y / w;
  745. result.z = z / w;
  746. };
  747. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  748. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  749. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  750. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  751. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  752. result.x = rx / rw;
  753. result.y = ry / rw;
  754. result.z = rz / rw;
  755. };
  756. Vector3.TransformNormal = function (vector, transformation) {
  757. var result = Vector3.Zero();
  758. Vector3.TransformNormalToRef(vector, transformation, result);
  759. return result;
  760. };
  761. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  762. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  763. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  764. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  765. };
  766. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  767. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  768. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  769. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  770. };
  771. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  772. var squared = amount * amount;
  773. var cubed = amount * squared;
  774. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  775. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  776. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  777. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  778. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  779. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  780. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  781. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  782. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  783. return new Vector3(x, y, z);
  784. };
  785. Vector3.Clamp = function (value, min, max) {
  786. var x = value.x;
  787. x = (x > max.x) ? max.x : x;
  788. x = (x < min.x) ? min.x : x;
  789. var y = value.y;
  790. y = (y > max.y) ? max.y : y;
  791. y = (y < min.y) ? min.y : y;
  792. var z = value.z;
  793. z = (z > max.z) ? max.z : z;
  794. z = (z < min.z) ? min.z : z;
  795. return new Vector3(x, y, z);
  796. };
  797. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  798. var squared = amount * amount;
  799. var cubed = amount * squared;
  800. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  801. var part2 = (-2.0 * cubed) + (3.0 * squared);
  802. var part3 = (cubed - (2.0 * squared)) + amount;
  803. var part4 = cubed - squared;
  804. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  805. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  806. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  807. return new Vector3(x, y, z);
  808. };
  809. Vector3.Lerp = function (start, end, amount) {
  810. var x = start.x + ((end.x - start.x) * amount);
  811. var y = start.y + ((end.y - start.y) * amount);
  812. var z = start.z + ((end.z - start.z) * amount);
  813. return new Vector3(x, y, z);
  814. };
  815. Vector3.Dot = function (left, right) {
  816. return (left.x * right.x + left.y * right.y + left.z * right.z);
  817. };
  818. Vector3.Cross = function (left, right) {
  819. var result = Vector3.Zero();
  820. Vector3.CrossToRef(left, right, result);
  821. return result;
  822. };
  823. Vector3.CrossToRef = function (left, right, result) {
  824. result.x = left.y * right.z - left.z * right.y;
  825. result.y = left.z * right.x - left.x * right.z;
  826. result.z = left.x * right.y - left.y * right.x;
  827. };
  828. Vector3.Normalize = function (vector) {
  829. var result = Vector3.Zero();
  830. Vector3.NormalizeToRef(vector, result);
  831. return result;
  832. };
  833. Vector3.NormalizeToRef = function (vector, result) {
  834. result.copyFrom(vector);
  835. result.normalize();
  836. };
  837. Vector3.Project = function (vector, world, transform, viewport) {
  838. var cw = viewport.width;
  839. var ch = viewport.height;
  840. var cx = viewport.x;
  841. var cy = viewport.y;
  842. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  843. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  844. return Vector3.TransformCoordinates(vector, finalMatrix);
  845. };
  846. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  847. var matrix = world.multiply(transform);
  848. matrix.invert();
  849. source.x = source.x / viewportWidth * 2 - 1;
  850. source.y = -(source.y / viewportHeight * 2 - 1);
  851. var vector = Vector3.TransformCoordinates(source, matrix);
  852. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  853. if (MathTools.WithinEpsilon(num, 1.0)) {
  854. vector = vector.scale(1.0 / num);
  855. }
  856. return vector;
  857. };
  858. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  859. var matrix = world.multiply(view).multiply(projection);
  860. matrix.invert();
  861. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  862. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  863. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  864. if (MathTools.WithinEpsilon(num, 1.0)) {
  865. vector = vector.scale(1.0 / num);
  866. }
  867. return vector;
  868. };
  869. Vector3.Minimize = function (left, right) {
  870. var min = left.clone();
  871. min.MinimizeInPlace(right);
  872. return min;
  873. };
  874. Vector3.Maximize = function (left, right) {
  875. var max = left.clone();
  876. max.MaximizeInPlace(right);
  877. return max;
  878. };
  879. Vector3.Distance = function (value1, value2) {
  880. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  881. };
  882. Vector3.DistanceSquared = function (value1, value2) {
  883. var x = value1.x - value2.x;
  884. var y = value1.y - value2.y;
  885. var z = value1.z - value2.z;
  886. return (x * x) + (y * y) + (z * z);
  887. };
  888. Vector3.Center = function (value1, value2) {
  889. var center = value1.add(value2);
  890. center.scaleInPlace(0.5);
  891. return center;
  892. };
  893. /**
  894. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  895. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  896. * to something in order to rotate it from its local system to the given target system.
  897. */
  898. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  899. var rotation = Vector3.Zero();
  900. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  901. return rotation;
  902. };
  903. /**
  904. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  905. */
  906. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  907. var u = axis1.normalize();
  908. var w = axis3.normalize();
  909. // world axis
  910. var X = Axis.X;
  911. var Y = Axis.Y;
  912. // equation unknowns and vars
  913. var yaw = 0.0;
  914. var pitch = 0.0;
  915. var roll = 0.0;
  916. var x = 0.0;
  917. var y = 0.0;
  918. var z = 0.0;
  919. var t = 0.0;
  920. var sign = -1.0;
  921. var nbRevert = 0;
  922. var cross = Tmp.Vector3[0];
  923. var dot = 0.0;
  924. // step 1 : rotation around w
  925. // Rv3(u) = u1, and u1 belongs to plane xOz
  926. // Rv3(w) = w1 = w invariant
  927. var u1 = Tmp.Vector3[1];
  928. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  929. z = 1.0;
  930. }
  931. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  932. x = 1.0;
  933. }
  934. else {
  935. t = w.z / w.x;
  936. x = -t * Math.sqrt(1 / (1 + t * t));
  937. z = Math.sqrt(1 / (1 + t * t));
  938. }
  939. u1.x = x;
  940. u1.y = y;
  941. u1.z = z;
  942. u1.normalize();
  943. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  944. cross.normalize();
  945. if (Vector3.Dot(w, cross) < 0) {
  946. sign = 1.0;
  947. }
  948. dot = Vector3.Dot(u, u1);
  949. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  950. roll = Math.acos(dot) * sign;
  951. if (Vector3.Dot(u1, X) < 0) {
  952. roll = Math.PI + roll;
  953. u1 = u1.scaleInPlace(-1);
  954. nbRevert++;
  955. }
  956. // step 2 : rotate around u1
  957. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  958. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  959. var w2 = Tmp.Vector3[2];
  960. var v2 = Tmp.Vector3[3];
  961. x = 0.0;
  962. y = 0.0;
  963. z = 0.0;
  964. sign = -1.0;
  965. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  966. x = 1.0;
  967. }
  968. else {
  969. t = u1.z / u1.x;
  970. x = -t * Math.sqrt(1 / (1 + t * t));
  971. z = Math.sqrt(1 / (1 + t * t));
  972. }
  973. w2.x = x;
  974. w2.y = y;
  975. w2.z = z;
  976. w2.normalize();
  977. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  978. v2.normalize();
  979. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  980. cross.normalize();
  981. if (Vector3.Dot(u1, cross) < 0) {
  982. sign = 1.0;
  983. }
  984. dot = Vector3.Dot(w, w2);
  985. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  986. pitch = Math.acos(dot) * sign;
  987. if (Vector3.Dot(v2, Y) < 0) {
  988. pitch = Math.PI + pitch;
  989. nbRevert++;
  990. }
  991. // step 3 : rotate around v2
  992. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  993. sign = -1.0;
  994. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  995. cross.normalize();
  996. if (Vector3.Dot(cross, Y) < 0) {
  997. sign = 1.0;
  998. }
  999. dot = Vector3.Dot(u1, X);
  1000. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1001. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1002. if (dot < 0 && nbRevert < 2) {
  1003. yaw = Math.PI + yaw;
  1004. }
  1005. ref.x = pitch;
  1006. ref.y = yaw;
  1007. ref.z = roll;
  1008. };
  1009. return Vector3;
  1010. })();
  1011. BABYLON.Vector3 = Vector3;
  1012. //Vector4 class created for EulerAngle class conversion to Quaternion
  1013. var Vector4 = (function () {
  1014. function Vector4(x, y, z, w) {
  1015. this.x = x;
  1016. this.y = y;
  1017. this.z = z;
  1018. this.w = w;
  1019. }
  1020. Vector4.prototype.toString = function () {
  1021. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  1022. };
  1023. // Operators
  1024. Vector4.prototype.asArray = function () {
  1025. var result = [];
  1026. this.toArray(result, 0);
  1027. return result;
  1028. };
  1029. Vector4.prototype.toArray = function (array, index) {
  1030. if (index === undefined) {
  1031. index = 0;
  1032. }
  1033. array[index] = this.x;
  1034. array[index + 1] = this.y;
  1035. array[index + 2] = this.z;
  1036. array[index + 3] = this.w;
  1037. return this;
  1038. };
  1039. Vector4.prototype.addInPlace = function (otherVector) {
  1040. this.x += otherVector.x;
  1041. this.y += otherVector.y;
  1042. this.z += otherVector.z;
  1043. this.w += otherVector.w;
  1044. return this;
  1045. };
  1046. Vector4.prototype.add = function (otherVector) {
  1047. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1048. };
  1049. Vector4.prototype.addToRef = function (otherVector, result) {
  1050. result.x = this.x + otherVector.x;
  1051. result.y = this.y + otherVector.y;
  1052. result.z = this.z + otherVector.z;
  1053. result.w = this.w + otherVector.w;
  1054. return this;
  1055. };
  1056. Vector4.prototype.subtractInPlace = function (otherVector) {
  1057. this.x -= otherVector.x;
  1058. this.y -= otherVector.y;
  1059. this.z -= otherVector.z;
  1060. this.w -= otherVector.w;
  1061. return this;
  1062. };
  1063. Vector4.prototype.subtract = function (otherVector) {
  1064. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1065. };
  1066. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1067. result.x = this.x - otherVector.x;
  1068. result.y = this.y - otherVector.y;
  1069. result.z = this.z - otherVector.z;
  1070. result.w = this.w - otherVector.w;
  1071. return this;
  1072. };
  1073. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1074. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1075. };
  1076. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1077. result.x = this.x - x;
  1078. result.y = this.y - y;
  1079. result.z = this.z - z;
  1080. result.w = this.w - w;
  1081. return this;
  1082. };
  1083. Vector4.prototype.negate = function () {
  1084. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1085. };
  1086. Vector4.prototype.scaleInPlace = function (scale) {
  1087. this.x *= scale;
  1088. this.y *= scale;
  1089. this.z *= scale;
  1090. this.w *= scale;
  1091. return this;
  1092. };
  1093. Vector4.prototype.scale = function (scale) {
  1094. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1095. };
  1096. Vector4.prototype.scaleToRef = function (scale, result) {
  1097. result.x = this.x * scale;
  1098. result.y = this.y * scale;
  1099. result.z = this.z * scale;
  1100. result.w = this.w * scale;
  1101. };
  1102. Vector4.prototype.equals = function (otherVector) {
  1103. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1104. };
  1105. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1106. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1107. return otherVector
  1108. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1109. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1110. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1111. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1112. };
  1113. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1114. return this.x === x && this.y === y && this.z === z && this.w === w;
  1115. };
  1116. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1117. this.x *= otherVector.x;
  1118. this.y *= otherVector.y;
  1119. this.z *= otherVector.z;
  1120. this.w *= otherVector.w;
  1121. return this;
  1122. };
  1123. Vector4.prototype.multiply = function (otherVector) {
  1124. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1125. };
  1126. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1127. result.x = this.x * otherVector.x;
  1128. result.y = this.y * otherVector.y;
  1129. result.z = this.z * otherVector.z;
  1130. result.w = this.w * otherVector.w;
  1131. return this;
  1132. };
  1133. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1134. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1135. };
  1136. Vector4.prototype.divide = function (otherVector) {
  1137. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1138. };
  1139. Vector4.prototype.divideToRef = function (otherVector, result) {
  1140. result.x = this.x / otherVector.x;
  1141. result.y = this.y / otherVector.y;
  1142. result.z = this.z / otherVector.z;
  1143. result.w = this.w / otherVector.w;
  1144. return this;
  1145. };
  1146. Vector4.prototype.MinimizeInPlace = function (other) {
  1147. if (other.x < this.x)
  1148. this.x = other.x;
  1149. if (other.y < this.y)
  1150. this.y = other.y;
  1151. if (other.z < this.z)
  1152. this.z = other.z;
  1153. if (other.w < this.w)
  1154. this.w = other.w;
  1155. return this;
  1156. };
  1157. Vector4.prototype.MaximizeInPlace = function (other) {
  1158. if (other.x > this.x)
  1159. this.x = other.x;
  1160. if (other.y > this.y)
  1161. this.y = other.y;
  1162. if (other.z > this.z)
  1163. this.z = other.z;
  1164. if (other.w > this.w)
  1165. this.w = other.w;
  1166. return this;
  1167. };
  1168. // Properties
  1169. Vector4.prototype.length = function () {
  1170. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1171. };
  1172. Vector4.prototype.lengthSquared = function () {
  1173. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1174. };
  1175. // Methods
  1176. Vector4.prototype.normalize = function () {
  1177. var len = this.length();
  1178. if (len === 0)
  1179. return this;
  1180. var num = 1.0 / len;
  1181. this.x *= num;
  1182. this.y *= num;
  1183. this.z *= num;
  1184. this.w *= num;
  1185. return this;
  1186. };
  1187. Vector4.prototype.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 Quaternion = (function () {
  1273. function Quaternion(x, y, z, w) {
  1274. if (x === void 0) { x = 0; }
  1275. if (y === void 0) { y = 0; }
  1276. if (z === void 0) { z = 0; }
  1277. if (w === void 0) { w = 1; }
  1278. this.x = x;
  1279. this.y = y;
  1280. this.z = z;
  1281. this.w = w;
  1282. }
  1283. Quaternion.prototype.toString = function () {
  1284. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1285. };
  1286. Quaternion.prototype.asArray = function () {
  1287. return [this.x, this.y, this.z, this.w];
  1288. };
  1289. Quaternion.prototype.equals = function (otherQuaternion) {
  1290. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1291. };
  1292. Quaternion.prototype.clone = function () {
  1293. return new Quaternion(this.x, this.y, this.z, this.w);
  1294. };
  1295. Quaternion.prototype.copyFrom = function (other) {
  1296. this.x = other.x;
  1297. this.y = other.y;
  1298. this.z = other.z;
  1299. this.w = other.w;
  1300. return this;
  1301. };
  1302. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1303. this.x = x;
  1304. this.y = y;
  1305. this.z = z;
  1306. this.w = w;
  1307. return this;
  1308. };
  1309. Quaternion.prototype.add = function (other) {
  1310. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1311. };
  1312. Quaternion.prototype.subtract = function (other) {
  1313. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1314. };
  1315. Quaternion.prototype.scale = function (value) {
  1316. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1317. };
  1318. Quaternion.prototype.multiply = function (q1) {
  1319. var result = new Quaternion(0, 0, 0, 1.0);
  1320. this.multiplyToRef(q1, result);
  1321. return result;
  1322. };
  1323. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1324. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1325. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1326. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1327. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1328. result.copyFromFloats(x, y, z, w);
  1329. return this;
  1330. };
  1331. Quaternion.prototype.multiplyInPlace = function (q1) {
  1332. this.multiplyToRef(q1, this);
  1333. return this;
  1334. };
  1335. Quaternion.prototype.conjugateToRef = function (ref) {
  1336. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1337. return this;
  1338. };
  1339. Quaternion.prototype.conjugateInPlace = function () {
  1340. this.x *= -1;
  1341. this.y *= -1;
  1342. this.z *= -1;
  1343. return this;
  1344. };
  1345. Quaternion.prototype.conjugate = function () {
  1346. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1347. return result;
  1348. };
  1349. Quaternion.prototype.length = function () {
  1350. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1351. };
  1352. Quaternion.prototype.normalize = function () {
  1353. var length = 1.0 / this.length();
  1354. this.x *= length;
  1355. this.y *= length;
  1356. this.z *= length;
  1357. this.w *= length;
  1358. return this;
  1359. };
  1360. Quaternion.prototype.toEulerAngles = function (order) {
  1361. if (order === void 0) { order = "YZX"; }
  1362. var result = Vector3.Zero();
  1363. this.toEulerAnglesToRef(result, order);
  1364. return result;
  1365. };
  1366. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1367. if (order === void 0) { order = "YZX"; }
  1368. var heading, attitude, bank;
  1369. var x = this.x, y = this.y, z = this.z, w = this.w;
  1370. switch (order) {
  1371. case "YZX":
  1372. var test = x * y + z * w;
  1373. if (test > 0.499) {
  1374. heading = 2 * Math.atan2(x, w);
  1375. attitude = Math.PI / 2;
  1376. bank = 0;
  1377. }
  1378. if (test < -0.499) {
  1379. heading = -2 * Math.atan2(x, w);
  1380. attitude = -Math.PI / 2;
  1381. bank = 0;
  1382. }
  1383. if (isNaN(heading)) {
  1384. var sqx = x * x;
  1385. var sqy = y * y;
  1386. var sqz = z * z;
  1387. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1388. attitude = Math.asin(2 * test); // attitude
  1389. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1390. }
  1391. break;
  1392. default:
  1393. throw new Error("Euler order " + order + " not supported yet.");
  1394. }
  1395. result.y = heading;
  1396. result.z = attitude;
  1397. result.x = bank;
  1398. return this;
  1399. };
  1400. ;
  1401. Quaternion.prototype.toRotationMatrix = function (result) {
  1402. var xx = this.x * this.x;
  1403. var yy = this.y * this.y;
  1404. var zz = this.z * this.z;
  1405. var xy = this.x * this.y;
  1406. var zw = this.z * this.w;
  1407. var zx = this.z * this.x;
  1408. var yw = this.y * this.w;
  1409. var yz = this.y * this.z;
  1410. var xw = this.x * this.w;
  1411. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1412. result.m[1] = 2.0 * (xy + zw);
  1413. result.m[2] = 2.0 * (zx - yw);
  1414. result.m[3] = 0;
  1415. result.m[4] = 2.0 * (xy - zw);
  1416. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1417. result.m[6] = 2.0 * (yz + xw);
  1418. result.m[7] = 0;
  1419. result.m[8] = 2.0 * (zx + yw);
  1420. result.m[9] = 2.0 * (yz - xw);
  1421. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1422. result.m[11] = 0;
  1423. result.m[12] = 0;
  1424. result.m[13] = 0;
  1425. result.m[14] = 0;
  1426. result.m[15] = 1.0;
  1427. return this;
  1428. };
  1429. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1430. Quaternion.FromRotationMatrixToRef(matrix, this);
  1431. return this;
  1432. };
  1433. // Statics
  1434. Quaternion.FromRotationMatrix = function (matrix) {
  1435. var result = new Quaternion();
  1436. Quaternion.FromRotationMatrixToRef(matrix, result);
  1437. return result;
  1438. };
  1439. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1440. var data = matrix.m;
  1441. var m11 = data[0], m12 = data[4], m13 = data[8];
  1442. var m21 = data[1], m22 = data[5], m23 = data[9];
  1443. var m31 = data[2], m32 = data[6], m33 = data[10];
  1444. var trace = m11 + m22 + m33;
  1445. var s;
  1446. if (trace > 0) {
  1447. s = 0.5 / Math.sqrt(trace + 1.0);
  1448. result.w = 0.25 / s;
  1449. result.x = (m32 - m23) * s;
  1450. result.y = (m13 - m31) * s;
  1451. result.z = (m21 - m12) * s;
  1452. }
  1453. else if (m11 > m22 && m11 > m33) {
  1454. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1455. result.w = (m32 - m23) / s;
  1456. result.x = 0.25 * s;
  1457. result.y = (m12 + m21) / s;
  1458. result.z = (m13 + m31) / s;
  1459. }
  1460. else if (m22 > m33) {
  1461. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1462. result.w = (m13 - m31) / s;
  1463. result.x = (m12 + m21) / s;
  1464. result.y = 0.25 * s;
  1465. result.z = (m23 + m32) / s;
  1466. }
  1467. else {
  1468. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1469. result.w = (m21 - m12) / s;
  1470. result.x = (m13 + m31) / s;
  1471. result.y = (m23 + m32) / s;
  1472. result.z = 0.25 * s;
  1473. }
  1474. };
  1475. Quaternion.Inverse = function (q) {
  1476. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1477. };
  1478. Quaternion.Identity = function () {
  1479. return new Quaternion(0, 0, 0, 1);
  1480. };
  1481. Quaternion.RotationAxis = function (axis, angle) {
  1482. var result = new Quaternion();
  1483. var sin = Math.sin(angle / 2);
  1484. axis.normalize();
  1485. result.w = Math.cos(angle / 2);
  1486. result.x = axis.x * sin;
  1487. result.y = axis.y * sin;
  1488. result.z = axis.z * sin;
  1489. return result;
  1490. };
  1491. Quaternion.FromArray = function (array, offset) {
  1492. if (!offset) {
  1493. offset = 0;
  1494. }
  1495. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1496. };
  1497. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1498. var result = new Quaternion();
  1499. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1500. return result;
  1501. };
  1502. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1503. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1504. var halfRoll = roll * 0.5;
  1505. var halfPitch = pitch * 0.5;
  1506. var halfYaw = yaw * 0.5;
  1507. var sinRoll = Math.sin(halfRoll);
  1508. var cosRoll = Math.cos(halfRoll);
  1509. var sinPitch = Math.sin(halfPitch);
  1510. var cosPitch = Math.cos(halfPitch);
  1511. var sinYaw = Math.sin(halfYaw);
  1512. var cosYaw = Math.cos(halfYaw);
  1513. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1514. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1515. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1516. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1517. };
  1518. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1519. var result = new Quaternion();
  1520. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1521. return result;
  1522. };
  1523. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1524. // Produces a quaternion from Euler angles in the z-x-z orientation
  1525. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1526. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1527. var halfBeta = beta * 0.5;
  1528. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1529. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1530. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1531. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1532. };
  1533. Quaternion.Slerp = function (left, right, amount) {
  1534. var num2;
  1535. var num3;
  1536. var num = amount;
  1537. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1538. var flag = false;
  1539. if (num4 < 0) {
  1540. flag = true;
  1541. num4 = -num4;
  1542. }
  1543. if (num4 > 0.999999) {
  1544. num3 = 1 - num;
  1545. num2 = flag ? -num : num;
  1546. }
  1547. else {
  1548. var num5 = Math.acos(num4);
  1549. var num6 = (1.0 / Math.sin(num5));
  1550. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1551. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1552. }
  1553. 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));
  1554. };
  1555. return Quaternion;
  1556. })();
  1557. BABYLON.Quaternion = Quaternion;
  1558. var Matrix = (function () {
  1559. function Matrix() {
  1560. this.m = new Float32Array(16);
  1561. }
  1562. // Properties
  1563. Matrix.prototype.isIdentity = function () {
  1564. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1565. return false;
  1566. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1567. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1568. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1569. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1570. return false;
  1571. return true;
  1572. };
  1573. Matrix.prototype.determinant = function () {
  1574. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1575. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1576. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1577. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1578. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1579. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1580. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1581. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1582. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1583. };
  1584. // Methods
  1585. Matrix.prototype.toArray = function () {
  1586. return this.m;
  1587. };
  1588. Matrix.prototype.asArray = function () {
  1589. return this.toArray();
  1590. };
  1591. Matrix.prototype.invert = function () {
  1592. this.invertToRef(this);
  1593. return this;
  1594. };
  1595. Matrix.prototype.reset = function () {
  1596. for (var index = 0; index < 16; index++) {
  1597. this.m[index] = 0;
  1598. }
  1599. return this;
  1600. };
  1601. Matrix.prototype.add = function (other) {
  1602. var result = new Matrix();
  1603. this.addToRef(other, result);
  1604. return result;
  1605. };
  1606. Matrix.prototype.addToRef = function (other, result) {
  1607. for (var index = 0; index < 16; index++) {
  1608. result.m[index] = this.m[index] + other.m[index];
  1609. }
  1610. return this;
  1611. };
  1612. Matrix.prototype.addToSelf = function (other) {
  1613. for (var index = 0; index < 16; index++) {
  1614. this.m[index] += other.m[index];
  1615. }
  1616. return this;
  1617. };
  1618. Matrix.prototype.invertToRef = function (other) {
  1619. var l1 = this.m[0];
  1620. var l2 = this.m[1];
  1621. var l3 = this.m[2];
  1622. var l4 = this.m[3];
  1623. var l5 = this.m[4];
  1624. var l6 = this.m[5];
  1625. var l7 = this.m[6];
  1626. var l8 = this.m[7];
  1627. var l9 = this.m[8];
  1628. var l10 = this.m[9];
  1629. var l11 = this.m[10];
  1630. var l12 = this.m[11];
  1631. var l13 = this.m[12];
  1632. var l14 = this.m[13];
  1633. var l15 = this.m[14];
  1634. var l16 = this.m[15];
  1635. var l17 = (l11 * l16) - (l12 * l15);
  1636. var l18 = (l10 * l16) - (l12 * l14);
  1637. var l19 = (l10 * l15) - (l11 * l14);
  1638. var l20 = (l9 * l16) - (l12 * l13);
  1639. var l21 = (l9 * l15) - (l11 * l13);
  1640. var l22 = (l9 * l14) - (l10 * l13);
  1641. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1642. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1643. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1644. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1645. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1646. var l28 = (l7 * l16) - (l8 * l15);
  1647. var l29 = (l6 * l16) - (l8 * l14);
  1648. var l30 = (l6 * l15) - (l7 * l14);
  1649. var l31 = (l5 * l16) - (l8 * l13);
  1650. var l32 = (l5 * l15) - (l7 * l13);
  1651. var l33 = (l5 * l14) - (l6 * l13);
  1652. var l34 = (l7 * l12) - (l8 * l11);
  1653. var l35 = (l6 * l12) - (l8 * l10);
  1654. var l36 = (l6 * l11) - (l7 * l10);
  1655. var l37 = (l5 * l12) - (l8 * l9);
  1656. var l38 = (l5 * l11) - (l7 * l9);
  1657. var l39 = (l5 * l10) - (l6 * l9);
  1658. other.m[0] = l23 * l27;
  1659. other.m[4] = l24 * l27;
  1660. other.m[8] = l25 * l27;
  1661. other.m[12] = l26 * l27;
  1662. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1663. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1664. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1665. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1666. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1667. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1668. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1669. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1670. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1671. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1672. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1673. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1674. return this;
  1675. };
  1676. Matrix.prototype.setTranslation = function (vector3) {
  1677. this.m[12] = vector3.x;
  1678. this.m[13] = vector3.y;
  1679. this.m[14] = vector3.z;
  1680. return this;
  1681. };
  1682. Matrix.prototype.getTranslation = function () {
  1683. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1684. };
  1685. Matrix.prototype.multiply = function (other) {
  1686. var result = new Matrix();
  1687. this.multiplyToRef(other, result);
  1688. return result;
  1689. };
  1690. Matrix.prototype.copyFrom = function (other) {
  1691. for (var index = 0; index < 16; index++) {
  1692. this.m[index] = other.m[index];
  1693. }
  1694. return this;
  1695. };
  1696. Matrix.prototype.copyToArray = function (array, offset) {
  1697. if (offset === void 0) { offset = 0; }
  1698. for (var index = 0; index < 16; index++) {
  1699. array[offset + index] = this.m[index];
  1700. }
  1701. return this;
  1702. };
  1703. Matrix.prototype.multiplyToRef = function (other, result) {
  1704. this.multiplyToArray(other, result.m, 0);
  1705. return this;
  1706. };
  1707. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1708. var tm0 = this.m[0];
  1709. var tm1 = this.m[1];
  1710. var tm2 = this.m[2];
  1711. var tm3 = this.m[3];
  1712. var tm4 = this.m[4];
  1713. var tm5 = this.m[5];
  1714. var tm6 = this.m[6];
  1715. var tm7 = this.m[7];
  1716. var tm8 = this.m[8];
  1717. var tm9 = this.m[9];
  1718. var tm10 = this.m[10];
  1719. var tm11 = this.m[11];
  1720. var tm12 = this.m[12];
  1721. var tm13 = this.m[13];
  1722. var tm14 = this.m[14];
  1723. var tm15 = this.m[15];
  1724. var om0 = other.m[0];
  1725. var om1 = other.m[1];
  1726. var om2 = other.m[2];
  1727. var om3 = other.m[3];
  1728. var om4 = other.m[4];
  1729. var om5 = other.m[5];
  1730. var om6 = other.m[6];
  1731. var om7 = other.m[7];
  1732. var om8 = other.m[8];
  1733. var om9 = other.m[9];
  1734. var om10 = other.m[10];
  1735. var om11 = other.m[11];
  1736. var om12 = other.m[12];
  1737. var om13 = other.m[13];
  1738. var om14 = other.m[14];
  1739. var om15 = other.m[15];
  1740. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1741. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1742. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1743. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1744. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1745. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1746. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1747. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1748. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1749. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1750. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1751. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1752. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1753. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1754. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1755. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1756. return this;
  1757. };
  1758. Matrix.prototype.equals = function (value) {
  1759. return value &&
  1760. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1761. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1762. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1763. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1764. };
  1765. Matrix.prototype.clone = function () {
  1766. 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]);
  1767. };
  1768. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1769. translation.x = this.m[12];
  1770. translation.y = this.m[13];
  1771. translation.z = this.m[14];
  1772. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1773. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1774. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1775. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1776. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1777. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1778. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1779. rotation.x = 0;
  1780. rotation.y = 0;
  1781. rotation.z = 0;
  1782. rotation.w = 1;
  1783. return false;
  1784. }
  1785. 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);
  1786. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1787. return true;
  1788. };
  1789. // Statics
  1790. Matrix.FromArray = function (array, offset) {
  1791. var result = new Matrix();
  1792. if (!offset) {
  1793. offset = 0;
  1794. }
  1795. Matrix.FromArrayToRef(array, offset, result);
  1796. return result;
  1797. };
  1798. Matrix.FromArrayToRef = function (array, offset, result) {
  1799. for (var index = 0; index < 16; index++) {
  1800. result.m[index] = array[index + offset];
  1801. }
  1802. };
  1803. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1804. for (var index = 0; index < 16; index++) {
  1805. result.m[index] = array[index + offset] * scale;
  1806. }
  1807. };
  1808. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1809. result.m[0] = initialM11;
  1810. result.m[1] = initialM12;
  1811. result.m[2] = initialM13;
  1812. result.m[3] = initialM14;
  1813. result.m[4] = initialM21;
  1814. result.m[5] = initialM22;
  1815. result.m[6] = initialM23;
  1816. result.m[7] = initialM24;
  1817. result.m[8] = initialM31;
  1818. result.m[9] = initialM32;
  1819. result.m[10] = initialM33;
  1820. result.m[11] = initialM34;
  1821. result.m[12] = initialM41;
  1822. result.m[13] = initialM42;
  1823. result.m[14] = initialM43;
  1824. result.m[15] = initialM44;
  1825. };
  1826. Matrix.prototype.getRow = function (index) {
  1827. if (index < 0 || index > 3) {
  1828. return null;
  1829. }
  1830. var i = index * 4;
  1831. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  1832. };
  1833. Matrix.prototype.setRow = function (index, row) {
  1834. if (index < 0 || index > 3) {
  1835. return this;
  1836. }
  1837. var i = index * 4;
  1838. this.m[i + 0] = row.x;
  1839. this.m[i + 1] = row.y;
  1840. this.m[i + 2] = row.z;
  1841. this.m[i + 3] = row.w;
  1842. return this;
  1843. };
  1844. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1845. var result = new Matrix();
  1846. result.m[0] = initialM11;
  1847. result.m[1] = initialM12;
  1848. result.m[2] = initialM13;
  1849. result.m[3] = initialM14;
  1850. result.m[4] = initialM21;
  1851. result.m[5] = initialM22;
  1852. result.m[6] = initialM23;
  1853. result.m[7] = initialM24;
  1854. result.m[8] = initialM31;
  1855. result.m[9] = initialM32;
  1856. result.m[10] = initialM33;
  1857. result.m[11] = initialM34;
  1858. result.m[12] = initialM41;
  1859. result.m[13] = initialM42;
  1860. result.m[14] = initialM43;
  1861. result.m[15] = initialM44;
  1862. return result;
  1863. };
  1864. Matrix.Compose = function (scale, rotation, translation) {
  1865. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1866. var rotationMatrix = Matrix.Identity();
  1867. rotation.toRotationMatrix(rotationMatrix);
  1868. result = result.multiply(rotationMatrix);
  1869. result.setTranslation(translation);
  1870. return result;
  1871. };
  1872. Matrix.Identity = function () {
  1873. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1874. };
  1875. Matrix.IdentityToRef = function (result) {
  1876. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1877. };
  1878. Matrix.Zero = function () {
  1879. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1880. };
  1881. Matrix.RotationX = function (angle) {
  1882. var result = new Matrix();
  1883. Matrix.RotationXToRef(angle, result);
  1884. return result;
  1885. };
  1886. Matrix.Invert = function (source) {
  1887. var result = new Matrix();
  1888. source.invertToRef(result);
  1889. return result;
  1890. };
  1891. Matrix.RotationXToRef = function (angle, result) {
  1892. var s = Math.sin(angle);
  1893. var c = Math.cos(angle);
  1894. result.m[0] = 1.0;
  1895. result.m[15] = 1.0;
  1896. result.m[5] = c;
  1897. result.m[10] = c;
  1898. result.m[9] = -s;
  1899. result.m[6] = s;
  1900. result.m[1] = 0;
  1901. result.m[2] = 0;
  1902. result.m[3] = 0;
  1903. result.m[4] = 0;
  1904. result.m[7] = 0;
  1905. result.m[8] = 0;
  1906. result.m[11] = 0;
  1907. result.m[12] = 0;
  1908. result.m[13] = 0;
  1909. result.m[14] = 0;
  1910. };
  1911. Matrix.RotationY = function (angle) {
  1912. var result = new Matrix();
  1913. Matrix.RotationYToRef(angle, result);
  1914. return result;
  1915. };
  1916. Matrix.RotationYToRef = function (angle, result) {
  1917. var s = Math.sin(angle);
  1918. var c = Math.cos(angle);
  1919. result.m[5] = 1.0;
  1920. result.m[15] = 1.0;
  1921. result.m[0] = c;
  1922. result.m[2] = -s;
  1923. result.m[8] = s;
  1924. result.m[10] = c;
  1925. result.m[1] = 0;
  1926. result.m[3] = 0;
  1927. result.m[4] = 0;
  1928. result.m[6] = 0;
  1929. result.m[7] = 0;
  1930. result.m[9] = 0;
  1931. result.m[11] = 0;
  1932. result.m[12] = 0;
  1933. result.m[13] = 0;
  1934. result.m[14] = 0;
  1935. };
  1936. Matrix.RotationZ = function (angle) {
  1937. var result = new Matrix();
  1938. Matrix.RotationZToRef(angle, result);
  1939. return result;
  1940. };
  1941. Matrix.RotationZToRef = function (angle, result) {
  1942. var s = Math.sin(angle);
  1943. var c = Math.cos(angle);
  1944. result.m[10] = 1.0;
  1945. result.m[15] = 1.0;
  1946. result.m[0] = c;
  1947. result.m[1] = s;
  1948. result.m[4] = -s;
  1949. result.m[5] = c;
  1950. result.m[2] = 0;
  1951. result.m[3] = 0;
  1952. result.m[6] = 0;
  1953. result.m[7] = 0;
  1954. result.m[8] = 0;
  1955. result.m[9] = 0;
  1956. result.m[11] = 0;
  1957. result.m[12] = 0;
  1958. result.m[13] = 0;
  1959. result.m[14] = 0;
  1960. };
  1961. Matrix.RotationAxis = function (axis, angle) {
  1962. var result = Matrix.Zero();
  1963. Matrix.RotationAxisToRef(axis, angle, result);
  1964. return result;
  1965. };
  1966. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1967. var s = Math.sin(-angle);
  1968. var c = Math.cos(-angle);
  1969. var c1 = 1 - c;
  1970. axis.normalize();
  1971. result.m[0] = (axis.x * axis.x) * c1 + c;
  1972. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1973. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1974. result.m[3] = 0.0;
  1975. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1976. result.m[5] = (axis.y * axis.y) * c1 + c;
  1977. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1978. result.m[7] = 0.0;
  1979. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1980. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1981. result.m[10] = (axis.z * axis.z) * c1 + c;
  1982. result.m[11] = 0.0;
  1983. result.m[15] = 1.0;
  1984. };
  1985. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1986. var result = new Matrix();
  1987. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1988. return result;
  1989. };
  1990. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1991. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1992. this._tempQuaternion.toRotationMatrix(result);
  1993. };
  1994. Matrix.Scaling = function (x, y, z) {
  1995. var result = Matrix.Zero();
  1996. Matrix.ScalingToRef(x, y, z, result);
  1997. return result;
  1998. };
  1999. Matrix.ScalingToRef = function (x, y, z, result) {
  2000. result.m[0] = x;
  2001. result.m[1] = 0;
  2002. result.m[2] = 0;
  2003. result.m[3] = 0;
  2004. result.m[4] = 0;
  2005. result.m[5] = y;
  2006. result.m[6] = 0;
  2007. result.m[7] = 0;
  2008. result.m[8] = 0;
  2009. result.m[9] = 0;
  2010. result.m[10] = z;
  2011. result.m[11] = 0;
  2012. result.m[12] = 0;
  2013. result.m[13] = 0;
  2014. result.m[14] = 0;
  2015. result.m[15] = 1.0;
  2016. };
  2017. Matrix.Translation = function (x, y, z) {
  2018. var result = Matrix.Identity();
  2019. Matrix.TranslationToRef(x, y, z, result);
  2020. return result;
  2021. };
  2022. Matrix.TranslationToRef = function (x, y, z, result) {
  2023. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2024. };
  2025. Matrix.Lerp = function (startValue, endValue, gradient) {
  2026. var startScale = new Vector3(0, 0, 0);
  2027. var startRotation = new Quaternion();
  2028. var startTranslation = new Vector3(0, 0, 0);
  2029. startValue.decompose(startScale, startRotation, startTranslation);
  2030. var endScale = new Vector3(0, 0, 0);
  2031. var endRotation = new Quaternion();
  2032. var endTranslation = new Vector3(0, 0, 0);
  2033. endValue.decompose(endScale, endRotation, endTranslation);
  2034. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2035. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2036. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2037. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2038. };
  2039. Matrix.LookAtLH = function (eye, target, up) {
  2040. var result = Matrix.Zero();
  2041. Matrix.LookAtLHToRef(eye, target, up, result);
  2042. return result;
  2043. };
  2044. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2045. // Z axis
  2046. target.subtractToRef(eye, this._zAxis);
  2047. this._zAxis.normalize();
  2048. // X axis
  2049. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2050. if (this._xAxis.lengthSquared() === 0) {
  2051. this._xAxis.x = 1.0;
  2052. }
  2053. else {
  2054. this._xAxis.normalize();
  2055. }
  2056. // Y axis
  2057. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2058. this._yAxis.normalize();
  2059. // Eye angles
  2060. var ex = -Vector3.Dot(this._xAxis, eye);
  2061. var ey = -Vector3.Dot(this._yAxis, eye);
  2062. var ez = -Vector3.Dot(this._zAxis, eye);
  2063. 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);
  2064. };
  2065. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2066. var matrix = Matrix.Zero();
  2067. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2068. return matrix;
  2069. };
  2070. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2071. var hw = 2.0 / width;
  2072. var hh = 2.0 / height;
  2073. var id = 1.0 / (zfar - znear);
  2074. var nid = znear / (znear - zfar);
  2075. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2076. };
  2077. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2078. var matrix = Matrix.Zero();
  2079. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2080. return matrix;
  2081. };
  2082. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2083. result.m[0] = 2.0 / (right - left);
  2084. result.m[1] = result.m[2] = result.m[3] = 0;
  2085. result.m[5] = 2.0 / (top - bottom);
  2086. result.m[4] = result.m[6] = result.m[7] = 0;
  2087. result.m[10] = -1.0 / (znear - zfar);
  2088. result.m[8] = result.m[9] = result.m[11] = 0;
  2089. result.m[12] = (left + right) / (left - right);
  2090. result.m[13] = (top + bottom) / (bottom - top);
  2091. result.m[14] = znear / (znear - zfar);
  2092. result.m[15] = 1.0;
  2093. };
  2094. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2095. var matrix = Matrix.Zero();
  2096. matrix.m[0] = (2.0 * znear) / width;
  2097. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2098. matrix.m[5] = (2.0 * znear) / height;
  2099. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2100. matrix.m[10] = -zfar / (znear - zfar);
  2101. matrix.m[8] = matrix.m[9] = 0.0;
  2102. matrix.m[11] = 1.0;
  2103. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2104. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2105. return matrix;
  2106. };
  2107. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2108. var matrix = Matrix.Zero();
  2109. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2110. return matrix;
  2111. };
  2112. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2113. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2114. var tan = 1.0 / (Math.tan(fov * 0.5));
  2115. if (isVerticalFovFixed) {
  2116. result.m[0] = tan / aspect;
  2117. }
  2118. else {
  2119. result.m[0] = tan;
  2120. }
  2121. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2122. if (isVerticalFovFixed) {
  2123. result.m[5] = tan;
  2124. }
  2125. else {
  2126. result.m[5] = tan * aspect;
  2127. }
  2128. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2129. result.m[8] = result.m[9] = 0.0;
  2130. result.m[10] = -zfar / (znear - zfar);
  2131. result.m[11] = 1.0;
  2132. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2133. result.m[14] = (znear * zfar) / (znear - zfar);
  2134. };
  2135. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2136. var cw = viewport.width;
  2137. var ch = viewport.height;
  2138. var cx = viewport.x;
  2139. var cy = viewport.y;
  2140. 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);
  2141. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2142. };
  2143. Matrix.GetAsMatrix2x2 = function (matrix) {
  2144. return new Float32Array([
  2145. matrix.m[0], matrix.m[1],
  2146. matrix.m[4], matrix.m[5]
  2147. ]);
  2148. };
  2149. Matrix.GetAsMatrix3x3 = function (matrix) {
  2150. return new Float32Array([
  2151. matrix.m[0], matrix.m[1], matrix.m[2],
  2152. matrix.m[4], matrix.m[5], matrix.m[6],
  2153. matrix.m[8], matrix.m[9], matrix.m[10]
  2154. ]);
  2155. };
  2156. Matrix.Transpose = function (matrix) {
  2157. var result = new Matrix();
  2158. result.m[0] = matrix.m[0];
  2159. result.m[1] = matrix.m[4];
  2160. result.m[2] = matrix.m[8];
  2161. result.m[3] = matrix.m[12];
  2162. result.m[4] = matrix.m[1];
  2163. result.m[5] = matrix.m[5];
  2164. result.m[6] = matrix.m[9];
  2165. result.m[7] = matrix.m[13];
  2166. result.m[8] = matrix.m[2];
  2167. result.m[9] = matrix.m[6];
  2168. result.m[10] = matrix.m[10];
  2169. result.m[11] = matrix.m[14];
  2170. result.m[12] = matrix.m[3];
  2171. result.m[13] = matrix.m[7];
  2172. result.m[14] = matrix.m[11];
  2173. result.m[15] = matrix.m[15];
  2174. return result;
  2175. };
  2176. Matrix.Reflection = function (plane) {
  2177. var matrix = new Matrix();
  2178. Matrix.ReflectionToRef(plane, matrix);
  2179. return matrix;
  2180. };
  2181. Matrix.ReflectionToRef = function (plane, result) {
  2182. plane.normalize();
  2183. var x = plane.normal.x;
  2184. var y = plane.normal.y;
  2185. var z = plane.normal.z;
  2186. var temp = -2 * x;
  2187. var temp2 = -2 * y;
  2188. var temp3 = -2 * z;
  2189. result.m[0] = (temp * x) + 1;
  2190. result.m[1] = temp2 * x;
  2191. result.m[2] = temp3 * x;
  2192. result.m[3] = 0.0;
  2193. result.m[4] = temp * y;
  2194. result.m[5] = (temp2 * y) + 1;
  2195. result.m[6] = temp3 * y;
  2196. result.m[7] = 0.0;
  2197. result.m[8] = temp * z;
  2198. result.m[9] = temp2 * z;
  2199. result.m[10] = (temp3 * z) + 1;
  2200. result.m[11] = 0.0;
  2201. result.m[12] = temp * plane.d;
  2202. result.m[13] = temp2 * plane.d;
  2203. result.m[14] = temp3 * plane.d;
  2204. result.m[15] = 1.0;
  2205. };
  2206. Matrix._tempQuaternion = new Quaternion();
  2207. Matrix._xAxis = Vector3.Zero();
  2208. Matrix._yAxis = Vector3.Zero();
  2209. Matrix._zAxis = Vector3.Zero();
  2210. return Matrix;
  2211. })();
  2212. BABYLON.Matrix = Matrix;
  2213. var Plane = (function () {
  2214. function Plane(a, b, c, d) {
  2215. this.normal = new Vector3(a, b, c);
  2216. this.d = d;
  2217. }
  2218. Plane.prototype.asArray = function () {
  2219. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2220. };
  2221. // Methods
  2222. Plane.prototype.clone = function () {
  2223. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2224. };
  2225. Plane.prototype.normalize = function () {
  2226. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2227. var magnitude = 0;
  2228. if (norm !== 0) {
  2229. magnitude = 1.0 / norm;
  2230. }
  2231. this.normal.x *= magnitude;
  2232. this.normal.y *= magnitude;
  2233. this.normal.z *= magnitude;
  2234. this.d *= magnitude;
  2235. return this;
  2236. };
  2237. Plane.prototype.transform = function (transformation) {
  2238. var transposedMatrix = Matrix.Transpose(transformation);
  2239. var x = this.normal.x;
  2240. var y = this.normal.y;
  2241. var z = this.normal.z;
  2242. var d = this.d;
  2243. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2244. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2245. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2246. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2247. return new Plane(normalX, normalY, normalZ, finalD);
  2248. };
  2249. Plane.prototype.dotCoordinate = function (point) {
  2250. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2251. };
  2252. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2253. var x1 = point2.x - point1.x;
  2254. var y1 = point2.y - point1.y;
  2255. var z1 = point2.z - point1.z;
  2256. var x2 = point3.x - point1.x;
  2257. var y2 = point3.y - point1.y;
  2258. var z2 = point3.z - point1.z;
  2259. var yz = (y1 * z2) - (z1 * y2);
  2260. var xz = (z1 * x2) - (x1 * z2);
  2261. var xy = (x1 * y2) - (y1 * x2);
  2262. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2263. var invPyth;
  2264. if (pyth !== 0) {
  2265. invPyth = 1.0 / pyth;
  2266. }
  2267. else {
  2268. invPyth = 0;
  2269. }
  2270. this.normal.x = yz * invPyth;
  2271. this.normal.y = xz * invPyth;
  2272. this.normal.z = xy * invPyth;
  2273. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2274. return this;
  2275. };
  2276. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2277. var dot = Vector3.Dot(this.normal, direction);
  2278. return (dot <= epsilon);
  2279. };
  2280. Plane.prototype.signedDistanceTo = function (point) {
  2281. return Vector3.Dot(point, this.normal) + this.d;
  2282. };
  2283. // Statics
  2284. Plane.FromArray = function (array) {
  2285. return new Plane(array[0], array[1], array[2], array[3]);
  2286. };
  2287. Plane.FromPoints = function (point1, point2, point3) {
  2288. var result = new Plane(0, 0, 0, 0);
  2289. result.copyFromPoints(point1, point2, point3);
  2290. return result;
  2291. };
  2292. Plane.FromPositionAndNormal = function (origin, normal) {
  2293. var result = new Plane(0, 0, 0, 0);
  2294. normal.normalize();
  2295. result.normal = normal;
  2296. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2297. return result;
  2298. };
  2299. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2300. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2301. return Vector3.Dot(point, normal) + d;
  2302. };
  2303. return Plane;
  2304. })();
  2305. BABYLON.Plane = Plane;
  2306. var Viewport = (function () {
  2307. function Viewport(x, y, width, height) {
  2308. this.x = x;
  2309. this.y = y;
  2310. this.width = width;
  2311. this.height = height;
  2312. }
  2313. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2314. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2315. };
  2316. return Viewport;
  2317. })();
  2318. BABYLON.Viewport = Viewport;
  2319. var Frustum = (function () {
  2320. function Frustum() {
  2321. }
  2322. Frustum.GetPlanes = function (transform) {
  2323. var frustumPlanes = [];
  2324. for (var index = 0; index < 6; index++) {
  2325. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2326. }
  2327. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2328. return frustumPlanes;
  2329. };
  2330. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2331. // Near
  2332. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2333. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2334. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2335. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2336. frustumPlanes[0].normalize();
  2337. // Far
  2338. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2339. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2340. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2341. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2342. frustumPlanes[1].normalize();
  2343. // Left
  2344. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2345. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2346. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2347. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2348. frustumPlanes[2].normalize();
  2349. // Right
  2350. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2351. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2352. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2353. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2354. frustumPlanes[3].normalize();
  2355. // Top
  2356. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2357. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2358. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2359. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2360. frustumPlanes[4].normalize();
  2361. // Bottom
  2362. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2363. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2364. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2365. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2366. frustumPlanes[5].normalize();
  2367. };
  2368. return Frustum;
  2369. })();
  2370. BABYLON.Frustum = Frustum;
  2371. (function (Space) {
  2372. Space[Space["LOCAL"] = 0] = "LOCAL";
  2373. Space[Space["WORLD"] = 1] = "WORLD";
  2374. })(BABYLON.Space || (BABYLON.Space = {}));
  2375. var Space = BABYLON.Space;
  2376. var Axis = (function () {
  2377. function Axis() {
  2378. }
  2379. Axis.X = new Vector3(1, 0, 0);
  2380. Axis.Y = new Vector3(0, 1, 0);
  2381. Axis.Z = new Vector3(0, 0, 1);
  2382. return Axis;
  2383. })();
  2384. BABYLON.Axis = Axis;
  2385. ;
  2386. var BezierCurve = (function () {
  2387. function BezierCurve() {
  2388. }
  2389. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2390. // Extract X (which is equal to time here)
  2391. var f0 = 1 - 3 * x2 + 3 * x1;
  2392. var f1 = 3 * x2 - 6 * x1;
  2393. var f2 = 3 * x1;
  2394. var refinedT = t;
  2395. for (var i = 0; i < 5; i++) {
  2396. var refinedT2 = refinedT * refinedT;
  2397. var refinedT3 = refinedT2 * refinedT;
  2398. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2399. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2400. refinedT -= (x - t) * slope;
  2401. refinedT = Math.min(1, Math.max(0, refinedT));
  2402. }
  2403. // Resolve cubic bezier for the given x
  2404. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2405. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2406. Math.pow(refinedT, 3);
  2407. };
  2408. return BezierCurve;
  2409. })();
  2410. BABYLON.BezierCurve = BezierCurve;
  2411. (function (Orientation) {
  2412. Orientation[Orientation["CW"] = 0] = "CW";
  2413. Orientation[Orientation["CCW"] = 1] = "CCW";
  2414. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2415. var Orientation = BABYLON.Orientation;
  2416. var Angle = (function () {
  2417. function Angle(radians) {
  2418. var _this = this;
  2419. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2420. this.radians = function () { return _this._radians; };
  2421. this._radians = radians;
  2422. if (this._radians < 0)
  2423. this._radians += (2 * Math.PI);
  2424. }
  2425. Angle.BetweenTwoPoints = function (a, b) {
  2426. var delta = b.subtract(a);
  2427. var theta = Math.atan2(delta.y, delta.x);
  2428. return new Angle(theta);
  2429. };
  2430. Angle.FromRadians = function (radians) {
  2431. return new Angle(radians);
  2432. };
  2433. Angle.FromDegrees = function (degrees) {
  2434. return new Angle(degrees * Math.PI / 180);
  2435. };
  2436. return Angle;
  2437. })();
  2438. BABYLON.Angle = Angle;
  2439. var Arc2 = (function () {
  2440. function Arc2(startPoint, midPoint, endPoint) {
  2441. this.startPoint = startPoint;
  2442. this.midPoint = midPoint;
  2443. this.endPoint = endPoint;
  2444. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2445. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2446. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2447. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2448. 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);
  2449. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2450. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2451. var a1 = this.startAngle.degrees();
  2452. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2453. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2454. // angles correction
  2455. if (a2 - a1 > +180.0)
  2456. a2 -= 360.0;
  2457. if (a2 - a1 < -180.0)
  2458. a2 += 360.0;
  2459. if (a3 - a2 > +180.0)
  2460. a3 -= 360.0;
  2461. if (a3 - a2 < -180.0)
  2462. a3 += 360.0;
  2463. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2464. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2465. }
  2466. return Arc2;
  2467. })();
  2468. BABYLON.Arc2 = Arc2;
  2469. var Path2 = (function () {
  2470. function Path2(x, y) {
  2471. this._points = new Array();
  2472. this._length = 0;
  2473. this.closed = false;
  2474. this._points.push(new Vector2(x, y));
  2475. }
  2476. Path2.prototype.addLineTo = function (x, y) {
  2477. if (closed) {
  2478. //Tools.Error("cannot add lines to closed paths");
  2479. return this;
  2480. }
  2481. var newPoint = new Vector2(x, y);
  2482. var previousPoint = this._points[this._points.length - 1];
  2483. this._points.push(newPoint);
  2484. this._length += newPoint.subtract(previousPoint).length();
  2485. return this;
  2486. };
  2487. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2488. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2489. if (closed) {
  2490. //Tools.Error("cannot add arcs to closed paths");
  2491. return this;
  2492. }
  2493. var startPoint = this._points[this._points.length - 1];
  2494. var midPoint = new Vector2(midX, midY);
  2495. var endPoint = new Vector2(endX, endY);
  2496. var arc = new Arc2(startPoint, midPoint, endPoint);
  2497. var increment = arc.angle.radians() / numberOfSegments;
  2498. if (arc.orientation === Orientation.CW)
  2499. increment *= -1;
  2500. var currentAngle = arc.startAngle.radians() + increment;
  2501. for (var i = 0; i < numberOfSegments; i++) {
  2502. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2503. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2504. this.addLineTo(x, y);
  2505. currentAngle += increment;
  2506. }
  2507. return this;
  2508. };
  2509. Path2.prototype.close = function () {
  2510. this.closed = true;
  2511. return this;
  2512. };
  2513. Path2.prototype.length = function () {
  2514. var result = this._length;
  2515. if (!this.closed) {
  2516. var lastPoint = this._points[this._points.length - 1];
  2517. var firstPoint = this._points[0];
  2518. result += (firstPoint.subtract(lastPoint).length());
  2519. }
  2520. return result;
  2521. };
  2522. Path2.prototype.getPoints = function () {
  2523. return this._points;
  2524. };
  2525. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2526. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2527. //Tools.Error("normalized length position should be between 0 and 1.");
  2528. return Vector2.Zero();
  2529. }
  2530. var lengthPosition = normalizedLengthPosition * this.length();
  2531. var previousOffset = 0;
  2532. for (var i = 0; i < this._points.length; i++) {
  2533. var j = (i + 1) % this._points.length;
  2534. var a = this._points[i];
  2535. var b = this._points[j];
  2536. var bToA = b.subtract(a);
  2537. var nextOffset = (bToA.length() + previousOffset);
  2538. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2539. var dir = bToA.normalize();
  2540. var localOffset = lengthPosition - previousOffset;
  2541. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2542. }
  2543. previousOffset = nextOffset;
  2544. }
  2545. //Tools.Error("internal error");
  2546. return Vector2.Zero();
  2547. };
  2548. Path2.StartingAt = function (x, y) {
  2549. return new Path2(x, y);
  2550. };
  2551. return Path2;
  2552. })();
  2553. BABYLON.Path2 = Path2;
  2554. var Path3D = (function () {
  2555. /**
  2556. * new Path3D(path, normal, raw)
  2557. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2558. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2559. * path : an array of Vector3, the curve axis of the Path3D
  2560. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2561. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2562. */
  2563. function Path3D(path, firstNormal, raw) {
  2564. this.path = path;
  2565. this._curve = new Array();
  2566. this._distances = new Array();
  2567. this._tangents = new Array();
  2568. this._normals = new Array();
  2569. this._binormals = new Array();
  2570. for (var p = 0; p < path.length; p++) {
  2571. this._curve[p] = path[p].clone(); // hard copy
  2572. }
  2573. this._raw = raw || false;
  2574. this._compute(firstNormal);
  2575. }
  2576. /**
  2577. * Returns the Path3D array of successive Vector3 designing its curve.
  2578. */
  2579. Path3D.prototype.getCurve = function () {
  2580. return this._curve;
  2581. };
  2582. /**
  2583. * Returns an array populated with tangent vectors on each Path3D curve point.
  2584. */
  2585. Path3D.prototype.getTangents = function () {
  2586. return this._tangents;
  2587. };
  2588. /**
  2589. * Returns an array populated with normal vectors on each Path3D curve point.
  2590. */
  2591. Path3D.prototype.getNormals = function () {
  2592. return this._normals;
  2593. };
  2594. /**
  2595. * Returns an array populated with binormal vectors on each Path3D curve point.
  2596. */
  2597. Path3D.prototype.getBinormals = function () {
  2598. return this._binormals;
  2599. };
  2600. /**
  2601. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2602. */
  2603. Path3D.prototype.getDistances = function () {
  2604. return this._distances;
  2605. };
  2606. /**
  2607. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2608. * Returns the same object updated.
  2609. */
  2610. Path3D.prototype.update = function (path, firstNormal) {
  2611. for (var p = 0; p < path.length; p++) {
  2612. this._curve[p].x = path[p].x;
  2613. this._curve[p].y = path[p].y;
  2614. this._curve[p].z = path[p].z;
  2615. }
  2616. this._compute(firstNormal);
  2617. return this;
  2618. };
  2619. // private function compute() : computes tangents, normals and binormals
  2620. Path3D.prototype._compute = function (firstNormal) {
  2621. var l = this._curve.length;
  2622. // first and last tangents
  2623. this._tangents[0] = this._getFirstNonNullVector(0);
  2624. if (!this._raw) {
  2625. this._tangents[0].normalize();
  2626. }
  2627. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2628. if (!this._raw) {
  2629. this._tangents[l - 1].normalize();
  2630. }
  2631. // normals and binormals at first point : arbitrary vector with _normalVector()
  2632. var tg0 = this._tangents[0];
  2633. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2634. this._normals[0] = pp0;
  2635. if (!this._raw) {
  2636. this._normals[0].normalize();
  2637. }
  2638. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2639. if (!this._raw) {
  2640. this._binormals[0].normalize();
  2641. }
  2642. this._distances[0] = 0;
  2643. // normals and binormals : next points
  2644. var prev; // previous vector (segment)
  2645. var cur; // current vector (segment)
  2646. var curTang; // current tangent
  2647. // previous normal
  2648. var prevBinor; // previous binormal
  2649. for (var i = 1; i < l; i++) {
  2650. // tangents
  2651. prev = this._getLastNonNullVector(i);
  2652. if (i < l - 1) {
  2653. cur = this._getFirstNonNullVector(i);
  2654. this._tangents[i] = prev.add(cur);
  2655. this._tangents[i].normalize();
  2656. }
  2657. this._distances[i] = this._distances[i - 1] + prev.length();
  2658. // normals and binormals
  2659. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2660. curTang = this._tangents[i];
  2661. prevBinor = this._binormals[i - 1];
  2662. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2663. if (!this._raw) {
  2664. this._normals[i].normalize();
  2665. }
  2666. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2667. if (!this._raw) {
  2668. this._binormals[i].normalize();
  2669. }
  2670. }
  2671. };
  2672. // private function getFirstNonNullVector(index)
  2673. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2674. Path3D.prototype._getFirstNonNullVector = function (index) {
  2675. var i = 1;
  2676. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2677. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2678. i++;
  2679. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2680. }
  2681. return nNVector;
  2682. };
  2683. // private function getLastNonNullVector(index)
  2684. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2685. Path3D.prototype._getLastNonNullVector = function (index) {
  2686. var i = 1;
  2687. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2688. while (nLVector.length() === 0 && index > i + 1) {
  2689. i++;
  2690. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2691. }
  2692. return nLVector;
  2693. };
  2694. // private function normalVector(v0, vt, va) :
  2695. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2696. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2697. Path3D.prototype._normalVector = function (v0, vt, va) {
  2698. var normal0;
  2699. if (va === undefined || va === null) {
  2700. var point;
  2701. if (!MathTools.WithinEpsilon(vt.y, 1, BABYLON.Epsilon)) {
  2702. point = new Vector3(0, -1, 0);
  2703. }
  2704. else if (!MathTools.WithinEpsilon(vt.x, 1, BABYLON.Epsilon)) {
  2705. point = new Vector3(1, 0, 0);
  2706. }
  2707. else if (!MathTools.WithinEpsilon(vt.z, 1, BABYLON.Epsilon)) {
  2708. point = new Vector3(0, 0, 1);
  2709. }
  2710. normal0 = Vector3.Cross(vt, point);
  2711. }
  2712. else {
  2713. normal0 = Vector3.Cross(vt, va);
  2714. Vector3.CrossToRef(normal0, vt, normal0);
  2715. }
  2716. normal0.normalize();
  2717. return normal0;
  2718. };
  2719. return Path3D;
  2720. })();
  2721. BABYLON.Path3D = Path3D;
  2722. var Curve3 = (function () {
  2723. /**
  2724. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  2725. * A Curve3 is designed from a series of successive Vector3.
  2726. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  2727. */
  2728. function Curve3(points) {
  2729. this._length = 0;
  2730. this._points = points;
  2731. this._length = this._computeLength(points);
  2732. }
  2733. /**
  2734. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  2735. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  2736. * @param v1 (Vector3) the control point
  2737. * @param v2 (Vector3) the end point of the Quadratic Bezier
  2738. * @param nbPoints (integer) the wanted number of points in the curve
  2739. */
  2740. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2741. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2742. var bez = new Array();
  2743. var equation = function (t, val0, val1, val2) {
  2744. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2745. return res;
  2746. };
  2747. for (var i = 0; i <= nbPoints; i++) {
  2748. 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)));
  2749. }
  2750. return new Curve3(bez);
  2751. };
  2752. /**
  2753. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  2754. * @param v0 (Vector3) the origin point of the Cubic Bezier
  2755. * @param v1 (Vector3) the first control point
  2756. * @param v2 (Vector3) the second control point
  2757. * @param v3 (Vector3) the end point of the Cubic Bezier
  2758. * @param nbPoints (integer) the wanted number of points in the curve
  2759. */
  2760. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2761. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2762. var bez = new Array();
  2763. var equation = function (t, val0, val1, val2, val3) {
  2764. 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;
  2765. return res;
  2766. };
  2767. for (var i = 0; i <= nbPoints; i++) {
  2768. 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)));
  2769. }
  2770. return new Curve3(bez);
  2771. };
  2772. /**
  2773. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  2774. * @param p1 (Vector3) the origin point of the Hermite Spline
  2775. * @param t1 (Vector3) the tangent vector at the origin point
  2776. * @param p2 (Vector3) the end point of the Hermite Spline
  2777. * @param t2 (Vector3) the tangent vector at the end point
  2778. * @param nbPoints (integer) the wanted number of points in the curve
  2779. */
  2780. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2781. var hermite = new Array();
  2782. var step = 1 / nbPoints;
  2783. for (var i = 0; i <= nbPoints; i++) {
  2784. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2785. }
  2786. return new Curve3(hermite);
  2787. };
  2788. /**
  2789. * Returns the Curve3 stored array of successive Vector3
  2790. */
  2791. Curve3.prototype.getPoints = function () {
  2792. return this._points;
  2793. };
  2794. /**
  2795. * Returns the computed length (float) of the curve.
  2796. */
  2797. Curve3.prototype.length = function () {
  2798. return this._length;
  2799. };
  2800. /**
  2801. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  2802. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  2803. * curveA and curveB keep unchanged.
  2804. */
  2805. Curve3.prototype.continue = function (curve) {
  2806. var lastPoint = this._points[this._points.length - 1];
  2807. var continuedPoints = this._points.slice();
  2808. var curvePoints = curve.getPoints();
  2809. for (var i = 1; i < curvePoints.length; i++) {
  2810. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2811. }
  2812. var continuedCurve = new Curve3(continuedPoints);
  2813. return continuedCurve;
  2814. };
  2815. Curve3.prototype._computeLength = function (path) {
  2816. var l = 0;
  2817. for (var i = 1; i < path.length; i++) {
  2818. l += (path[i].subtract(path[i - 1])).length();
  2819. }
  2820. return l;
  2821. };
  2822. return Curve3;
  2823. })();
  2824. BABYLON.Curve3 = Curve3;
  2825. // SphericalHarmonics
  2826. var SphericalHarmonics = (function () {
  2827. function SphericalHarmonics() {
  2828. this.L00 = Vector3.Zero();
  2829. this.L1_1 = Vector3.Zero();
  2830. this.L10 = Vector3.Zero();
  2831. this.L11 = Vector3.Zero();
  2832. this.L2_2 = Vector3.Zero();
  2833. this.L2_1 = Vector3.Zero();
  2834. this.L20 = Vector3.Zero();
  2835. this.L21 = Vector3.Zero();
  2836. this.L22 = Vector3.Zero();
  2837. }
  2838. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  2839. var colorVector = new Vector3(color.r, color.g, color.b);
  2840. var c = colorVector.scale(deltaSolidAngle);
  2841. this.L00 = this.L00.add(c.scale(0.282095));
  2842. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  2843. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  2844. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  2845. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  2846. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  2847. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  2848. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  2849. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  2850. };
  2851. SphericalHarmonics.prototype.scale = function (scale) {
  2852. this.L00 = this.L00.scale(scale);
  2853. this.L1_1 = this.L1_1.scale(scale);
  2854. this.L10 = this.L10.scale(scale);
  2855. this.L11 = this.L11.scale(scale);
  2856. this.L2_2 = this.L2_2.scale(scale);
  2857. this.L2_1 = this.L2_1.scale(scale);
  2858. this.L20 = this.L20.scale(scale);
  2859. this.L21 = this.L21.scale(scale);
  2860. this.L22 = this.L22.scale(scale);
  2861. };
  2862. return SphericalHarmonics;
  2863. })();
  2864. BABYLON.SphericalHarmonics = SphericalHarmonics;
  2865. // SphericalPolynomial
  2866. var SphericalPolynomial = (function () {
  2867. function SphericalPolynomial() {
  2868. this.x = Vector3.Zero();
  2869. this.y = Vector3.Zero();
  2870. this.z = Vector3.Zero();
  2871. this.xx = Vector3.Zero();
  2872. this.yy = Vector3.Zero();
  2873. this.zz = Vector3.Zero();
  2874. this.xy = Vector3.Zero();
  2875. this.yz = Vector3.Zero();
  2876. this.zx = Vector3.Zero();
  2877. }
  2878. SphericalPolynomial.prototype.addAmbient = function (color) {
  2879. var colorVector = new Vector3(color.r, color.g, color.b);
  2880. this.xx = this.xx.add(colorVector);
  2881. this.yy = this.yy.add(colorVector);
  2882. this.zz = this.zz.add(colorVector);
  2883. };
  2884. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  2885. var result = new SphericalPolynomial();
  2886. result.x = harmonics.L11.scale(1.02333);
  2887. result.y = harmonics.L1_1.scale(1.02333);
  2888. result.z = harmonics.L10.scale(1.02333);
  2889. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  2890. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  2891. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  2892. result.yz = harmonics.L2_1.scale(0.858086);
  2893. result.zx = harmonics.L21.scale(0.858086);
  2894. result.xy = harmonics.L2_2.scale(0.858086);
  2895. return result;
  2896. };
  2897. return SphericalPolynomial;
  2898. })();
  2899. BABYLON.SphericalPolynomial = SphericalPolynomial;
  2900. // Vertex formats
  2901. var PositionNormalVertex = (function () {
  2902. function PositionNormalVertex(position, normal) {
  2903. if (position === void 0) { position = Vector3.Zero(); }
  2904. if (normal === void 0) { normal = Vector3.Up(); }
  2905. this.position = position;
  2906. this.normal = normal;
  2907. }
  2908. PositionNormalVertex.prototype.clone = function () {
  2909. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2910. };
  2911. return PositionNormalVertex;
  2912. })();
  2913. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2914. var PositionNormalTextureVertex = (function () {
  2915. function PositionNormalTextureVertex(position, normal, uv) {
  2916. if (position === void 0) { position = Vector3.Zero(); }
  2917. if (normal === void 0) { normal = Vector3.Up(); }
  2918. if (uv === void 0) { uv = Vector2.Zero(); }
  2919. this.position = position;
  2920. this.normal = normal;
  2921. this.uv = uv;
  2922. }
  2923. PositionNormalTextureVertex.prototype.clone = function () {
  2924. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2925. };
  2926. return PositionNormalTextureVertex;
  2927. })();
  2928. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2929. // Temporary pre-allocated objects for engine internal use
  2930. // usage in any internal function :
  2931. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  2932. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  2933. var Tmp = (function () {
  2934. function Tmp() {
  2935. }
  2936. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  2937. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  2938. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  2939. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  2940. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  2941. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  2942. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  2943. Matrix.Zero(), Matrix.Zero(),
  2944. Matrix.Zero(), Matrix.Zero(),
  2945. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  2946. return Tmp;
  2947. })();
  2948. BABYLON.Tmp = Tmp;
  2949. })(BABYLON || (BABYLON = {}));
  2950. var BABYLON;
  2951. (function (BABYLON) {
  2952. function generateSerializableMember(type, sourceName) {
  2953. return function (target, propertyKey) {
  2954. if (!target.__serializableMembers) {
  2955. target.__serializableMembers = {};
  2956. }
  2957. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  2958. };
  2959. }
  2960. function serialize(sourceName) {
  2961. return generateSerializableMember(0, sourceName); // value member
  2962. }
  2963. BABYLON.serialize = serialize;
  2964. function serializeAsTexture(sourceName) {
  2965. return generateSerializableMember(1, sourceName); // texture member
  2966. }
  2967. BABYLON.serializeAsTexture = serializeAsTexture;
  2968. function serializeAsColor3(sourceName) {
  2969. return generateSerializableMember(2, sourceName); // color3 member
  2970. }
  2971. BABYLON.serializeAsColor3 = serializeAsColor3;
  2972. function serializeAsFresnelParameters(sourceName) {
  2973. return generateSerializableMember(3, sourceName); // fresnel parameters member
  2974. }
  2975. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  2976. function serializeAsVector2(sourceName) {
  2977. return generateSerializableMember(4, sourceName); // vector2 member
  2978. }
  2979. BABYLON.serializeAsVector2 = serializeAsVector2;
  2980. function serializeAsVector3(sourceName) {
  2981. return generateSerializableMember(5, sourceName); // vector3 member
  2982. }
  2983. BABYLON.serializeAsVector3 = serializeAsVector3;
  2984. function serializeAsMeshReference(sourceName) {
  2985. return generateSerializableMember(6, sourceName); // mesh reference member
  2986. }
  2987. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  2988. var SerializationHelper = (function () {
  2989. function SerializationHelper() {
  2990. }
  2991. SerializationHelper.Serialize = function (entity, serializationObject) {
  2992. if (!serializationObject) {
  2993. serializationObject = {};
  2994. }
  2995. // Tags
  2996. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  2997. // Properties
  2998. for (var property in entity.__serializableMembers) {
  2999. var propertyDescriptor = entity.__serializableMembers[property];
  3000. var targetPropertyName = propertyDescriptor.sourceName || property;
  3001. var propertyType = propertyDescriptor.type;
  3002. var sourceProperty = entity[property];
  3003. if (sourceProperty !== undefined && sourceProperty !== null) {
  3004. switch (propertyType) {
  3005. case 0:
  3006. serializationObject[targetPropertyName] = sourceProperty;
  3007. break;
  3008. case 1:
  3009. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3010. break;
  3011. case 2:
  3012. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3013. break;
  3014. case 3:
  3015. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3016. break;
  3017. case 4:
  3018. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3019. break;
  3020. case 5:
  3021. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3022. break;
  3023. case 6:
  3024. serializationObject[targetPropertyName] = sourceProperty.id;
  3025. break;
  3026. }
  3027. }
  3028. }
  3029. return serializationObject;
  3030. };
  3031. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3032. var destination = creationFunction();
  3033. // Tags
  3034. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3035. // Properties
  3036. for (var property in destination.__serializableMembers) {
  3037. var propertyDescriptor = destination.__serializableMembers[property];
  3038. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3039. var propertyType = propertyDescriptor.type;
  3040. if (sourceProperty !== undefined && sourceProperty !== null) {
  3041. switch (propertyType) {
  3042. case 0:
  3043. destination[property] = sourceProperty;
  3044. break;
  3045. case 1:
  3046. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3047. break;
  3048. case 2:
  3049. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3050. break;
  3051. case 3:
  3052. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3053. break;
  3054. case 4:
  3055. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3056. break;
  3057. case 5:
  3058. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3059. break;
  3060. case 6:
  3061. destination[property] = scene.getLastMeshByID(sourceProperty);
  3062. break;
  3063. }
  3064. }
  3065. }
  3066. return destination;
  3067. };
  3068. SerializationHelper.Clone = function (creationFunction, source) {
  3069. var destination = creationFunction();
  3070. // Tags
  3071. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3072. // Properties
  3073. for (var property in destination.__serializableMembers) {
  3074. var propertyDescriptor = destination.__serializableMembers[property];
  3075. var sourceProperty = source[property];
  3076. var propertyType = propertyDescriptor.type;
  3077. if (sourceProperty !== undefined && sourceProperty !== null) {
  3078. switch (propertyType) {
  3079. case 0: // Value
  3080. case 6:
  3081. destination[property] = sourceProperty;
  3082. break;
  3083. case 1: // Texture
  3084. case 2: // Color3
  3085. case 3: // FresnelParameters
  3086. case 4: // Vector2
  3087. case 5:
  3088. destination[property] = sourceProperty.clone();
  3089. break;
  3090. }
  3091. }
  3092. }
  3093. return destination;
  3094. };
  3095. return SerializationHelper;
  3096. })();
  3097. BABYLON.SerializationHelper = SerializationHelper;
  3098. })(BABYLON || (BABYLON = {}));
  3099. var BABYLON;
  3100. (function (BABYLON) {
  3101. /**
  3102. * A class serves as a medium between the observable and its observers
  3103. */
  3104. var EventState = (function () {
  3105. /**
  3106. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3107. */
  3108. function EventState(skipNextObservers) {
  3109. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3110. this.skipNextObservers = skipNextObservers;
  3111. }
  3112. return EventState;
  3113. })();
  3114. BABYLON.EventState = EventState;
  3115. var Observer = (function () {
  3116. function Observer(callback, mask) {
  3117. this.callback = callback;
  3118. this.mask = mask;
  3119. }
  3120. return Observer;
  3121. })();
  3122. BABYLON.Observer = Observer;
  3123. var Observable = (function () {
  3124. function Observable() {
  3125. this._observers = new Array();
  3126. }
  3127. /**
  3128. * Create a new Observer with the specified callback
  3129. * @param callback the callback that will be executed for that Observer
  3130. * @param mash the mask used to filter observers
  3131. * @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.
  3132. */
  3133. Observable.prototype.add = function (callback, mask, insertFirst) {
  3134. if (mask === void 0) { mask = -1; }
  3135. if (insertFirst === void 0) { insertFirst = false; }
  3136. if (!callback) {
  3137. return null;
  3138. }
  3139. var observer = new Observer(callback, mask);
  3140. if (insertFirst) {
  3141. this._observers.unshift(observer);
  3142. }
  3143. else {
  3144. this._observers.push(observer);
  3145. }
  3146. return observer;
  3147. };
  3148. /**
  3149. * Remove an Observer from the Observable object
  3150. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3151. */
  3152. Observable.prototype.remove = function (observer) {
  3153. var index = this._observers.indexOf(observer);
  3154. if (index !== -1) {
  3155. this._observers.splice(index, 1);
  3156. return true;
  3157. }
  3158. return false;
  3159. };
  3160. /**
  3161. * Remove a callback from the Observable object
  3162. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3163. */
  3164. Observable.prototype.removeCallback = function (callback) {
  3165. for (var index = 0; index < this._observers.length; index++) {
  3166. if (this._observers[index].callback === callback) {
  3167. this._observers.splice(index, 1);
  3168. return true;
  3169. }
  3170. }
  3171. return false;
  3172. };
  3173. /**
  3174. * Notify all Observers by calling their respective callback with the given data
  3175. * @param eventData
  3176. * @param mask
  3177. */
  3178. Observable.prototype.notifyObservers = function (eventData, mask) {
  3179. if (mask === void 0) { mask = -1; }
  3180. var state = new EventState();
  3181. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3182. var obs = _a[_i];
  3183. if (obs.mask & mask) {
  3184. obs.callback(eventData, state);
  3185. }
  3186. if (state.skipNextObservers) {
  3187. break;
  3188. }
  3189. }
  3190. };
  3191. /**
  3192. * return true is the Observable has at least one Observer registered
  3193. */
  3194. Observable.prototype.hasObservers = function () {
  3195. return this._observers.length > 0;
  3196. };
  3197. /**
  3198. * Clear the list of observers
  3199. */
  3200. Observable.prototype.clear = function () {
  3201. this._observers = new Array();
  3202. };
  3203. /**
  3204. * Clone the current observable
  3205. */
  3206. Observable.prototype.clone = function () {
  3207. var result = new Observable();
  3208. result._observers = this._observers.slice(0);
  3209. return result;
  3210. };
  3211. return Observable;
  3212. })();
  3213. BABYLON.Observable = Observable;
  3214. })(BABYLON || (BABYLON = {}));
  3215. var BABYLON;
  3216. (function (BABYLON) {
  3217. var Database = (function () {
  3218. function Database(urlToScene, callbackManifestChecked) {
  3219. // Handling various flavors of prefixed version of IndexedDB
  3220. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3221. this.callbackManifestChecked = callbackManifestChecked;
  3222. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3223. this.db = null;
  3224. this.enableSceneOffline = false;
  3225. this.enableTexturesOffline = false;
  3226. this.manifestVersionFound = 0;
  3227. this.mustUpdateRessources = false;
  3228. this.hasReachedQuota = false;
  3229. if (!Database.IDBStorageEnabled) {
  3230. this.callbackManifestChecked(true);
  3231. }
  3232. else {
  3233. this.checkManifestFile();
  3234. }
  3235. }
  3236. Database.prototype.checkManifestFile = function () {
  3237. var _this = this;
  3238. function noManifestFile() {
  3239. that.enableSceneOffline = false;
  3240. that.enableTexturesOffline = false;
  3241. that.callbackManifestChecked(false);
  3242. }
  3243. var that = this;
  3244. var timeStampUsed = false;
  3245. var manifestURL = this.currentSceneUrl + ".manifest";
  3246. var xhr = new XMLHttpRequest();
  3247. if (navigator.onLine) {
  3248. // Adding a timestamp to by-pass browsers' cache
  3249. timeStampUsed = true;
  3250. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3251. }
  3252. xhr.open("GET", manifestURL, true);
  3253. xhr.addEventListener("load", function () {
  3254. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3255. try {
  3256. var manifestFile = JSON.parse(xhr.response);
  3257. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3258. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3259. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3260. _this.manifestVersionFound = manifestFile.version;
  3261. }
  3262. if (_this.callbackManifestChecked) {
  3263. _this.callbackManifestChecked(true);
  3264. }
  3265. }
  3266. catch (ex) {
  3267. noManifestFile();
  3268. }
  3269. }
  3270. else {
  3271. noManifestFile();
  3272. }
  3273. }, false);
  3274. xhr.addEventListener("error", function (event) {
  3275. if (timeStampUsed) {
  3276. timeStampUsed = false;
  3277. // Let's retry without the timeStamp
  3278. // It could fail when coupled with HTML5 Offline API
  3279. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3280. xhr.open("GET", retryManifestURL, true);
  3281. xhr.send();
  3282. }
  3283. else {
  3284. noManifestFile();
  3285. }
  3286. }, false);
  3287. try {
  3288. xhr.send();
  3289. }
  3290. catch (ex) {
  3291. BABYLON.Tools.Error("Error on XHR send request.");
  3292. that.callbackManifestChecked(false);
  3293. }
  3294. };
  3295. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3296. var _this = this;
  3297. function handleError() {
  3298. that.isSupported = false;
  3299. if (errorCallback)
  3300. errorCallback();
  3301. }
  3302. var that = this;
  3303. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3304. // Your browser doesn't support IndexedDB
  3305. this.isSupported = false;
  3306. if (errorCallback)
  3307. errorCallback();
  3308. }
  3309. else {
  3310. // If the DB hasn't been opened or created yet
  3311. if (!this.db) {
  3312. this.hasReachedQuota = false;
  3313. this.isSupported = true;
  3314. var request = this.idbFactory.open("babylonjs", 1);
  3315. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3316. request.onerror = function (event) {
  3317. handleError();
  3318. };
  3319. // executes when a version change transaction cannot complete due to other active transactions
  3320. request.onblocked = function (event) {
  3321. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3322. handleError();
  3323. };
  3324. // DB has been opened successfully
  3325. request.onsuccess = function (event) {
  3326. _this.db = request.result;
  3327. successCallback();
  3328. };
  3329. // Initialization of the DB. Creating Scenes & Textures stores
  3330. request.onupgradeneeded = function (event) {
  3331. _this.db = (event.target).result;
  3332. try {
  3333. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3334. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3335. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3336. }
  3337. catch (ex) {
  3338. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3339. handleError();
  3340. }
  3341. };
  3342. }
  3343. else {
  3344. if (successCallback)
  3345. successCallback();
  3346. }
  3347. }
  3348. };
  3349. Database.prototype.loadImageFromDB = function (url, image) {
  3350. var _this = this;
  3351. var completeURL = Database.ReturnFullUrlLocation(url);
  3352. var saveAndLoadImage = function () {
  3353. if (!_this.hasReachedQuota && _this.db !== null) {
  3354. // the texture is not yet in the DB, let's try to save it
  3355. _this._saveImageIntoDBAsync(completeURL, image);
  3356. }
  3357. else {
  3358. image.src = url;
  3359. }
  3360. };
  3361. if (!this.mustUpdateRessources) {
  3362. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3363. }
  3364. else {
  3365. saveAndLoadImage();
  3366. }
  3367. };
  3368. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3369. if (this.isSupported && this.db !== null) {
  3370. var texture;
  3371. var transaction = this.db.transaction(["textures"]);
  3372. transaction.onabort = function (event) {
  3373. image.src = url;
  3374. };
  3375. transaction.oncomplete = function (event) {
  3376. var blobTextureURL;
  3377. if (texture) {
  3378. var URL = window.URL || window.webkitURL;
  3379. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3380. image.onerror = function () {
  3381. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3382. image.src = url;
  3383. };
  3384. image.src = blobTextureURL;
  3385. }
  3386. else {
  3387. notInDBCallback();
  3388. }
  3389. };
  3390. var getRequest = transaction.objectStore("textures").get(url);
  3391. getRequest.onsuccess = function (event) {
  3392. texture = (event.target).result;
  3393. };
  3394. getRequest.onerror = function (event) {
  3395. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3396. image.src = url;
  3397. };
  3398. }
  3399. else {
  3400. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3401. image.src = url;
  3402. }
  3403. };
  3404. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3405. var _this = this;
  3406. if (this.isSupported) {
  3407. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3408. var generateBlobUrl = function () {
  3409. var blobTextureURL;
  3410. if (blob) {
  3411. var URL = window.URL || window.webkitURL;
  3412. try {
  3413. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3414. }
  3415. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3416. catch (ex) {
  3417. blobTextureURL = URL.createObjectURL(blob);
  3418. }
  3419. }
  3420. image.src = blobTextureURL;
  3421. };
  3422. if (Database.IsUASupportingBlobStorage) {
  3423. var xhr = new XMLHttpRequest(), blob;
  3424. xhr.open("GET", url, true);
  3425. xhr.responseType = "blob";
  3426. xhr.addEventListener("load", function () {
  3427. if (xhr.status === 200) {
  3428. // Blob as response (XHR2)
  3429. blob = xhr.response;
  3430. var transaction = _this.db.transaction(["textures"], "readwrite");
  3431. // the transaction could abort because of a QuotaExceededError error
  3432. transaction.onabort = function (event) {
  3433. try {
  3434. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3435. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3436. this.hasReachedQuota = true;
  3437. }
  3438. }
  3439. catch (ex) { }
  3440. generateBlobUrl();
  3441. };
  3442. transaction.oncomplete = function (event) {
  3443. generateBlobUrl();
  3444. };
  3445. var newTexture = { textureUrl: url, data: blob };
  3446. try {
  3447. // Put the blob into the dabase
  3448. var addRequest = transaction.objectStore("textures").put(newTexture);
  3449. addRequest.onsuccess = function (event) {
  3450. };
  3451. addRequest.onerror = function (event) {
  3452. generateBlobUrl();
  3453. };
  3454. }
  3455. catch (ex) {
  3456. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3457. if (ex.code === 25) {
  3458. Database.IsUASupportingBlobStorage = false;
  3459. }
  3460. image.src = url;
  3461. }
  3462. }
  3463. else {
  3464. image.src = url;
  3465. }
  3466. }, false);
  3467. xhr.addEventListener("error", function (event) {
  3468. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3469. image.src = url;
  3470. }, false);
  3471. xhr.send();
  3472. }
  3473. else {
  3474. image.src = url;
  3475. }
  3476. }
  3477. else {
  3478. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3479. image.src = url;
  3480. }
  3481. };
  3482. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3483. var _this = this;
  3484. var updateVersion = function (event) {
  3485. // the version is not yet in the DB or we need to update it
  3486. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3487. };
  3488. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3489. };
  3490. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3491. var _this = this;
  3492. if (this.isSupported) {
  3493. var version;
  3494. try {
  3495. var transaction = this.db.transaction(["versions"]);
  3496. transaction.oncomplete = function (event) {
  3497. if (version) {
  3498. // If the version in the JSON file is > than the version in DB
  3499. if (_this.manifestVersionFound > version.data) {
  3500. _this.mustUpdateRessources = true;
  3501. updateInDBCallback();
  3502. }
  3503. else {
  3504. callback(version.data);
  3505. }
  3506. }
  3507. else {
  3508. _this.mustUpdateRessources = true;
  3509. updateInDBCallback();
  3510. }
  3511. };
  3512. transaction.onabort = function (event) {
  3513. callback(-1);
  3514. };
  3515. var getRequest = transaction.objectStore("versions").get(url);
  3516. getRequest.onsuccess = function (event) {
  3517. version = (event.target).result;
  3518. };
  3519. getRequest.onerror = function (event) {
  3520. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3521. callback(-1);
  3522. };
  3523. }
  3524. catch (ex) {
  3525. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3526. callback(-1);
  3527. }
  3528. }
  3529. else {
  3530. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3531. callback(-1);
  3532. }
  3533. };
  3534. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3535. var _this = this;
  3536. if (this.isSupported && !this.hasReachedQuota) {
  3537. try {
  3538. // Open a transaction to the database
  3539. var transaction = this.db.transaction(["versions"], "readwrite");
  3540. // the transaction could abort because of a QuotaExceededError error
  3541. transaction.onabort = function (event) {
  3542. try {
  3543. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3544. _this.hasReachedQuota = true;
  3545. }
  3546. }
  3547. catch (ex) { }
  3548. callback(-1);
  3549. };
  3550. transaction.oncomplete = function (event) {
  3551. callback(_this.manifestVersionFound);
  3552. };
  3553. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3554. // Put the scene into the database
  3555. var addRequest = transaction.objectStore("versions").put(newVersion);
  3556. addRequest.onsuccess = function (event) {
  3557. };
  3558. addRequest.onerror = function (event) {
  3559. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3560. };
  3561. }
  3562. catch (ex) {
  3563. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3564. callback(-1);
  3565. }
  3566. }
  3567. else {
  3568. callback(-1);
  3569. }
  3570. };
  3571. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3572. var _this = this;
  3573. var completeUrl = Database.ReturnFullUrlLocation(url);
  3574. var saveAndLoadFile = function (event) {
  3575. // the scene is not yet in the DB, let's try to save it
  3576. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3577. };
  3578. this._checkVersionFromDB(completeUrl, function (version) {
  3579. if (version !== -1) {
  3580. if (!_this.mustUpdateRessources) {
  3581. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3582. }
  3583. else {
  3584. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3585. }
  3586. }
  3587. else {
  3588. errorCallback();
  3589. }
  3590. });
  3591. };
  3592. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3593. if (this.isSupported) {
  3594. var targetStore;
  3595. if (url.indexOf(".babylon") !== -1) {
  3596. targetStore = "scenes";
  3597. }
  3598. else {
  3599. targetStore = "textures";
  3600. }
  3601. var file;
  3602. var transaction = this.db.transaction([targetStore]);
  3603. transaction.oncomplete = function (event) {
  3604. if (file) {
  3605. callback(file.data);
  3606. }
  3607. else {
  3608. notInDBCallback();
  3609. }
  3610. };
  3611. transaction.onabort = function (event) {
  3612. notInDBCallback();
  3613. };
  3614. var getRequest = transaction.objectStore(targetStore).get(url);
  3615. getRequest.onsuccess = function (event) {
  3616. file = (event.target).result;
  3617. };
  3618. getRequest.onerror = function (event) {
  3619. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3620. notInDBCallback();
  3621. };
  3622. }
  3623. else {
  3624. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3625. callback();
  3626. }
  3627. };
  3628. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3629. var _this = this;
  3630. if (this.isSupported) {
  3631. var targetStore;
  3632. if (url.indexOf(".babylon") !== -1) {
  3633. targetStore = "scenes";
  3634. }
  3635. else {
  3636. targetStore = "textures";
  3637. }
  3638. // Create XHR
  3639. var xhr = new XMLHttpRequest(), fileData;
  3640. xhr.open("GET", url, true);
  3641. if (useArrayBuffer) {
  3642. xhr.responseType = "arraybuffer";
  3643. }
  3644. xhr.onprogress = progressCallback;
  3645. xhr.addEventListener("load", function () {
  3646. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3647. // Blob as response (XHR2)
  3648. //fileData = xhr.responseText;
  3649. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3650. if (!_this.hasReachedQuota) {
  3651. // Open a transaction to the database
  3652. var transaction = _this.db.transaction([targetStore], "readwrite");
  3653. // the transaction could abort because of a QuotaExceededError error
  3654. transaction.onabort = function (event) {
  3655. try {
  3656. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3657. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3658. this.hasReachedQuota = true;
  3659. }
  3660. }
  3661. catch (ex) { }
  3662. callback(fileData);
  3663. };
  3664. transaction.oncomplete = function (event) {
  3665. callback(fileData);
  3666. };
  3667. var newFile;
  3668. if (targetStore === "scenes") {
  3669. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3670. }
  3671. else {
  3672. newFile = { textureUrl: url, data: fileData };
  3673. }
  3674. try {
  3675. // Put the scene into the database
  3676. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3677. addRequest.onsuccess = function (event) {
  3678. };
  3679. addRequest.onerror = function (event) {
  3680. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3681. };
  3682. }
  3683. catch (ex) {
  3684. callback(fileData);
  3685. }
  3686. }
  3687. else {
  3688. callback(fileData);
  3689. }
  3690. }
  3691. else {
  3692. callback();
  3693. }
  3694. }, false);
  3695. xhr.addEventListener("error", function (event) {
  3696. BABYLON.Tools.Error("error on XHR request.");
  3697. callback();
  3698. }, false);
  3699. xhr.send();
  3700. }
  3701. else {
  3702. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3703. callback();
  3704. }
  3705. };
  3706. Database.IsUASupportingBlobStorage = true;
  3707. Database.IDBStorageEnabled = true;
  3708. Database.parseURL = function (url) {
  3709. var a = document.createElement('a');
  3710. a.href = url;
  3711. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3712. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3713. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3714. return absLocation;
  3715. };
  3716. Database.ReturnFullUrlLocation = function (url) {
  3717. if (url.indexOf("http:/") === -1) {
  3718. return (Database.parseURL(window.location.href) + url);
  3719. }
  3720. else {
  3721. return url;
  3722. }
  3723. };
  3724. return Database;
  3725. })();
  3726. BABYLON.Database = Database;
  3727. })(BABYLON || (BABYLON = {}));
  3728. var BABYLON;
  3729. (function (BABYLON) {
  3730. var Internals;
  3731. (function (Internals) {
  3732. /*
  3733. * Based on jsTGALoader - Javascript loader for TGA file
  3734. * By Vincent Thibault
  3735. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3736. */
  3737. var TGATools = (function () {
  3738. function TGATools() {
  3739. }
  3740. TGATools.GetTGAHeader = function (data) {
  3741. var offset = 0;
  3742. var header = {
  3743. id_length: data[offset++],
  3744. colormap_type: data[offset++],
  3745. image_type: data[offset++],
  3746. colormap_index: data[offset++] | data[offset++] << 8,
  3747. colormap_length: data[offset++] | data[offset++] << 8,
  3748. colormap_size: data[offset++],
  3749. origin: [
  3750. data[offset++] | data[offset++] << 8,
  3751. data[offset++] | data[offset++] << 8
  3752. ],
  3753. width: data[offset++] | data[offset++] << 8,
  3754. height: data[offset++] | data[offset++] << 8,
  3755. pixel_size: data[offset++],
  3756. flags: data[offset++]
  3757. };
  3758. return header;
  3759. };
  3760. TGATools.UploadContent = function (gl, data) {
  3761. // Not enough data to contain header ?
  3762. if (data.length < 19) {
  3763. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3764. return;
  3765. }
  3766. // Read Header
  3767. var offset = 18;
  3768. var header = TGATools.GetTGAHeader(data);
  3769. // Assume it's a valid Targa file.
  3770. if (header.id_length + offset > data.length) {
  3771. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3772. return;
  3773. }
  3774. // Skip not needed data
  3775. offset += header.id_length;
  3776. var use_rle = false;
  3777. var use_pal = false;
  3778. var use_rgb = false;
  3779. var use_grey = false;
  3780. // Get some informations.
  3781. switch (header.image_type) {
  3782. case TGATools._TYPE_RLE_INDEXED:
  3783. use_rle = true;
  3784. case TGATools._TYPE_INDEXED:
  3785. use_pal = true;
  3786. break;
  3787. case TGATools._TYPE_RLE_RGB:
  3788. use_rle = true;
  3789. case TGATools._TYPE_RGB:
  3790. use_rgb = true;
  3791. break;
  3792. case TGATools._TYPE_RLE_GREY:
  3793. use_rle = true;
  3794. case TGATools._TYPE_GREY:
  3795. use_grey = true;
  3796. break;
  3797. }
  3798. var pixel_data;
  3799. var numAlphaBits = header.flags & 0xf;
  3800. var pixel_size = header.pixel_size >> 3;
  3801. var pixel_total = header.width * header.height * pixel_size;
  3802. // Read palettes
  3803. var palettes;
  3804. if (use_pal) {
  3805. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3806. }
  3807. // Read LRE
  3808. if (use_rle) {
  3809. pixel_data = new Uint8Array(pixel_total);
  3810. var c, count, i;
  3811. var localOffset = 0;
  3812. var pixels = new Uint8Array(pixel_size);
  3813. while (offset < pixel_total && localOffset < pixel_total) {
  3814. c = data[offset++];
  3815. count = (c & 0x7f) + 1;
  3816. // RLE pixels
  3817. if (c & 0x80) {
  3818. // Bind pixel tmp array
  3819. for (i = 0; i < pixel_size; ++i) {
  3820. pixels[i] = data[offset++];
  3821. }
  3822. // Copy pixel array
  3823. for (i = 0; i < count; ++i) {
  3824. pixel_data.set(pixels, localOffset + i * pixel_size);
  3825. }
  3826. localOffset += pixel_size * count;
  3827. }
  3828. else {
  3829. count *= pixel_size;
  3830. for (i = 0; i < count; ++i) {
  3831. pixel_data[localOffset + i] = data[offset++];
  3832. }
  3833. localOffset += count;
  3834. }
  3835. }
  3836. }
  3837. else {
  3838. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3839. }
  3840. // Load to texture
  3841. var x_start, y_start, x_step, y_step, y_end, x_end;
  3842. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3843. default:
  3844. case TGATools._ORIGIN_UL:
  3845. x_start = 0;
  3846. x_step = 1;
  3847. x_end = header.width;
  3848. y_start = 0;
  3849. y_step = 1;
  3850. y_end = header.height;
  3851. break;
  3852. case TGATools._ORIGIN_BL:
  3853. x_start = 0;
  3854. x_step = 1;
  3855. x_end = header.width;
  3856. y_start = header.height - 1;
  3857. y_step = -1;
  3858. y_end = -1;
  3859. break;
  3860. case TGATools._ORIGIN_UR:
  3861. x_start = header.width - 1;
  3862. x_step = -1;
  3863. x_end = -1;
  3864. y_start = 0;
  3865. y_step = 1;
  3866. y_end = header.height;
  3867. break;
  3868. case TGATools._ORIGIN_BR:
  3869. x_start = header.width - 1;
  3870. x_step = -1;
  3871. x_end = -1;
  3872. y_start = header.height - 1;
  3873. y_step = -1;
  3874. y_end = -1;
  3875. break;
  3876. }
  3877. // Load the specify method
  3878. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3879. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3880. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3881. };
  3882. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3883. var image = pixel_data, colormap = palettes;
  3884. var width = header.width, height = header.height;
  3885. var color, i = 0, x, y;
  3886. var imageData = new Uint8Array(width * height * 4);
  3887. for (y = y_start; y !== y_end; y += y_step) {
  3888. for (x = x_start; x !== x_end; x += x_step, i++) {
  3889. color = image[i];
  3890. imageData[(x + width * y) * 4 + 3] = 255;
  3891. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3892. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3893. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3894. }
  3895. }
  3896. return imageData;
  3897. };
  3898. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3899. var image = pixel_data;
  3900. var width = header.width, height = header.height;
  3901. var color, i = 0, x, y;
  3902. var imageData = new Uint8Array(width * height * 4);
  3903. for (y = y_start; y !== y_end; y += y_step) {
  3904. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3905. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3906. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3907. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3908. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3909. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3910. }
  3911. }
  3912. return imageData;
  3913. };
  3914. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3915. var image = pixel_data;
  3916. var width = header.width, height = header.height;
  3917. var i = 0, x, y;
  3918. var imageData = new Uint8Array(width * height * 4);
  3919. for (y = y_start; y !== y_end; y += y_step) {
  3920. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3921. imageData[(x + width * y) * 4 + 3] = 255;
  3922. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3923. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3924. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3925. }
  3926. }
  3927. return imageData;
  3928. };
  3929. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3930. var image = pixel_data;
  3931. var width = header.width, height = header.height;
  3932. var i = 0, x, y;
  3933. var imageData = new Uint8Array(width * height * 4);
  3934. for (y = y_start; y !== y_end; y += y_step) {
  3935. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3936. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3937. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3938. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3939. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3940. }
  3941. }
  3942. return imageData;
  3943. };
  3944. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3945. var image = pixel_data;
  3946. var width = header.width, height = header.height;
  3947. var color, i = 0, x, y;
  3948. var imageData = new Uint8Array(width * height * 4);
  3949. for (y = y_start; y !== y_end; y += y_step) {
  3950. for (x = x_start; x !== x_end; x += x_step, i++) {
  3951. color = image[i];
  3952. imageData[(x + width * y) * 4 + 0] = color;
  3953. imageData[(x + width * y) * 4 + 1] = color;
  3954. imageData[(x + width * y) * 4 + 2] = color;
  3955. imageData[(x + width * y) * 4 + 3] = 255;
  3956. }
  3957. }
  3958. return imageData;
  3959. };
  3960. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3961. var image = pixel_data;
  3962. var width = header.width, height = header.height;
  3963. var i = 0, x, y;
  3964. var imageData = new Uint8Array(width * height * 4);
  3965. for (y = y_start; y !== y_end; y += y_step) {
  3966. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3967. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3968. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3969. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3970. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3971. }
  3972. }
  3973. return imageData;
  3974. };
  3975. TGATools._TYPE_NO_DATA = 0;
  3976. TGATools._TYPE_INDEXED = 1;
  3977. TGATools._TYPE_RGB = 2;
  3978. TGATools._TYPE_GREY = 3;
  3979. TGATools._TYPE_RLE_INDEXED = 9;
  3980. TGATools._TYPE_RLE_RGB = 10;
  3981. TGATools._TYPE_RLE_GREY = 11;
  3982. TGATools._ORIGIN_MASK = 0x30;
  3983. TGATools._ORIGIN_SHIFT = 0x04;
  3984. TGATools._ORIGIN_BL = 0x00;
  3985. TGATools._ORIGIN_BR = 0x01;
  3986. TGATools._ORIGIN_UL = 0x02;
  3987. TGATools._ORIGIN_UR = 0x03;
  3988. return TGATools;
  3989. })();
  3990. Internals.TGATools = TGATools;
  3991. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3992. })(BABYLON || (BABYLON = {}));
  3993. var BABYLON;
  3994. (function (BABYLON) {
  3995. var SmartArray = (function () {
  3996. function SmartArray(capacity) {
  3997. this.length = 0;
  3998. this._duplicateId = 0;
  3999. this.data = new Array(capacity);
  4000. this._id = SmartArray._GlobalId++;
  4001. }
  4002. SmartArray.prototype.push = function (value) {
  4003. this.data[this.length++] = value;
  4004. if (this.length > this.data.length) {
  4005. this.data.length *= 2;
  4006. }
  4007. if (!value.__smartArrayFlags) {
  4008. value.__smartArrayFlags = {};
  4009. }
  4010. value.__smartArrayFlags[this._id] = this._duplicateId;
  4011. };
  4012. SmartArray.prototype.pushNoDuplicate = function (value) {
  4013. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4014. return;
  4015. }
  4016. this.push(value);
  4017. };
  4018. SmartArray.prototype.sort = function (compareFn) {
  4019. this.data.sort(compareFn);
  4020. };
  4021. SmartArray.prototype.reset = function () {
  4022. this.length = 0;
  4023. this._duplicateId++;
  4024. };
  4025. SmartArray.prototype.concat = function (array) {
  4026. if (array.length === 0) {
  4027. return;
  4028. }
  4029. if (this.length + array.length > this.data.length) {
  4030. this.data.length = (this.length + array.length) * 2;
  4031. }
  4032. for (var index = 0; index < array.length; index++) {
  4033. this.data[this.length++] = (array.data || array)[index];
  4034. }
  4035. };
  4036. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4037. if (array.length === 0) {
  4038. return;
  4039. }
  4040. if (this.length + array.length > this.data.length) {
  4041. this.data.length = (this.length + array.length) * 2;
  4042. }
  4043. for (var index = 0; index < array.length; index++) {
  4044. var item = (array.data || array)[index];
  4045. this.pushNoDuplicate(item);
  4046. }
  4047. };
  4048. SmartArray.prototype.indexOf = function (value) {
  4049. var position = this.data.indexOf(value);
  4050. if (position >= this.length) {
  4051. return -1;
  4052. }
  4053. return position;
  4054. };
  4055. // Statics
  4056. SmartArray._GlobalId = 0;
  4057. return SmartArray;
  4058. })();
  4059. BABYLON.SmartArray = SmartArray;
  4060. })(BABYLON || (BABYLON = {}));
  4061. var BABYLON;
  4062. (function (BABYLON) {
  4063. var SmartCollection = (function () {
  4064. function SmartCollection(capacity) {
  4065. if (capacity === void 0) { capacity = 10; }
  4066. this.count = 0;
  4067. this._initialCapacity = capacity;
  4068. this.items = {};
  4069. this._keys = new Array(this._initialCapacity);
  4070. }
  4071. SmartCollection.prototype.add = function (key, item) {
  4072. if (this.items[key] != undefined) {
  4073. return -1;
  4074. }
  4075. this.items[key] = item;
  4076. //literal keys are always strings, but we keep source type of key in _keys array
  4077. this._keys[this.count++] = key;
  4078. if (this.count > this._keys.length) {
  4079. this._keys.length *= 2;
  4080. }
  4081. return this.count;
  4082. };
  4083. SmartCollection.prototype.remove = function (key) {
  4084. if (this.items[key] == undefined) {
  4085. return -1;
  4086. }
  4087. return this.removeItemOfIndex(this.indexOf(key));
  4088. };
  4089. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4090. if (index < this.count && index > -1) {
  4091. delete this.items[this._keys[index]];
  4092. //here, shifting by hand is better optimised than .splice
  4093. while (index < this.count) {
  4094. this._keys[index] = this._keys[index + 1];
  4095. index++;
  4096. }
  4097. }
  4098. else {
  4099. return -1;
  4100. }
  4101. return --this.count;
  4102. };
  4103. SmartCollection.prototype.indexOf = function (key) {
  4104. for (var i = 0; i !== this.count; i++) {
  4105. if (this._keys[i] === key) {
  4106. return i;
  4107. }
  4108. }
  4109. return -1;
  4110. };
  4111. SmartCollection.prototype.item = function (key) {
  4112. return this.items[key];
  4113. };
  4114. SmartCollection.prototype.getAllKeys = function () {
  4115. if (this.count > 0) {
  4116. var keys = new Array(this.count);
  4117. for (var i = 0; i < this.count; i++) {
  4118. keys[i] = this._keys[i];
  4119. }
  4120. return keys;
  4121. }
  4122. else {
  4123. return undefined;
  4124. }
  4125. };
  4126. SmartCollection.prototype.getKeyByIndex = function (index) {
  4127. if (index < this.count && index > -1) {
  4128. return this._keys[index];
  4129. }
  4130. else {
  4131. return undefined;
  4132. }
  4133. };
  4134. SmartCollection.prototype.getItemByIndex = function (index) {
  4135. if (index < this.count && index > -1) {
  4136. return this.items[this._keys[index]];
  4137. }
  4138. else {
  4139. return undefined;
  4140. }
  4141. };
  4142. SmartCollection.prototype.empty = function () {
  4143. if (this.count > 0) {
  4144. this.count = 0;
  4145. this.items = {};
  4146. this._keys = new Array(this._initialCapacity);
  4147. }
  4148. };
  4149. SmartCollection.prototype.forEach = function (block) {
  4150. var key;
  4151. for (key in this.items) {
  4152. if (this.items.hasOwnProperty(key)) {
  4153. block(this.items[key]);
  4154. }
  4155. }
  4156. };
  4157. return SmartCollection;
  4158. })();
  4159. BABYLON.SmartCollection = SmartCollection;
  4160. })(BABYLON || (BABYLON = {}));
  4161. var BABYLON;
  4162. (function (BABYLON) {
  4163. // Screenshots
  4164. var screenshotCanvas;
  4165. var cloneValue = function (source, destinationObject) {
  4166. if (!source)
  4167. return null;
  4168. if (source instanceof BABYLON.Mesh) {
  4169. return null;
  4170. }
  4171. if (source instanceof BABYLON.SubMesh) {
  4172. return source.clone(destinationObject);
  4173. }
  4174. else if (source.clone) {
  4175. return source.clone();
  4176. }
  4177. return null;
  4178. };
  4179. var Tools = (function () {
  4180. function Tools() {
  4181. }
  4182. Tools.Instantiate = function (className) {
  4183. var arr = className.split(".");
  4184. var fn = (window || this);
  4185. for (var i = 0, len = arr.length; i < len; i++) {
  4186. fn = fn[arr[i]];
  4187. }
  4188. if (typeof fn !== "function") {
  4189. return null;
  4190. }
  4191. return fn;
  4192. };
  4193. Tools.SetImmediate = function (action) {
  4194. if (window.setImmediate) {
  4195. window.setImmediate(action);
  4196. }
  4197. else {
  4198. setTimeout(action, 1);
  4199. }
  4200. };
  4201. Tools.IsExponentOfTwo = function (value) {
  4202. var count = 1;
  4203. do {
  4204. count *= 2;
  4205. } while (count < value);
  4206. return count === value;
  4207. };
  4208. Tools.GetExponentOfTwo = function (value, max) {
  4209. var count = 1;
  4210. do {
  4211. count *= 2;
  4212. } while (count < value);
  4213. if (count > max)
  4214. count = max;
  4215. return count;
  4216. };
  4217. Tools.GetFilename = function (path) {
  4218. var index = path.lastIndexOf("/");
  4219. if (index < 0)
  4220. return path;
  4221. return path.substring(index + 1);
  4222. };
  4223. Tools.GetDOMTextContent = function (element) {
  4224. var result = "";
  4225. var child = element.firstChild;
  4226. while (child) {
  4227. if (child.nodeType === 3) {
  4228. result += child.textContent;
  4229. }
  4230. child = child.nextSibling;
  4231. }
  4232. return result;
  4233. };
  4234. Tools.ToDegrees = function (angle) {
  4235. return angle * 180 / Math.PI;
  4236. };
  4237. Tools.ToRadians = function (angle) {
  4238. return angle * Math.PI / 180;
  4239. };
  4240. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4241. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4242. var output = "";
  4243. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4244. var i = 0;
  4245. var bytes = new Uint8Array(buffer);
  4246. while (i < bytes.length) {
  4247. chr1 = bytes[i++];
  4248. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4249. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4250. enc1 = chr1 >> 2;
  4251. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4252. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4253. enc4 = chr3 & 63;
  4254. if (isNaN(chr2)) {
  4255. enc3 = enc4 = 64;
  4256. }
  4257. else if (isNaN(chr3)) {
  4258. enc4 = 64;
  4259. }
  4260. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4261. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4262. }
  4263. return "data:image/png;base64," + output;
  4264. };
  4265. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4266. if (bias === void 0) { bias = null; }
  4267. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4268. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4269. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4270. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4271. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4272. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4273. }
  4274. if (bias) {
  4275. minimum.x -= minimum.x * bias.x + bias.y;
  4276. minimum.y -= minimum.y * bias.x + bias.y;
  4277. minimum.z -= minimum.z * bias.x + bias.y;
  4278. maximum.x += maximum.x * bias.x + bias.y;
  4279. maximum.y += maximum.y * bias.x + bias.y;
  4280. maximum.z += maximum.z * bias.x + bias.y;
  4281. }
  4282. return {
  4283. minimum: minimum,
  4284. maximum: maximum
  4285. };
  4286. };
  4287. Tools.ExtractMinAndMax = function (positions, start, count, bias) {
  4288. if (bias === void 0) { bias = null; }
  4289. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4290. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4291. for (var index = start; index < start + count; index++) {
  4292. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4293. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4294. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4295. }
  4296. if (bias) {
  4297. minimum.x -= minimum.x * bias.x + bias.y;
  4298. minimum.y -= minimum.y * bias.x + bias.y;
  4299. minimum.z -= minimum.z * bias.x + bias.y;
  4300. maximum.x += maximum.x * bias.x + bias.y;
  4301. maximum.y += maximum.y * bias.x + bias.y;
  4302. maximum.z += maximum.z * bias.x + bias.y;
  4303. }
  4304. return {
  4305. minimum: minimum,
  4306. maximum: maximum
  4307. };
  4308. };
  4309. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4310. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4311. return undefined;
  4312. return Array.isArray(obj) ? obj : [obj];
  4313. };
  4314. // Misc.
  4315. Tools.GetPointerPrefix = function () {
  4316. var eventPrefix = "pointer";
  4317. // Check if pointer events are supported
  4318. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4319. eventPrefix = "mouse";
  4320. }
  4321. return eventPrefix;
  4322. };
  4323. Tools.QueueNewFrame = function (func) {
  4324. if (window.requestAnimationFrame)
  4325. window.requestAnimationFrame(func);
  4326. else if (window.msRequestAnimationFrame)
  4327. window.msRequestAnimationFrame(func);
  4328. else if (window.webkitRequestAnimationFrame)
  4329. window.webkitRequestAnimationFrame(func);
  4330. else if (window.mozRequestAnimationFrame)
  4331. window.mozRequestAnimationFrame(func);
  4332. else if (window.oRequestAnimationFrame)
  4333. window.oRequestAnimationFrame(func);
  4334. else {
  4335. window.setTimeout(func, 16);
  4336. }
  4337. };
  4338. Tools.RequestFullscreen = function (element) {
  4339. if (element.requestFullscreen)
  4340. element.requestFullscreen();
  4341. else if (element.msRequestFullscreen)
  4342. element.msRequestFullscreen();
  4343. else if (element.webkitRequestFullscreen)
  4344. element.webkitRequestFullscreen();
  4345. else if (element.mozRequestFullScreen)
  4346. element.mozRequestFullScreen();
  4347. };
  4348. Tools.ExitFullscreen = function () {
  4349. if (document.exitFullscreen) {
  4350. document.exitFullscreen();
  4351. }
  4352. else if (document.mozCancelFullScreen) {
  4353. document.mozCancelFullScreen();
  4354. }
  4355. else if (document.webkitCancelFullScreen) {
  4356. document.webkitCancelFullScreen();
  4357. }
  4358. else if (document.msCancelFullScreen) {
  4359. document.msCancelFullScreen();
  4360. }
  4361. };
  4362. // External files
  4363. Tools.CleanUrl = function (url) {
  4364. url = url.replace(/#/mg, "%23");
  4365. return url;
  4366. };
  4367. Tools.LoadImage = function (url, onload, onerror, database) {
  4368. if (url instanceof ArrayBuffer) {
  4369. url = Tools.EncodeArrayBufferTobase64(url);
  4370. }
  4371. url = Tools.CleanUrl(url);
  4372. var img = new Image();
  4373. if (url.substr(0, 5) !== "data:") {
  4374. if (Tools.CorsBehavior) {
  4375. switch (typeof (Tools.CorsBehavior)) {
  4376. case "function":
  4377. var result = Tools.CorsBehavior(url);
  4378. if (result) {
  4379. img.crossOrigin = result;
  4380. }
  4381. break;
  4382. case "string":
  4383. default:
  4384. img.crossOrigin = Tools.CorsBehavior;
  4385. break;
  4386. }
  4387. }
  4388. }
  4389. img.onload = function () {
  4390. onload(img);
  4391. };
  4392. img.onerror = function (err) {
  4393. Tools.Error("Error while trying to load texture: " + url);
  4394. if (Tools.UseFallbackTexture) {
  4395. 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";
  4396. onload(img);
  4397. }
  4398. else {
  4399. onerror();
  4400. }
  4401. };
  4402. var noIndexedDB = function () {
  4403. img.src = url;
  4404. };
  4405. var loadFromIndexedDB = function () {
  4406. database.loadImageFromDB(url, img);
  4407. };
  4408. //ANY database to do!
  4409. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4410. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4411. }
  4412. else {
  4413. if (url.indexOf("file:") === -1) {
  4414. noIndexedDB();
  4415. }
  4416. else {
  4417. try {
  4418. var textureName = url.substring(5);
  4419. var blobURL;
  4420. try {
  4421. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4422. }
  4423. catch (ex) {
  4424. // Chrome doesn't support oneTimeOnly parameter
  4425. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4426. }
  4427. img.src = blobURL;
  4428. }
  4429. catch (e) {
  4430. img.src = null;
  4431. }
  4432. }
  4433. }
  4434. return img;
  4435. };
  4436. //ANY
  4437. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4438. url = Tools.CleanUrl(url);
  4439. var noIndexedDB = function () {
  4440. var request = new XMLHttpRequest();
  4441. var loadUrl = Tools.BaseUrl + url;
  4442. request.open('GET', loadUrl, true);
  4443. if (useArrayBuffer) {
  4444. request.responseType = "arraybuffer";
  4445. }
  4446. request.onprogress = progressCallBack;
  4447. request.onreadystatechange = function () {
  4448. if (request.readyState === 4) {
  4449. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4450. callback(!useArrayBuffer ? request.responseText : request.response);
  4451. }
  4452. else {
  4453. if (onError) {
  4454. onError();
  4455. }
  4456. else {
  4457. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4458. }
  4459. }
  4460. }
  4461. };
  4462. request.send(null);
  4463. };
  4464. var loadFromIndexedDB = function () {
  4465. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4466. };
  4467. if (url.indexOf("file:") !== -1) {
  4468. var fileName = url.substring(5).toLowerCase();
  4469. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4470. }
  4471. else {
  4472. // Caching all files
  4473. if (database && database.enableSceneOffline) {
  4474. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4475. }
  4476. else {
  4477. noIndexedDB();
  4478. }
  4479. }
  4480. };
  4481. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4482. var reader = new FileReader();
  4483. reader.onload = function (e) {
  4484. //target doesn't have result from ts 1.3
  4485. callback(e.target['result']);
  4486. };
  4487. reader.onprogress = progressCallback;
  4488. reader.readAsDataURL(fileToLoad);
  4489. };
  4490. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4491. var reader = new FileReader();
  4492. reader.onerror = function (e) {
  4493. Tools.Log("Error while reading file: " + fileToLoad.name);
  4494. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4495. };
  4496. reader.onload = function (e) {
  4497. //target doesn't have result from ts 1.3
  4498. callback(e.target['result']);
  4499. };
  4500. reader.onprogress = progressCallBack;
  4501. if (!useArrayBuffer) {
  4502. // Asynchronous read
  4503. reader.readAsText(fileToLoad);
  4504. }
  4505. else {
  4506. reader.readAsArrayBuffer(fileToLoad);
  4507. }
  4508. };
  4509. //returns a downloadable url to a file content.
  4510. Tools.FileAsURL = function (content) {
  4511. var fileBlob = new Blob([content]);
  4512. var url = window.URL || window.webkitURL;
  4513. var link = url.createObjectURL(fileBlob);
  4514. return link;
  4515. };
  4516. // Misc.
  4517. Tools.Format = function (value, decimals) {
  4518. if (decimals === void 0) { decimals = 2; }
  4519. return value.toFixed(decimals);
  4520. };
  4521. Tools.CheckExtends = function (v, min, max) {
  4522. if (v.x < min.x)
  4523. min.x = v.x;
  4524. if (v.y < min.y)
  4525. min.y = v.y;
  4526. if (v.z < min.z)
  4527. min.z = v.z;
  4528. if (v.x > max.x)
  4529. max.x = v.x;
  4530. if (v.y > max.y)
  4531. max.y = v.y;
  4532. if (v.z > max.z)
  4533. max.z = v.z;
  4534. };
  4535. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4536. for (var prop in source) {
  4537. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4538. continue;
  4539. }
  4540. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4541. continue;
  4542. }
  4543. var sourceValue = source[prop];
  4544. var typeOfSourceValue = typeof sourceValue;
  4545. if (typeOfSourceValue === "function") {
  4546. continue;
  4547. }
  4548. if (typeOfSourceValue === "object") {
  4549. if (sourceValue instanceof Array) {
  4550. destination[prop] = [];
  4551. if (sourceValue.length > 0) {
  4552. if (typeof sourceValue[0] == "object") {
  4553. for (var index = 0; index < sourceValue.length; index++) {
  4554. var clonedValue = cloneValue(sourceValue[index], destination);
  4555. if (destination[prop].indexOf(clonedValue) === -1) {
  4556. destination[prop].push(clonedValue);
  4557. }
  4558. }
  4559. }
  4560. else {
  4561. destination[prop] = sourceValue.slice(0);
  4562. }
  4563. }
  4564. }
  4565. else {
  4566. destination[prop] = cloneValue(sourceValue, destination);
  4567. }
  4568. }
  4569. else {
  4570. destination[prop] = sourceValue;
  4571. }
  4572. }
  4573. };
  4574. Tools.IsEmpty = function (obj) {
  4575. for (var i in obj) {
  4576. return false;
  4577. }
  4578. return true;
  4579. };
  4580. Tools.RegisterTopRootEvents = function (events) {
  4581. for (var index = 0; index < events.length; index++) {
  4582. var event = events[index];
  4583. window.addEventListener(event.name, event.handler, false);
  4584. try {
  4585. if (window.parent) {
  4586. window.parent.addEventListener(event.name, event.handler, false);
  4587. }
  4588. }
  4589. catch (e) {
  4590. }
  4591. }
  4592. };
  4593. Tools.UnregisterTopRootEvents = function (events) {
  4594. for (var index = 0; index < events.length; index++) {
  4595. var event = events[index];
  4596. window.removeEventListener(event.name, event.handler);
  4597. try {
  4598. if (window.parent) {
  4599. window.parent.removeEventListener(event.name, event.handler);
  4600. }
  4601. }
  4602. catch (e) {
  4603. }
  4604. }
  4605. };
  4606. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4607. // Read the contents of the framebuffer
  4608. var numberOfChannelsByLine = width * 4;
  4609. var halfHeight = height / 2;
  4610. //Reading datas from WebGL
  4611. var data = engine.readPixels(0, 0, width, height);
  4612. //To flip image on Y axis.
  4613. for (var i = 0; i < halfHeight; i++) {
  4614. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4615. var currentCell = j + i * numberOfChannelsByLine;
  4616. var targetLine = height - i - 1;
  4617. var targetCell = j + targetLine * numberOfChannelsByLine;
  4618. var temp = data[currentCell];
  4619. data[currentCell] = data[targetCell];
  4620. data[targetCell] = temp;
  4621. }
  4622. }
  4623. // Create a 2D canvas to store the result
  4624. if (!screenshotCanvas) {
  4625. screenshotCanvas = document.createElement('canvas');
  4626. }
  4627. screenshotCanvas.width = width;
  4628. screenshotCanvas.height = height;
  4629. var context = screenshotCanvas.getContext('2d');
  4630. // Copy the pixels to a 2D canvas
  4631. var imageData = context.createImageData(width, height);
  4632. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4633. var castData = imageData.data;
  4634. castData.set(data);
  4635. context.putImageData(imageData, 0, 0);
  4636. var base64Image = screenshotCanvas.toDataURL();
  4637. if (successCallback) {
  4638. successCallback(base64Image);
  4639. }
  4640. else {
  4641. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4642. if (("download" in document.createElement("a"))) {
  4643. var a = window.document.createElement("a");
  4644. a.href = base64Image;
  4645. var date = new Date();
  4646. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4647. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4648. window.document.body.appendChild(a);
  4649. a.addEventListener("click", function () {
  4650. a.parentElement.removeChild(a);
  4651. });
  4652. a.click();
  4653. }
  4654. else {
  4655. var newWindow = window.open("");
  4656. var img = newWindow.document.createElement("img");
  4657. img.src = base64Image;
  4658. newWindow.document.body.appendChild(img);
  4659. }
  4660. }
  4661. };
  4662. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4663. var width;
  4664. var height;
  4665. //If a precision value is specified
  4666. if (size.precision) {
  4667. width = Math.round(engine.getRenderWidth() * size.precision);
  4668. height = Math.round(width / engine.getAspectRatio(camera));
  4669. size = { width: width, height: height };
  4670. }
  4671. else if (size.width && size.height) {
  4672. width = size.width;
  4673. height = size.height;
  4674. }
  4675. else if (size.width && !size.height) {
  4676. width = size.width;
  4677. height = Math.round(width / engine.getAspectRatio(camera));
  4678. size = { width: width, height: height };
  4679. }
  4680. else if (size.height && !size.width) {
  4681. height = size.height;
  4682. width = Math.round(height * engine.getAspectRatio(camera));
  4683. size = { width: width, height: height };
  4684. }
  4685. else if (!isNaN(size)) {
  4686. height = size;
  4687. width = size;
  4688. }
  4689. else {
  4690. Tools.Error("Invalid 'size' parameter !");
  4691. return;
  4692. }
  4693. var scene = camera.getScene();
  4694. var previousCamera = null;
  4695. if (scene.activeCamera !== camera) {
  4696. previousCamera = scene.activeCamera;
  4697. scene.activeCamera = camera;
  4698. }
  4699. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4700. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4701. texture.renderList = scene.meshes;
  4702. texture.onAfterRender = function () {
  4703. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4704. };
  4705. scene.incrementRenderId();
  4706. texture.render(true);
  4707. texture.dispose();
  4708. if (previousCamera) {
  4709. scene.activeCamera = previousCamera;
  4710. }
  4711. camera.getProjectionMatrix(true); // Force cache refresh;
  4712. };
  4713. // XHR response validator for local file scenario
  4714. Tools.ValidateXHRData = function (xhr, dataType) {
  4715. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4716. if (dataType === void 0) { dataType = 7; }
  4717. try {
  4718. if (dataType & 1) {
  4719. if (xhr.responseText && xhr.responseText.length > 0) {
  4720. return true;
  4721. }
  4722. else if (dataType === 1) {
  4723. return false;
  4724. }
  4725. }
  4726. if (dataType & 2) {
  4727. // Check header width and height since there is no "TGA" magic number
  4728. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4729. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4730. return true;
  4731. }
  4732. else if (dataType === 2) {
  4733. return false;
  4734. }
  4735. }
  4736. if (dataType & 4) {
  4737. // Check for the "DDS" magic number
  4738. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4739. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4740. return true;
  4741. }
  4742. else {
  4743. return false;
  4744. }
  4745. }
  4746. }
  4747. catch (e) {
  4748. }
  4749. return false;
  4750. };
  4751. Object.defineProperty(Tools, "NoneLogLevel", {
  4752. get: function () {
  4753. return Tools._NoneLogLevel;
  4754. },
  4755. enumerable: true,
  4756. configurable: true
  4757. });
  4758. Object.defineProperty(Tools, "MessageLogLevel", {
  4759. get: function () {
  4760. return Tools._MessageLogLevel;
  4761. },
  4762. enumerable: true,
  4763. configurable: true
  4764. });
  4765. Object.defineProperty(Tools, "WarningLogLevel", {
  4766. get: function () {
  4767. return Tools._WarningLogLevel;
  4768. },
  4769. enumerable: true,
  4770. configurable: true
  4771. });
  4772. Object.defineProperty(Tools, "ErrorLogLevel", {
  4773. get: function () {
  4774. return Tools._ErrorLogLevel;
  4775. },
  4776. enumerable: true,
  4777. configurable: true
  4778. });
  4779. Object.defineProperty(Tools, "AllLogLevel", {
  4780. get: function () {
  4781. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4782. },
  4783. enumerable: true,
  4784. configurable: true
  4785. });
  4786. Tools._AddLogEntry = function (entry) {
  4787. Tools._LogCache = entry + Tools._LogCache;
  4788. if (Tools.OnNewCacheEntry) {
  4789. Tools.OnNewCacheEntry(entry);
  4790. }
  4791. };
  4792. Tools._FormatMessage = function (message) {
  4793. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4794. var date = new Date();
  4795. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4796. };
  4797. Tools._LogDisabled = function (message) {
  4798. // nothing to do
  4799. };
  4800. Tools._LogEnabled = function (message) {
  4801. var formattedMessage = Tools._FormatMessage(message);
  4802. console.log("BJS - " + formattedMessage);
  4803. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4804. Tools._AddLogEntry(entry);
  4805. };
  4806. Tools._WarnDisabled = function (message) {
  4807. // nothing to do
  4808. };
  4809. Tools._WarnEnabled = function (message) {
  4810. var formattedMessage = Tools._FormatMessage(message);
  4811. console.warn("BJS - " + formattedMessage);
  4812. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4813. Tools._AddLogEntry(entry);
  4814. };
  4815. Tools._ErrorDisabled = function (message) {
  4816. // nothing to do
  4817. };
  4818. Tools._ErrorEnabled = function (message) {
  4819. Tools.errorsCount++;
  4820. var formattedMessage = Tools._FormatMessage(message);
  4821. console.error("BJS - " + formattedMessage);
  4822. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4823. Tools._AddLogEntry(entry);
  4824. };
  4825. Object.defineProperty(Tools, "LogCache", {
  4826. get: function () {
  4827. return Tools._LogCache;
  4828. },
  4829. enumerable: true,
  4830. configurable: true
  4831. });
  4832. Tools.ClearLogCache = function () {
  4833. Tools._LogCache = "";
  4834. Tools.errorsCount = 0;
  4835. };
  4836. Object.defineProperty(Tools, "LogLevels", {
  4837. set: function (level) {
  4838. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4839. Tools.Log = Tools._LogEnabled;
  4840. }
  4841. else {
  4842. Tools.Log = Tools._LogDisabled;
  4843. }
  4844. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4845. Tools.Warn = Tools._WarnEnabled;
  4846. }
  4847. else {
  4848. Tools.Warn = Tools._WarnDisabled;
  4849. }
  4850. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4851. Tools.Error = Tools._ErrorEnabled;
  4852. }
  4853. else {
  4854. Tools.Error = Tools._ErrorDisabled;
  4855. }
  4856. },
  4857. enumerable: true,
  4858. configurable: true
  4859. });
  4860. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4861. get: function () {
  4862. return Tools._PerformanceNoneLogLevel;
  4863. },
  4864. enumerable: true,
  4865. configurable: true
  4866. });
  4867. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4868. get: function () {
  4869. return Tools._PerformanceUserMarkLogLevel;
  4870. },
  4871. enumerable: true,
  4872. configurable: true
  4873. });
  4874. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4875. get: function () {
  4876. return Tools._PerformanceConsoleLogLevel;
  4877. },
  4878. enumerable: true,
  4879. configurable: true
  4880. });
  4881. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4882. set: function (level) {
  4883. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4884. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4885. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4886. return;
  4887. }
  4888. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4889. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4890. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4891. return;
  4892. }
  4893. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4894. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4895. },
  4896. enumerable: true,
  4897. configurable: true
  4898. });
  4899. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4900. };
  4901. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4902. };
  4903. Tools._StartUserMark = function (counterName, condition) {
  4904. if (condition === void 0) { condition = true; }
  4905. if (!condition || !Tools._performance.mark) {
  4906. return;
  4907. }
  4908. Tools._performance.mark(counterName + "-Begin");
  4909. };
  4910. Tools._EndUserMark = function (counterName, condition) {
  4911. if (condition === void 0) { condition = true; }
  4912. if (!condition || !Tools._performance.mark) {
  4913. return;
  4914. }
  4915. Tools._performance.mark(counterName + "-End");
  4916. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4917. };
  4918. Tools._StartPerformanceConsole = function (counterName, condition) {
  4919. if (condition === void 0) { condition = true; }
  4920. if (!condition) {
  4921. return;
  4922. }
  4923. Tools._StartUserMark(counterName, condition);
  4924. if (console.time) {
  4925. console.time(counterName);
  4926. }
  4927. };
  4928. Tools._EndPerformanceConsole = function (counterName, condition) {
  4929. if (condition === void 0) { condition = true; }
  4930. if (!condition) {
  4931. return;
  4932. }
  4933. Tools._EndUserMark(counterName, condition);
  4934. if (console.time) {
  4935. console.timeEnd(counterName);
  4936. }
  4937. };
  4938. Object.defineProperty(Tools, "Now", {
  4939. get: function () {
  4940. if (window.performance && window.performance.now) {
  4941. return window.performance.now();
  4942. }
  4943. return new Date().getTime();
  4944. },
  4945. enumerable: true,
  4946. configurable: true
  4947. });
  4948. Tools.BaseUrl = "";
  4949. Tools.CorsBehavior = "anonymous";
  4950. Tools.UseFallbackTexture = true;
  4951. // Logs
  4952. Tools._NoneLogLevel = 0;
  4953. Tools._MessageLogLevel = 1;
  4954. Tools._WarningLogLevel = 2;
  4955. Tools._ErrorLogLevel = 4;
  4956. Tools._LogCache = "";
  4957. Tools.errorsCount = 0;
  4958. Tools.Log = Tools._LogEnabled;
  4959. Tools.Warn = Tools._WarnEnabled;
  4960. Tools.Error = Tools._ErrorEnabled;
  4961. // Performances
  4962. Tools._PerformanceNoneLogLevel = 0;
  4963. Tools._PerformanceUserMarkLogLevel = 1;
  4964. Tools._PerformanceConsoleLogLevel = 2;
  4965. Tools._performance = window.performance;
  4966. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4967. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4968. return Tools;
  4969. })();
  4970. BABYLON.Tools = Tools;
  4971. /**
  4972. * An implementation of a loop for asynchronous functions.
  4973. */
  4974. var AsyncLoop = (function () {
  4975. /**
  4976. * Constroctor.
  4977. * @param iterations the number of iterations.
  4978. * @param _fn the function to run each iteration
  4979. * @param _successCallback the callback that will be called upon succesful execution
  4980. * @param offset starting offset.
  4981. */
  4982. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4983. if (offset === void 0) { offset = 0; }
  4984. this.iterations = iterations;
  4985. this._fn = _fn;
  4986. this._successCallback = _successCallback;
  4987. this.index = offset - 1;
  4988. this._done = false;
  4989. }
  4990. /**
  4991. * Execute the next iteration. Must be called after the last iteration was finished.
  4992. */
  4993. AsyncLoop.prototype.executeNext = function () {
  4994. if (!this._done) {
  4995. if (this.index + 1 < this.iterations) {
  4996. ++this.index;
  4997. this._fn(this);
  4998. }
  4999. else {
  5000. this.breakLoop();
  5001. }
  5002. }
  5003. };
  5004. /**
  5005. * Break the loop and run the success callback.
  5006. */
  5007. AsyncLoop.prototype.breakLoop = function () {
  5008. this._done = true;
  5009. this._successCallback();
  5010. };
  5011. /**
  5012. * Helper function
  5013. */
  5014. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5015. if (offset === void 0) { offset = 0; }
  5016. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5017. loop.executeNext();
  5018. return loop;
  5019. };
  5020. /**
  5021. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5022. * @param iterations total number of iterations
  5023. * @param syncedIterations number of synchronous iterations in each async iteration.
  5024. * @param fn the function to call each iteration.
  5025. * @param callback a success call back that will be called when iterating stops.
  5026. * @param breakFunction a break condition (optional)
  5027. * @param timeout timeout settings for the setTimeout function. default - 0.
  5028. * @constructor
  5029. */
  5030. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5031. if (timeout === void 0) { timeout = 0; }
  5032. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5033. if (breakFunction && breakFunction())
  5034. loop.breakLoop();
  5035. else {
  5036. setTimeout(function () {
  5037. for (var i = 0; i < syncedIterations; ++i) {
  5038. var iteration = (loop.index * syncedIterations) + i;
  5039. if (iteration >= iterations)
  5040. break;
  5041. fn(iteration);
  5042. if (breakFunction && breakFunction()) {
  5043. loop.breakLoop();
  5044. break;
  5045. }
  5046. }
  5047. loop.executeNext();
  5048. }, timeout);
  5049. }
  5050. }, callback);
  5051. };
  5052. return AsyncLoop;
  5053. })();
  5054. BABYLON.AsyncLoop = AsyncLoop;
  5055. })(BABYLON || (BABYLON = {}));
  5056. var BABYLON;
  5057. (function (BABYLON) {
  5058. var Internals;
  5059. (function (Internals) {
  5060. var _AlphaState = (function () {
  5061. function _AlphaState() {
  5062. this._isAlphaBlendDirty = false;
  5063. this._isBlendFunctionParametersDirty = false;
  5064. this._alphaBlend = false;
  5065. this._blendFunctionParameters = new Array(4);
  5066. }
  5067. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5068. get: function () {
  5069. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5070. },
  5071. enumerable: true,
  5072. configurable: true
  5073. });
  5074. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5075. get: function () {
  5076. return this._alphaBlend;
  5077. },
  5078. set: function (value) {
  5079. if (this._alphaBlend === value) {
  5080. return;
  5081. }
  5082. this._alphaBlend = value;
  5083. this._isAlphaBlendDirty = true;
  5084. },
  5085. enumerable: true,
  5086. configurable: true
  5087. });
  5088. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5089. if (this._blendFunctionParameters[0] === value0 &&
  5090. this._blendFunctionParameters[1] === value1 &&
  5091. this._blendFunctionParameters[2] === value2 &&
  5092. this._blendFunctionParameters[3] === value3) {
  5093. return;
  5094. }
  5095. this._blendFunctionParameters[0] = value0;
  5096. this._blendFunctionParameters[1] = value1;
  5097. this._blendFunctionParameters[2] = value2;
  5098. this._blendFunctionParameters[3] = value3;
  5099. this._isBlendFunctionParametersDirty = true;
  5100. };
  5101. _AlphaState.prototype.reset = function () {
  5102. this._alphaBlend = false;
  5103. this._blendFunctionParameters[0] = null;
  5104. this._blendFunctionParameters[1] = null;
  5105. this._blendFunctionParameters[2] = null;
  5106. this._blendFunctionParameters[3] = null;
  5107. this._isAlphaBlendDirty = true;
  5108. this._isBlendFunctionParametersDirty = false;
  5109. };
  5110. _AlphaState.prototype.apply = function (gl) {
  5111. if (!this.isDirty) {
  5112. return;
  5113. }
  5114. // Alpha blend
  5115. if (this._isAlphaBlendDirty) {
  5116. if (this._alphaBlend) {
  5117. gl.enable(gl.BLEND);
  5118. }
  5119. else {
  5120. gl.disable(gl.BLEND);
  5121. }
  5122. this._isAlphaBlendDirty = false;
  5123. }
  5124. // Alpha function
  5125. if (this._isBlendFunctionParametersDirty) {
  5126. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5127. this._isBlendFunctionParametersDirty = false;
  5128. }
  5129. };
  5130. return _AlphaState;
  5131. })();
  5132. Internals._AlphaState = _AlphaState;
  5133. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5134. })(BABYLON || (BABYLON = {}));
  5135. var BABYLON;
  5136. (function (BABYLON) {
  5137. var Internals;
  5138. (function (Internals) {
  5139. var _DepthCullingState = (function () {
  5140. function _DepthCullingState() {
  5141. this._isDepthTestDirty = false;
  5142. this._isDepthMaskDirty = false;
  5143. this._isDepthFuncDirty = false;
  5144. this._isCullFaceDirty = false;
  5145. this._isCullDirty = false;
  5146. this._isZOffsetDirty = false;
  5147. }
  5148. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5149. get: function () {
  5150. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5151. },
  5152. enumerable: true,
  5153. configurable: true
  5154. });
  5155. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5156. get: function () {
  5157. return this._zOffset;
  5158. },
  5159. set: function (value) {
  5160. if (this._zOffset === value) {
  5161. return;
  5162. }
  5163. this._zOffset = value;
  5164. this._isZOffsetDirty = true;
  5165. },
  5166. enumerable: true,
  5167. configurable: true
  5168. });
  5169. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5170. get: function () {
  5171. return this._cullFace;
  5172. },
  5173. set: function (value) {
  5174. if (this._cullFace === value) {
  5175. return;
  5176. }
  5177. this._cullFace = value;
  5178. this._isCullFaceDirty = true;
  5179. },
  5180. enumerable: true,
  5181. configurable: true
  5182. });
  5183. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5184. get: function () {
  5185. return this._cull;
  5186. },
  5187. set: function (value) {
  5188. if (this._cull === value) {
  5189. return;
  5190. }
  5191. this._cull = value;
  5192. this._isCullDirty = true;
  5193. },
  5194. enumerable: true,
  5195. configurable: true
  5196. });
  5197. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5198. get: function () {
  5199. return this._depthFunc;
  5200. },
  5201. set: function (value) {
  5202. if (this._depthFunc === value) {
  5203. return;
  5204. }
  5205. this._depthFunc = value;
  5206. this._isDepthFuncDirty = true;
  5207. },
  5208. enumerable: true,
  5209. configurable: true
  5210. });
  5211. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5212. get: function () {
  5213. return this._depthMask;
  5214. },
  5215. set: function (value) {
  5216. if (this._depthMask === value) {
  5217. return;
  5218. }
  5219. this._depthMask = value;
  5220. this._isDepthMaskDirty = true;
  5221. },
  5222. enumerable: true,
  5223. configurable: true
  5224. });
  5225. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5226. get: function () {
  5227. return this._depthTest;
  5228. },
  5229. set: function (value) {
  5230. if (this._depthTest === value) {
  5231. return;
  5232. }
  5233. this._depthTest = value;
  5234. this._isDepthTestDirty = true;
  5235. },
  5236. enumerable: true,
  5237. configurable: true
  5238. });
  5239. _DepthCullingState.prototype.reset = function () {
  5240. this._depthMask = true;
  5241. this._depthTest = true;
  5242. this._depthFunc = null;
  5243. this._cull = null;
  5244. this._cullFace = null;
  5245. this._zOffset = 0;
  5246. this._isDepthTestDirty = true;
  5247. this._isDepthMaskDirty = true;
  5248. this._isDepthFuncDirty = false;
  5249. this._isCullFaceDirty = false;
  5250. this._isCullDirty = false;
  5251. this._isZOffsetDirty = false;
  5252. };
  5253. _DepthCullingState.prototype.apply = function (gl) {
  5254. if (!this.isDirty) {
  5255. return;
  5256. }
  5257. // Cull
  5258. if (this._isCullDirty) {
  5259. if (this.cull) {
  5260. gl.enable(gl.CULL_FACE);
  5261. }
  5262. else {
  5263. gl.disable(gl.CULL_FACE);
  5264. }
  5265. this._isCullDirty = false;
  5266. }
  5267. // Cull face
  5268. if (this._isCullFaceDirty) {
  5269. gl.cullFace(this.cullFace);
  5270. this._isCullFaceDirty = false;
  5271. }
  5272. // Depth mask
  5273. if (this._isDepthMaskDirty) {
  5274. gl.depthMask(this.depthMask);
  5275. this._isDepthMaskDirty = false;
  5276. }
  5277. // Depth test
  5278. if (this._isDepthTestDirty) {
  5279. if (this.depthTest) {
  5280. gl.enable(gl.DEPTH_TEST);
  5281. }
  5282. else {
  5283. gl.disable(gl.DEPTH_TEST);
  5284. }
  5285. this._isDepthTestDirty = false;
  5286. }
  5287. // Depth func
  5288. if (this._isDepthFuncDirty) {
  5289. gl.depthFunc(this.depthFunc);
  5290. this._isDepthFuncDirty = false;
  5291. }
  5292. // zOffset
  5293. if (this._isZOffsetDirty) {
  5294. if (this.zOffset) {
  5295. gl.enable(gl.POLYGON_OFFSET_FILL);
  5296. gl.polygonOffset(this.zOffset, 0);
  5297. }
  5298. else {
  5299. gl.disable(gl.POLYGON_OFFSET_FILL);
  5300. }
  5301. this._isZOffsetDirty = false;
  5302. }
  5303. };
  5304. return _DepthCullingState;
  5305. })();
  5306. Internals._DepthCullingState = _DepthCullingState;
  5307. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5308. })(BABYLON || (BABYLON = {}));
  5309. var BABYLON;
  5310. (function (BABYLON) {
  5311. var compileShader = function (gl, source, type, defines) {
  5312. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5313. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5314. gl.compileShader(shader);
  5315. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5316. throw new Error(gl.getShaderInfoLog(shader));
  5317. }
  5318. return shader;
  5319. };
  5320. var getWebGLTextureType = function (gl, type) {
  5321. var textureType = gl.UNSIGNED_BYTE;
  5322. if (type === Engine.TEXTURETYPE_FLOAT)
  5323. textureType = gl.FLOAT;
  5324. return textureType;
  5325. };
  5326. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5327. var magFilter = gl.NEAREST;
  5328. var minFilter = gl.NEAREST;
  5329. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5330. magFilter = gl.LINEAR;
  5331. if (generateMipMaps) {
  5332. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5333. }
  5334. else {
  5335. minFilter = gl.LINEAR;
  5336. }
  5337. }
  5338. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5339. magFilter = gl.LINEAR;
  5340. if (generateMipMaps) {
  5341. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5342. }
  5343. else {
  5344. minFilter = gl.LINEAR;
  5345. }
  5346. }
  5347. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5348. magFilter = gl.NEAREST;
  5349. if (generateMipMaps) {
  5350. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5351. }
  5352. else {
  5353. minFilter = gl.NEAREST;
  5354. }
  5355. }
  5356. return {
  5357. min: minFilter,
  5358. mag: magFilter
  5359. };
  5360. };
  5361. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5362. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5363. var engine = scene.getEngine();
  5364. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5365. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5366. gl.bindTexture(gl.TEXTURE_2D, texture);
  5367. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5368. texture._baseWidth = width;
  5369. texture._baseHeight = height;
  5370. texture._width = potWidth;
  5371. texture._height = potHeight;
  5372. texture.isReady = true;
  5373. processFunction(potWidth, potHeight);
  5374. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5375. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5376. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5377. if (!noMipmap && !isCompressed) {
  5378. gl.generateMipmap(gl.TEXTURE_2D);
  5379. }
  5380. gl.bindTexture(gl.TEXTURE_2D, null);
  5381. engine.resetTextureCache();
  5382. scene._removePendingData(texture);
  5383. if (onLoad) {
  5384. onLoad();
  5385. }
  5386. };
  5387. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5388. var img;
  5389. var onload = function () {
  5390. loadedImages[index] = img;
  5391. loadedImages._internalCount++;
  5392. scene._removePendingData(img);
  5393. if (loadedImages._internalCount === 6) {
  5394. onfinish(loadedImages);
  5395. }
  5396. };
  5397. var onerror = function () {
  5398. scene._removePendingData(img);
  5399. };
  5400. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5401. scene._addPendingData(img);
  5402. };
  5403. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5404. var loadedImages = [];
  5405. loadedImages._internalCount = 0;
  5406. for (var index = 0; index < 6; index++) {
  5407. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5408. }
  5409. };
  5410. var EngineCapabilities = (function () {
  5411. function EngineCapabilities() {
  5412. }
  5413. return EngineCapabilities;
  5414. })();
  5415. BABYLON.EngineCapabilities = EngineCapabilities;
  5416. /**
  5417. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5418. */
  5419. var Engine = (function () {
  5420. /**
  5421. * @constructor
  5422. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5423. * @param {boolean} [antialias] - enable antialias
  5424. * @param options - further options to be sent to the getContext function
  5425. */
  5426. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5427. var _this = this;
  5428. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5429. // Public members
  5430. this.isFullscreen = false;
  5431. this.isPointerLock = false;
  5432. this.cullBackFaces = true;
  5433. this.renderEvenInBackground = true;
  5434. // To enable/disable IDB support and avoid XHR on .manifest
  5435. this.enableOfflineSupport = true;
  5436. this.scenes = new Array();
  5437. this._windowIsBackground = false;
  5438. this._webGLVersion = "1.0";
  5439. this._drawCalls = 0;
  5440. this._renderingQueueLaunched = false;
  5441. this._activeRenderLoops = [];
  5442. // FPS
  5443. this.fpsRange = 60;
  5444. this.previousFramesDuration = [];
  5445. this.fps = 60;
  5446. this.deltaTime = 0;
  5447. // States
  5448. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5449. this._alphaState = new BABYLON.Internals._AlphaState();
  5450. this._alphaMode = Engine.ALPHA_DISABLE;
  5451. // Cache
  5452. this._loadedTexturesCache = new Array();
  5453. this._maxTextureChannels = 16;
  5454. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5455. this._compiledEffects = {};
  5456. this._uintIndicesCurrentlySet = false;
  5457. this._renderingCanvas = canvas;
  5458. options = options || {};
  5459. options.antialias = antialias;
  5460. if (options.preserveDrawingBuffer === undefined) {
  5461. options.preserveDrawingBuffer = false;
  5462. }
  5463. // GL
  5464. //try {
  5465. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5466. // if (this._gl) {
  5467. // this._webGLVersion = "2.0";
  5468. // }
  5469. //} catch (e) {
  5470. // // Do nothing
  5471. //}
  5472. if (!this._gl) {
  5473. try {
  5474. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5475. }
  5476. catch (e) {
  5477. throw new Error("WebGL not supported");
  5478. }
  5479. }
  5480. if (!this._gl) {
  5481. throw new Error("WebGL not supported");
  5482. }
  5483. this._onBlur = function () {
  5484. _this._windowIsBackground = true;
  5485. };
  5486. this._onFocus = function () {
  5487. _this._windowIsBackground = false;
  5488. };
  5489. window.addEventListener("blur", this._onBlur);
  5490. window.addEventListener("focus", this._onFocus);
  5491. // Viewport
  5492. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  5493. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  5494. this.resize();
  5495. // Caps
  5496. this._caps = new EngineCapabilities();
  5497. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5498. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5499. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5500. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5501. // Infos
  5502. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5503. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5504. if (rendererInfo != null) {
  5505. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5506. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5507. }
  5508. if (!this._glVendor) {
  5509. this._glVendor = "Unknown vendor";
  5510. }
  5511. if (!this._glRenderer) {
  5512. this._glRenderer = "Unknown renderer";
  5513. }
  5514. // Extensions
  5515. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5516. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5517. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5518. 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');
  5519. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5520. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5521. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5522. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5523. this._caps.highPrecisionShaderSupported = true;
  5524. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5525. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5526. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  5527. if (this._gl.getShaderPrecisionFormat) {
  5528. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5529. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5530. }
  5531. // Depth buffer
  5532. this.setDepthBuffer(true);
  5533. this.setDepthFunctionToLessOrEqual();
  5534. this.setDepthWrite(true);
  5535. // Fullscreen
  5536. this._onFullscreenChange = function () {
  5537. if (document.fullscreen !== undefined) {
  5538. _this.isFullscreen = document.fullscreen;
  5539. }
  5540. else if (document.mozFullScreen !== undefined) {
  5541. _this.isFullscreen = document.mozFullScreen;
  5542. }
  5543. else if (document.webkitIsFullScreen !== undefined) {
  5544. _this.isFullscreen = document.webkitIsFullScreen;
  5545. }
  5546. else if (document.msIsFullScreen !== undefined) {
  5547. _this.isFullscreen = document.msIsFullScreen;
  5548. }
  5549. // Pointer lock
  5550. if (_this.isFullscreen && _this._pointerLockRequested) {
  5551. canvas.requestPointerLock = canvas.requestPointerLock ||
  5552. canvas.msRequestPointerLock ||
  5553. canvas.mozRequestPointerLock ||
  5554. canvas.webkitRequestPointerLock;
  5555. if (canvas.requestPointerLock) {
  5556. canvas.requestPointerLock();
  5557. }
  5558. }
  5559. };
  5560. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5561. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5562. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5563. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5564. // Pointer lock
  5565. this._onPointerLockChange = function () {
  5566. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5567. document.webkitPointerLockElement === canvas ||
  5568. document.msPointerLockElement === canvas ||
  5569. document.pointerLockElement === canvas);
  5570. };
  5571. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5572. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5573. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5574. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5575. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5576. Engine.audioEngine = new BABYLON.AudioEngine();
  5577. }
  5578. //default loading screen
  5579. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5580. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5581. }
  5582. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5583. get: function () {
  5584. return Engine._ALPHA_DISABLE;
  5585. },
  5586. enumerable: true,
  5587. configurable: true
  5588. });
  5589. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5590. get: function () {
  5591. return Engine._ALPHA_ONEONE;
  5592. },
  5593. enumerable: true,
  5594. configurable: true
  5595. });
  5596. Object.defineProperty(Engine, "ALPHA_ADD", {
  5597. get: function () {
  5598. return Engine._ALPHA_ADD;
  5599. },
  5600. enumerable: true,
  5601. configurable: true
  5602. });
  5603. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5604. get: function () {
  5605. return Engine._ALPHA_COMBINE;
  5606. },
  5607. enumerable: true,
  5608. configurable: true
  5609. });
  5610. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5611. get: function () {
  5612. return Engine._ALPHA_SUBTRACT;
  5613. },
  5614. enumerable: true,
  5615. configurable: true
  5616. });
  5617. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5618. get: function () {
  5619. return Engine._ALPHA_MULTIPLY;
  5620. },
  5621. enumerable: true,
  5622. configurable: true
  5623. });
  5624. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5625. get: function () {
  5626. return Engine._ALPHA_MAXIMIZED;
  5627. },
  5628. enumerable: true,
  5629. configurable: true
  5630. });
  5631. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5632. get: function () {
  5633. return Engine._DELAYLOADSTATE_NONE;
  5634. },
  5635. enumerable: true,
  5636. configurable: true
  5637. });
  5638. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5639. get: function () {
  5640. return Engine._DELAYLOADSTATE_LOADED;
  5641. },
  5642. enumerable: true,
  5643. configurable: true
  5644. });
  5645. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5646. get: function () {
  5647. return Engine._DELAYLOADSTATE_LOADING;
  5648. },
  5649. enumerable: true,
  5650. configurable: true
  5651. });
  5652. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5653. get: function () {
  5654. return Engine._DELAYLOADSTATE_NOTLOADED;
  5655. },
  5656. enumerable: true,
  5657. configurable: true
  5658. });
  5659. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5660. get: function () {
  5661. return Engine._TEXTUREFORMAT_ALPHA;
  5662. },
  5663. enumerable: true,
  5664. configurable: true
  5665. });
  5666. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5667. get: function () {
  5668. return Engine._TEXTUREFORMAT_LUMINANCE;
  5669. },
  5670. enumerable: true,
  5671. configurable: true
  5672. });
  5673. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5674. get: function () {
  5675. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5676. },
  5677. enumerable: true,
  5678. configurable: true
  5679. });
  5680. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5681. get: function () {
  5682. return Engine._TEXTUREFORMAT_RGB;
  5683. },
  5684. enumerable: true,
  5685. configurable: true
  5686. });
  5687. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5688. get: function () {
  5689. return Engine._TEXTUREFORMAT_RGBA;
  5690. },
  5691. enumerable: true,
  5692. configurable: true
  5693. });
  5694. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5695. get: function () {
  5696. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5697. },
  5698. enumerable: true,
  5699. configurable: true
  5700. });
  5701. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5702. get: function () {
  5703. return Engine._TEXTURETYPE_FLOAT;
  5704. },
  5705. enumerable: true,
  5706. configurable: true
  5707. });
  5708. Object.defineProperty(Engine, "Version", {
  5709. get: function () {
  5710. return "2.4.0-alpha";
  5711. },
  5712. enumerable: true,
  5713. configurable: true
  5714. });
  5715. Object.defineProperty(Engine.prototype, "webGLVersion", {
  5716. get: function () {
  5717. return this._webGLVersion;
  5718. },
  5719. enumerable: true,
  5720. configurable: true
  5721. });
  5722. Engine.prototype._prepareWorkingCanvas = function () {
  5723. if (this._workingCanvas) {
  5724. return;
  5725. }
  5726. this._workingCanvas = document.createElement("canvas");
  5727. this._workingContext = this._workingCanvas.getContext("2d");
  5728. };
  5729. Engine.prototype.resetTextureCache = function () {
  5730. for (var index = 0; index < this._maxTextureChannels; index++) {
  5731. this._activeTexturesCache[index] = null;
  5732. }
  5733. };
  5734. Engine.prototype.getGlInfo = function () {
  5735. return {
  5736. vendor: this._glVendor,
  5737. renderer: this._glRenderer,
  5738. version: this._glVersion
  5739. };
  5740. };
  5741. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5742. if (useScreen === void 0) { useScreen = false; }
  5743. var viewport = camera.viewport;
  5744. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5745. };
  5746. Engine.prototype.getRenderWidth = function (useScreen) {
  5747. if (useScreen === void 0) { useScreen = false; }
  5748. if (!useScreen && this._currentRenderTarget) {
  5749. return this._currentRenderTarget._width;
  5750. }
  5751. return this._renderingCanvas.width;
  5752. };
  5753. Engine.prototype.getRenderHeight = function (useScreen) {
  5754. if (useScreen === void 0) { useScreen = false; }
  5755. if (!useScreen && this._currentRenderTarget) {
  5756. return this._currentRenderTarget._height;
  5757. }
  5758. return this._renderingCanvas.height;
  5759. };
  5760. Engine.prototype.getRenderingCanvas = function () {
  5761. return this._renderingCanvas;
  5762. };
  5763. Engine.prototype.getRenderingCanvasClientRect = function () {
  5764. return this._renderingCanvas.getBoundingClientRect();
  5765. };
  5766. Engine.prototype.setHardwareScalingLevel = function (level) {
  5767. this._hardwareScalingLevel = level;
  5768. this.resize();
  5769. };
  5770. Engine.prototype.getHardwareScalingLevel = function () {
  5771. return this._hardwareScalingLevel;
  5772. };
  5773. Engine.prototype.getLoadedTexturesCache = function () {
  5774. return this._loadedTexturesCache;
  5775. };
  5776. Engine.prototype.getCaps = function () {
  5777. return this._caps;
  5778. };
  5779. Object.defineProperty(Engine.prototype, "drawCalls", {
  5780. get: function () {
  5781. return this._drawCalls;
  5782. },
  5783. enumerable: true,
  5784. configurable: true
  5785. });
  5786. // Methods
  5787. Engine.prototype.resetDrawCalls = function () {
  5788. this._drawCalls = 0;
  5789. };
  5790. Engine.prototype.setDepthFunctionToGreater = function () {
  5791. this._depthCullingState.depthFunc = this._gl.GREATER;
  5792. };
  5793. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5794. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5795. };
  5796. Engine.prototype.setDepthFunctionToLess = function () {
  5797. this._depthCullingState.depthFunc = this._gl.LESS;
  5798. };
  5799. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5800. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5801. };
  5802. /**
  5803. * stop executing a render loop function and remove it from the execution array
  5804. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5805. */
  5806. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5807. if (!renderFunction) {
  5808. this._activeRenderLoops = [];
  5809. return;
  5810. }
  5811. var index = this._activeRenderLoops.indexOf(renderFunction);
  5812. if (index >= 0) {
  5813. this._activeRenderLoops.splice(index, 1);
  5814. }
  5815. };
  5816. Engine.prototype._renderLoop = function () {
  5817. var shouldRender = true;
  5818. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5819. shouldRender = false;
  5820. }
  5821. if (shouldRender) {
  5822. // Start new frame
  5823. this.beginFrame();
  5824. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5825. var renderFunction = this._activeRenderLoops[index];
  5826. renderFunction();
  5827. }
  5828. // Present
  5829. this.endFrame();
  5830. }
  5831. if (this._activeRenderLoops.length > 0) {
  5832. // Register new frame
  5833. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5834. }
  5835. else {
  5836. this._renderingQueueLaunched = false;
  5837. }
  5838. };
  5839. /**
  5840. * Register and execute a render loop. The engine can have more than one render function.
  5841. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5842. * @example
  5843. * engine.runRenderLoop(function () {
  5844. * scene.render()
  5845. * })
  5846. */
  5847. Engine.prototype.runRenderLoop = function (renderFunction) {
  5848. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5849. return;
  5850. }
  5851. this._activeRenderLoops.push(renderFunction);
  5852. if (!this._renderingQueueLaunched) {
  5853. this._renderingQueueLaunched = true;
  5854. this._bindedRenderFunction = this._renderLoop.bind(this);
  5855. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5856. }
  5857. };
  5858. /**
  5859. * Toggle full screen mode.
  5860. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5861. */
  5862. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5863. if (this.isFullscreen) {
  5864. BABYLON.Tools.ExitFullscreen();
  5865. }
  5866. else {
  5867. this._pointerLockRequested = requestPointerLock;
  5868. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5869. }
  5870. };
  5871. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5872. this.applyStates();
  5873. if (backBuffer) {
  5874. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5875. }
  5876. if (depthStencil && this._depthCullingState.depthMask) {
  5877. this._gl.clearDepth(1.0);
  5878. }
  5879. var mode = 0;
  5880. if (backBuffer) {
  5881. mode |= this._gl.COLOR_BUFFER_BIT;
  5882. }
  5883. if (depthStencil && this._depthCullingState.depthMask) {
  5884. mode |= this._gl.DEPTH_BUFFER_BIT;
  5885. }
  5886. this._gl.clear(mode);
  5887. };
  5888. /**
  5889. * Set the WebGL's viewport
  5890. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5891. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5892. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5893. */
  5894. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5895. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5896. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5897. var x = viewport.x || 0;
  5898. var y = viewport.y || 0;
  5899. this._cachedViewport = viewport;
  5900. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5901. };
  5902. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5903. this._cachedViewport = null;
  5904. this._gl.viewport(x, y, width, height);
  5905. };
  5906. Engine.prototype.beginFrame = function () {
  5907. this._measureFps();
  5908. };
  5909. Engine.prototype.endFrame = function () {
  5910. //this.flushFramebuffer();
  5911. };
  5912. /**
  5913. * resize the view according to the canvas' size.
  5914. * @example
  5915. * window.addEventListener("resize", function () {
  5916. * engine.resize();
  5917. * });
  5918. */
  5919. Engine.prototype.resize = function () {
  5920. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5921. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5922. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5923. for (var index = 0; index < this.scenes.length; index++) {
  5924. var scene = this.scenes[index];
  5925. if (scene.debugLayer.isVisible()) {
  5926. scene.debugLayer._syncPositions();
  5927. }
  5928. }
  5929. };
  5930. /**
  5931. * force a specific size of the canvas
  5932. * @param {number} width - the new canvas' width
  5933. * @param {number} height - the new canvas' height
  5934. */
  5935. Engine.prototype.setSize = function (width, height) {
  5936. this._renderingCanvas.width = width;
  5937. this._renderingCanvas.height = height;
  5938. for (var index = 0; index < this.scenes.length; index++) {
  5939. var scene = this.scenes[index];
  5940. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5941. var cam = scene.cameras[camIndex];
  5942. cam._currentRenderId = 0;
  5943. }
  5944. }
  5945. };
  5946. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5947. this._currentRenderTarget = texture;
  5948. var gl = this._gl;
  5949. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5950. if (texture.isCube) {
  5951. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5952. }
  5953. else {
  5954. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5955. }
  5956. this._gl.viewport(0, 0, texture._width, texture._height);
  5957. this.wipeCaches();
  5958. };
  5959. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5960. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5961. this._currentRenderTarget = null;
  5962. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5963. var gl = this._gl;
  5964. gl.bindTexture(gl.TEXTURE_2D, texture);
  5965. gl.generateMipmap(gl.TEXTURE_2D);
  5966. gl.bindTexture(gl.TEXTURE_2D, null);
  5967. }
  5968. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5969. };
  5970. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5971. if (texture.generateMipMaps) {
  5972. var gl = this._gl;
  5973. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5974. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5975. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5976. }
  5977. };
  5978. Engine.prototype.flushFramebuffer = function () {
  5979. this._gl.flush();
  5980. };
  5981. Engine.prototype.restoreDefaultFramebuffer = function () {
  5982. this._currentRenderTarget = null;
  5983. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5984. this.setViewport(this._cachedViewport);
  5985. this.wipeCaches();
  5986. };
  5987. // VBOs
  5988. Engine.prototype._resetVertexBufferBinding = function () {
  5989. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5990. this._cachedVertexBuffers = null;
  5991. };
  5992. Engine.prototype.createVertexBuffer = function (vertices) {
  5993. var vbo = this._gl.createBuffer();
  5994. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5995. if (vertices instanceof Float32Array) {
  5996. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5997. }
  5998. else {
  5999. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  6000. }
  6001. this._resetVertexBufferBinding();
  6002. vbo.references = 1;
  6003. return vbo;
  6004. };
  6005. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  6006. var vbo = this._gl.createBuffer();
  6007. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  6008. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6009. this._resetVertexBufferBinding();
  6010. vbo.references = 1;
  6011. return vbo;
  6012. };
  6013. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  6014. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6015. if (offset === undefined) {
  6016. offset = 0;
  6017. }
  6018. if (vertices instanceof Float32Array) {
  6019. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  6020. }
  6021. else {
  6022. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6023. }
  6024. this._resetVertexBufferBinding();
  6025. };
  6026. Engine.prototype._resetIndexBufferBinding = function () {
  6027. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  6028. this._cachedIndexBuffer = null;
  6029. };
  6030. Engine.prototype.createIndexBuffer = function (indices) {
  6031. var vbo = this._gl.createBuffer();
  6032. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  6033. // Check for 32 bits indices
  6034. var arrayBuffer;
  6035. var need32Bits = false;
  6036. if (this._caps.uintIndices) {
  6037. for (var index = 0; index < indices.length; index++) {
  6038. if (indices[index] > 65535) {
  6039. need32Bits = true;
  6040. break;
  6041. }
  6042. }
  6043. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6044. }
  6045. else {
  6046. arrayBuffer = new Uint16Array(indices);
  6047. }
  6048. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6049. this._resetIndexBufferBinding();
  6050. vbo.references = 1;
  6051. vbo.is32Bits = need32Bits;
  6052. return vbo;
  6053. };
  6054. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6055. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6056. this._cachedVertexBuffers = vertexBuffer;
  6057. this._cachedEffectForVertexBuffers = effect;
  6058. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6059. var offset = 0;
  6060. for (var index = 0; index < vertexDeclaration.length; index++) {
  6061. var order = effect.getAttributeLocation(index);
  6062. if (order >= 0) {
  6063. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6064. }
  6065. offset += vertexDeclaration[index] * 4;
  6066. }
  6067. }
  6068. if (this._cachedIndexBuffer !== indexBuffer) {
  6069. this._cachedIndexBuffer = indexBuffer;
  6070. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6071. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6072. }
  6073. };
  6074. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  6075. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6076. this._cachedVertexBuffers = vertexBuffers;
  6077. this._cachedEffectForVertexBuffers = effect;
  6078. var attributes = effect.getAttributesNames();
  6079. for (var index = 0; index < attributes.length; index++) {
  6080. var order = effect.getAttributeLocation(index);
  6081. if (order >= 0) {
  6082. var vertexBuffer = vertexBuffers[attributes[index]];
  6083. if (!vertexBuffer) {
  6084. continue;
  6085. }
  6086. var stride = vertexBuffer.getStrideSize();
  6087. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6088. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6089. }
  6090. }
  6091. }
  6092. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  6093. this._cachedIndexBuffer = indexBuffer;
  6094. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6095. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6096. }
  6097. };
  6098. Engine.prototype._releaseBuffer = function (buffer) {
  6099. buffer.references--;
  6100. if (buffer.references === 0) {
  6101. this._gl.deleteBuffer(buffer);
  6102. return true;
  6103. }
  6104. return false;
  6105. };
  6106. Engine.prototype.createInstancesBuffer = function (capacity) {
  6107. var buffer = this._gl.createBuffer();
  6108. buffer.capacity = capacity;
  6109. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6110. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6111. return buffer;
  6112. };
  6113. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6114. this._gl.deleteBuffer(buffer);
  6115. };
  6116. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6117. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6118. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6119. for (var index = 0; index < 4; index++) {
  6120. var offsetLocation = offsetLocations[index];
  6121. this._gl.enableVertexAttribArray(offsetLocation);
  6122. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6123. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6124. }
  6125. };
  6126. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6127. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6128. for (var index = 0; index < 4; index++) {
  6129. var offsetLocation = offsetLocations[index];
  6130. this._gl.disableVertexAttribArray(offsetLocation);
  6131. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6132. }
  6133. };
  6134. Engine.prototype.applyStates = function () {
  6135. this._depthCullingState.apply(this._gl);
  6136. this._alphaState.apply(this._gl);
  6137. };
  6138. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6139. // Apply states
  6140. this.applyStates();
  6141. this._drawCalls++;
  6142. // Render
  6143. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6144. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6145. if (instancesCount) {
  6146. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6147. return;
  6148. }
  6149. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6150. };
  6151. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6152. // Apply states
  6153. this.applyStates();
  6154. this._drawCalls++;
  6155. if (instancesCount) {
  6156. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6157. return;
  6158. }
  6159. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6160. };
  6161. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  6162. // Apply states
  6163. this.applyStates();
  6164. this._drawCalls++;
  6165. if (instancesCount) {
  6166. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6167. return;
  6168. }
  6169. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6170. };
  6171. // Shaders
  6172. Engine.prototype._releaseEffect = function (effect) {
  6173. if (this._compiledEffects[effect._key]) {
  6174. delete this._compiledEffects[effect._key];
  6175. if (effect.getProgram()) {
  6176. this._gl.deleteProgram(effect.getProgram());
  6177. }
  6178. }
  6179. };
  6180. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6181. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6182. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6183. var name = vertex + "+" + fragment + "@" + defines;
  6184. if (this._compiledEffects[name]) {
  6185. return this._compiledEffects[name];
  6186. }
  6187. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6188. effect._key = name;
  6189. this._compiledEffects[name] = effect;
  6190. return effect;
  6191. };
  6192. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6193. if (uniformsNames === void 0) { uniformsNames = []; }
  6194. if (samplers === void 0) { samplers = []; }
  6195. if (defines === void 0) { defines = ""; }
  6196. return this.createEffect({
  6197. vertex: "particles",
  6198. fragmentElement: fragmentName
  6199. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6200. };
  6201. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6202. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6203. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6204. var shaderProgram = this._gl.createProgram();
  6205. this._gl.attachShader(shaderProgram, vertexShader);
  6206. this._gl.attachShader(shaderProgram, fragmentShader);
  6207. this._gl.linkProgram(shaderProgram);
  6208. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6209. if (!linked) {
  6210. var error = this._gl.getProgramInfoLog(shaderProgram);
  6211. if (error) {
  6212. throw new Error(error);
  6213. }
  6214. }
  6215. this._gl.deleteShader(vertexShader);
  6216. this._gl.deleteShader(fragmentShader);
  6217. return shaderProgram;
  6218. };
  6219. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6220. var results = [];
  6221. for (var index = 0; index < uniformsNames.length; index++) {
  6222. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6223. }
  6224. return results;
  6225. };
  6226. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6227. var results = [];
  6228. for (var index = 0; index < attributesNames.length; index++) {
  6229. try {
  6230. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6231. }
  6232. catch (e) {
  6233. results.push(-1);
  6234. }
  6235. }
  6236. return results;
  6237. };
  6238. Engine.prototype.enableEffect = function (effect) {
  6239. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6240. if (effect && effect.onBind) {
  6241. effect.onBind(effect);
  6242. }
  6243. return;
  6244. }
  6245. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6246. // Use program
  6247. this._gl.useProgram(effect.getProgram());
  6248. for (var i in this._vertexAttribArrays) {
  6249. //make sure this is a number)
  6250. var iAsNumber = +i;
  6251. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  6252. continue;
  6253. }
  6254. this._vertexAttribArrays[iAsNumber] = false;
  6255. this._gl.disableVertexAttribArray(iAsNumber);
  6256. }
  6257. var attributesCount = effect.getAttributesCount();
  6258. for (var index = 0; index < attributesCount; index++) {
  6259. // Attributes
  6260. var order = effect.getAttributeLocation(index);
  6261. if (order >= 0) {
  6262. this._vertexAttribArrays[order] = true;
  6263. this._gl.enableVertexAttribArray(order);
  6264. }
  6265. }
  6266. this._currentEffect = effect;
  6267. if (effect.onBind) {
  6268. effect.onBind(effect);
  6269. }
  6270. };
  6271. Engine.prototype.setArray = function (uniform, array) {
  6272. if (!uniform)
  6273. return;
  6274. this._gl.uniform1fv(uniform, array);
  6275. };
  6276. Engine.prototype.setArray2 = function (uniform, array) {
  6277. if (!uniform || array.length % 2 !== 0)
  6278. return;
  6279. this._gl.uniform2fv(uniform, array);
  6280. };
  6281. Engine.prototype.setArray3 = function (uniform, array) {
  6282. if (!uniform || array.length % 3 !== 0)
  6283. return;
  6284. this._gl.uniform3fv(uniform, array);
  6285. };
  6286. Engine.prototype.setArray4 = function (uniform, array) {
  6287. if (!uniform || array.length % 4 !== 0)
  6288. return;
  6289. this._gl.uniform4fv(uniform, array);
  6290. };
  6291. Engine.prototype.setMatrices = function (uniform, matrices) {
  6292. if (!uniform)
  6293. return;
  6294. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6295. };
  6296. Engine.prototype.setMatrix = function (uniform, matrix) {
  6297. if (!uniform)
  6298. return;
  6299. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6300. };
  6301. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6302. if (!uniform)
  6303. return;
  6304. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6305. };
  6306. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6307. if (!uniform)
  6308. return;
  6309. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6310. };
  6311. Engine.prototype.setFloat = function (uniform, value) {
  6312. if (!uniform)
  6313. return;
  6314. this._gl.uniform1f(uniform, value);
  6315. };
  6316. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6317. if (!uniform)
  6318. return;
  6319. this._gl.uniform2f(uniform, x, y);
  6320. };
  6321. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6322. if (!uniform)
  6323. return;
  6324. this._gl.uniform3f(uniform, x, y, z);
  6325. };
  6326. Engine.prototype.setBool = function (uniform, bool) {
  6327. if (!uniform)
  6328. return;
  6329. this._gl.uniform1i(uniform, bool);
  6330. };
  6331. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6332. if (!uniform)
  6333. return;
  6334. this._gl.uniform4f(uniform, x, y, z, w);
  6335. };
  6336. Engine.prototype.setColor3 = function (uniform, color3) {
  6337. if (!uniform)
  6338. return;
  6339. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6340. };
  6341. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6342. if (!uniform)
  6343. return;
  6344. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6345. };
  6346. // States
  6347. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6348. if (zOffset === void 0) { zOffset = 0; }
  6349. if (reverseSide === void 0) { reverseSide = false; }
  6350. // Culling
  6351. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6352. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6353. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6354. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6355. if (culling) {
  6356. this._depthCullingState.cullFace = cullFace;
  6357. this._depthCullingState.cull = true;
  6358. }
  6359. else {
  6360. this._depthCullingState.cull = false;
  6361. }
  6362. }
  6363. // Z offset
  6364. this._depthCullingState.zOffset = zOffset;
  6365. };
  6366. Engine.prototype.setDepthBuffer = function (enable) {
  6367. this._depthCullingState.depthTest = enable;
  6368. };
  6369. Engine.prototype.getDepthWrite = function () {
  6370. return this._depthCullingState.depthMask;
  6371. };
  6372. Engine.prototype.setDepthWrite = function (enable) {
  6373. this._depthCullingState.depthMask = enable;
  6374. };
  6375. Engine.prototype.setColorWrite = function (enable) {
  6376. this._gl.colorMask(enable, enable, enable, enable);
  6377. };
  6378. Engine.prototype.setAlphaMode = function (mode) {
  6379. if (this._alphaMode === mode) {
  6380. return;
  6381. }
  6382. switch (mode) {
  6383. case Engine.ALPHA_DISABLE:
  6384. this.setDepthWrite(true);
  6385. this._alphaState.alphaBlend = false;
  6386. break;
  6387. case Engine.ALPHA_COMBINE:
  6388. this.setDepthWrite(false);
  6389. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6390. this._alphaState.alphaBlend = true;
  6391. break;
  6392. case Engine.ALPHA_ONEONE:
  6393. this.setDepthWrite(false);
  6394. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6395. this._alphaState.alphaBlend = true;
  6396. break;
  6397. case Engine.ALPHA_ADD:
  6398. this.setDepthWrite(false);
  6399. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6400. this._alphaState.alphaBlend = true;
  6401. break;
  6402. case Engine.ALPHA_SUBTRACT:
  6403. this.setDepthWrite(false);
  6404. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6405. this._alphaState.alphaBlend = true;
  6406. break;
  6407. case Engine.ALPHA_MULTIPLY:
  6408. this.setDepthWrite(false);
  6409. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6410. this._alphaState.alphaBlend = true;
  6411. break;
  6412. case Engine.ALPHA_MAXIMIZED:
  6413. this.setDepthWrite(false);
  6414. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6415. this._alphaState.alphaBlend = true;
  6416. break;
  6417. }
  6418. this._alphaMode = mode;
  6419. };
  6420. Engine.prototype.getAlphaMode = function () {
  6421. return this._alphaMode;
  6422. };
  6423. Engine.prototype.setAlphaTesting = function (enable) {
  6424. this._alphaTest = enable;
  6425. };
  6426. Engine.prototype.getAlphaTesting = function () {
  6427. return this._alphaTest;
  6428. };
  6429. // Textures
  6430. Engine.prototype.wipeCaches = function () {
  6431. this.resetTextureCache();
  6432. this._currentEffect = null;
  6433. this._depthCullingState.reset();
  6434. this._alphaState.reset();
  6435. this._cachedVertexBuffers = null;
  6436. this._cachedIndexBuffer = null;
  6437. this._cachedEffectForVertexBuffers = null;
  6438. };
  6439. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6440. var gl = this._gl;
  6441. gl.bindTexture(gl.TEXTURE_2D, texture);
  6442. var magFilter = gl.NEAREST;
  6443. var minFilter = gl.NEAREST;
  6444. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6445. magFilter = gl.LINEAR;
  6446. minFilter = gl.LINEAR;
  6447. }
  6448. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6449. magFilter = gl.LINEAR;
  6450. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6451. }
  6452. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6453. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6454. gl.bindTexture(gl.TEXTURE_2D, null);
  6455. texture.samplingMode = samplingMode;
  6456. };
  6457. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6458. var _this = this;
  6459. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6460. if (onLoad === void 0) { onLoad = null; }
  6461. if (onError === void 0) { onError = null; }
  6462. if (buffer === void 0) { buffer = null; }
  6463. var texture = this._gl.createTexture();
  6464. var extension;
  6465. var fromData = false;
  6466. if (url.substr(0, 5) === "data:") {
  6467. fromData = true;
  6468. }
  6469. if (!fromData)
  6470. extension = url.substr(url.length - 4, 4).toLowerCase();
  6471. else {
  6472. var oldUrl = url;
  6473. fromData = oldUrl.split(':');
  6474. url = oldUrl;
  6475. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6476. }
  6477. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6478. var isTGA = (extension === ".tga");
  6479. scene._addPendingData(texture);
  6480. texture.url = url;
  6481. texture.noMipmap = noMipmap;
  6482. texture.references = 1;
  6483. texture.samplingMode = samplingMode;
  6484. this._loadedTexturesCache.push(texture);
  6485. var onerror = function () {
  6486. scene._removePendingData(texture);
  6487. if (onError) {
  6488. onError();
  6489. }
  6490. };
  6491. var callback;
  6492. if (isTGA) {
  6493. callback = function (arrayBuffer) {
  6494. var data = new Uint8Array(arrayBuffer);
  6495. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6496. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6497. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6498. }, onLoad, samplingMode);
  6499. };
  6500. if (!(fromData instanceof Array))
  6501. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6502. callback(arrayBuffer);
  6503. }, onerror, scene.database, true);
  6504. else
  6505. callback(buffer);
  6506. }
  6507. else if (isDDS) {
  6508. callback = function (data) {
  6509. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6510. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6511. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6512. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6513. }, onLoad, samplingMode);
  6514. };
  6515. if (!(fromData instanceof Array))
  6516. BABYLON.Tools.LoadFile(url, function (data) {
  6517. callback(data);
  6518. }, onerror, scene.database, true);
  6519. else
  6520. callback(buffer);
  6521. }
  6522. else {
  6523. var onload = function (img) {
  6524. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6525. var isPot = (img.width === potWidth && img.height === potHeight);
  6526. if (!isPot) {
  6527. _this._prepareWorkingCanvas();
  6528. _this._workingCanvas.width = potWidth;
  6529. _this._workingCanvas.height = potHeight;
  6530. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6531. _this._workingContext.imageSmoothingEnabled = false;
  6532. _this._workingContext.mozImageSmoothingEnabled = false;
  6533. _this._workingContext.oImageSmoothingEnabled = false;
  6534. _this._workingContext.webkitImageSmoothingEnabled = false;
  6535. _this._workingContext.msImageSmoothingEnabled = false;
  6536. }
  6537. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6538. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6539. _this._workingContext.imageSmoothingEnabled = true;
  6540. _this._workingContext.mozImageSmoothingEnabled = true;
  6541. _this._workingContext.oImageSmoothingEnabled = true;
  6542. _this._workingContext.webkitImageSmoothingEnabled = true;
  6543. _this._workingContext.msImageSmoothingEnabled = true;
  6544. }
  6545. }
  6546. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6547. }, onLoad, samplingMode);
  6548. };
  6549. if (!(fromData instanceof Array))
  6550. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6551. else
  6552. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6553. }
  6554. return texture;
  6555. };
  6556. Engine.prototype._getInternalFormat = function (format) {
  6557. var internalFormat = this._gl.RGBA;
  6558. switch (format) {
  6559. case Engine.TEXTUREFORMAT_ALPHA:
  6560. internalFormat = this._gl.ALPHA;
  6561. break;
  6562. case Engine.TEXTUREFORMAT_LUMINANCE:
  6563. internalFormat = this._gl.LUMINANCE;
  6564. break;
  6565. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6566. internalFormat = this._gl.LUMINANCE_ALPHA;
  6567. break;
  6568. case Engine.TEXTUREFORMAT_RGB:
  6569. internalFormat = this._gl.RGB;
  6570. break;
  6571. case Engine.TEXTUREFORMAT_RGBA:
  6572. internalFormat = this._gl.RGBA;
  6573. break;
  6574. }
  6575. return internalFormat;
  6576. };
  6577. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6578. if (compression === void 0) { compression = null; }
  6579. var internalFormat = this._getInternalFormat(format);
  6580. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6581. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6582. if (compression) {
  6583. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6584. }
  6585. else {
  6586. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6587. }
  6588. if (texture.generateMipMaps) {
  6589. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6590. }
  6591. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6592. this.resetTextureCache();
  6593. texture.isReady = true;
  6594. };
  6595. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6596. if (compression === void 0) { compression = null; }
  6597. var texture = this._gl.createTexture();
  6598. texture._baseWidth = width;
  6599. texture._baseHeight = height;
  6600. texture._width = width;
  6601. texture._height = height;
  6602. texture.references = 1;
  6603. this.updateRawTexture(texture, data, format, invertY, compression);
  6604. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6605. // Filters
  6606. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6607. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6608. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6609. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6610. texture.samplingMode = samplingMode;
  6611. this._loadedTexturesCache.push(texture);
  6612. return texture;
  6613. };
  6614. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6615. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6616. var texture = this._gl.createTexture();
  6617. texture._baseWidth = width;
  6618. texture._baseHeight = height;
  6619. if (forceExponantOfTwo) {
  6620. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6621. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6622. }
  6623. this.resetTextureCache();
  6624. texture._width = width;
  6625. texture._height = height;
  6626. texture.isReady = false;
  6627. texture.generateMipMaps = generateMipMaps;
  6628. texture.references = 1;
  6629. texture.samplingMode = samplingMode;
  6630. this.updateTextureSamplingMode(samplingMode, texture);
  6631. this._loadedTexturesCache.push(texture);
  6632. return texture;
  6633. };
  6634. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6635. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6636. if (texture.isCube) {
  6637. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6638. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6639. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6640. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6641. }
  6642. else {
  6643. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6644. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6645. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6646. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6647. }
  6648. };
  6649. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6650. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6651. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6652. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6653. if (texture.generateMipMaps) {
  6654. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6655. }
  6656. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6657. this.resetTextureCache();
  6658. texture.isReady = true;
  6659. };
  6660. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6661. if (texture._isDisabled) {
  6662. return;
  6663. }
  6664. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6665. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6666. try {
  6667. // Testing video texture support
  6668. if (this._videoTextureSupported === undefined) {
  6669. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6670. if (this._gl.getError() !== 0) {
  6671. this._videoTextureSupported = false;
  6672. }
  6673. else {
  6674. this._videoTextureSupported = true;
  6675. }
  6676. }
  6677. // Copy video through the current working canvas if video texture is not supported
  6678. if (!this._videoTextureSupported) {
  6679. if (!texture._workingCanvas) {
  6680. texture._workingCanvas = document.createElement("canvas");
  6681. texture._workingContext = texture._workingCanvas.getContext("2d");
  6682. texture._workingCanvas.width = texture._width;
  6683. texture._workingCanvas.height = texture._height;
  6684. }
  6685. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6686. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6687. }
  6688. else {
  6689. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6690. }
  6691. if (texture.generateMipMaps) {
  6692. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6693. }
  6694. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6695. this.resetTextureCache();
  6696. texture.isReady = true;
  6697. }
  6698. catch (ex) {
  6699. // Something unexpected
  6700. // Let's disable the texture
  6701. texture._isDisabled = true;
  6702. }
  6703. };
  6704. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6705. // old version had a "generateMipMaps" arg instead of options.
  6706. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6707. // in the same way, generateDepthBuffer is defaulted to true
  6708. var generateMipMaps = false;
  6709. var generateDepthBuffer = true;
  6710. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6711. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6712. if (options !== undefined) {
  6713. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6714. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6715. type = options.type === undefined ? type : options.type;
  6716. if (options.samplingMode !== undefined) {
  6717. samplingMode = options.samplingMode;
  6718. }
  6719. if (type === Engine.TEXTURETYPE_FLOAT) {
  6720. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6721. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6722. }
  6723. }
  6724. var gl = this._gl;
  6725. var texture = gl.createTexture();
  6726. gl.bindTexture(gl.TEXTURE_2D, texture);
  6727. var width = size.width || size;
  6728. var height = size.height || size;
  6729. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6730. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6731. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6732. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6733. }
  6734. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6735. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6736. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6737. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6738. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6739. var depthBuffer;
  6740. // Create the depth buffer
  6741. if (generateDepthBuffer) {
  6742. depthBuffer = gl.createRenderbuffer();
  6743. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6744. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6745. }
  6746. // Create the framebuffer
  6747. var framebuffer = gl.createFramebuffer();
  6748. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6749. if (generateDepthBuffer) {
  6750. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6751. }
  6752. if (generateMipMaps) {
  6753. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6754. }
  6755. // Unbind
  6756. gl.bindTexture(gl.TEXTURE_2D, null);
  6757. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6758. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6759. texture._framebuffer = framebuffer;
  6760. if (generateDepthBuffer) {
  6761. texture._depthBuffer = depthBuffer;
  6762. }
  6763. texture._width = width;
  6764. texture._height = height;
  6765. texture.isReady = true;
  6766. texture.generateMipMaps = generateMipMaps;
  6767. texture.references = 1;
  6768. texture.samplingMode = samplingMode;
  6769. this.resetTextureCache();
  6770. this._loadedTexturesCache.push(texture);
  6771. return texture;
  6772. };
  6773. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6774. var gl = this._gl;
  6775. var texture = gl.createTexture();
  6776. var generateMipMaps = true;
  6777. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6778. if (options !== undefined) {
  6779. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6780. if (options.samplingMode !== undefined) {
  6781. samplingMode = options.samplingMode;
  6782. }
  6783. }
  6784. texture.isCube = true;
  6785. texture.references = 1;
  6786. texture.generateMipMaps = generateMipMaps;
  6787. texture.references = 1;
  6788. texture.samplingMode = samplingMode;
  6789. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6790. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6791. for (var face = 0; face < 6; face++) {
  6792. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6793. }
  6794. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6795. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6796. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6797. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6798. // Create the depth buffer
  6799. var depthBuffer = gl.createRenderbuffer();
  6800. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6801. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6802. // Create the framebuffer
  6803. var framebuffer = gl.createFramebuffer();
  6804. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6805. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6806. // Mipmaps
  6807. if (texture.generateMipMaps) {
  6808. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6809. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6810. }
  6811. // Unbind
  6812. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6813. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6814. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6815. texture._framebuffer = framebuffer;
  6816. texture._depthBuffer = depthBuffer;
  6817. this.resetTextureCache();
  6818. texture._width = size;
  6819. texture._height = size;
  6820. texture.isReady = true;
  6821. return texture;
  6822. };
  6823. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  6824. var _this = this;
  6825. var gl = this._gl;
  6826. var texture = gl.createTexture();
  6827. texture.isCube = true;
  6828. texture.url = rootUrl;
  6829. texture.references = 1;
  6830. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6831. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6832. if (isDDS) {
  6833. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6834. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6835. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6836. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6837. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6838. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6839. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6840. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6841. }
  6842. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6843. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6844. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6845. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6846. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6847. _this.resetTextureCache();
  6848. texture._width = info.width;
  6849. texture._height = info.height;
  6850. texture.isReady = true;
  6851. }, null, null, true);
  6852. }
  6853. else {
  6854. cascadeLoad(rootUrl, scene, function (imgs) {
  6855. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6856. var height = width;
  6857. _this._prepareWorkingCanvas();
  6858. _this._workingCanvas.width = width;
  6859. _this._workingCanvas.height = height;
  6860. var faces = [
  6861. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6862. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6863. ];
  6864. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6865. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6866. for (var index = 0; index < faces.length; index++) {
  6867. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6868. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6869. }
  6870. if (!noMipmap) {
  6871. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6872. }
  6873. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6874. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6875. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6876. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6877. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6878. _this.resetTextureCache();
  6879. texture._width = width;
  6880. texture._height = height;
  6881. texture.isReady = true;
  6882. }, files);
  6883. }
  6884. return texture;
  6885. };
  6886. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  6887. var _this = this;
  6888. var gl = this._gl;
  6889. var texture = gl.createTexture();
  6890. scene._addPendingData(texture);
  6891. texture.isCube = true;
  6892. texture.references = 1;
  6893. texture.url = url;
  6894. var internalFormat = this._getInternalFormat(format);
  6895. var textureType = gl.UNSIGNED_BYTE;
  6896. if (type === Engine.TEXTURETYPE_FLOAT) {
  6897. textureType = gl.FLOAT;
  6898. }
  6899. var width = size;
  6900. var height = width;
  6901. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  6902. texture._width = width;
  6903. texture._height = height;
  6904. var onerror = function () {
  6905. scene._removePendingData(texture);
  6906. };
  6907. var internalCallback = function (data) {
  6908. var rgbeDataArrays = callback(data);
  6909. var facesIndex = [
  6910. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6911. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6912. ];
  6913. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6914. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6915. if (!noMipmap && isPot) {
  6916. if (mipmmapGenerator) {
  6917. var arrayTemp = [];
  6918. // Data are known to be in +X +Y +Z -X -Y -Z
  6919. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  6920. arrayTemp.push(rgbeDataArrays[0]); // +X
  6921. arrayTemp.push(rgbeDataArrays[3]); // -X
  6922. arrayTemp.push(rgbeDataArrays[1]); // +Y
  6923. arrayTemp.push(rgbeDataArrays[4]); // -Y
  6924. arrayTemp.push(rgbeDataArrays[2]); // +Z
  6925. arrayTemp.push(rgbeDataArrays[5]); // -Z
  6926. var mipData = mipmmapGenerator(arrayTemp);
  6927. for (var level = 0; level < mipData.length; level++) {
  6928. var mipSize = width >> level;
  6929. // mipData is order in +X -X +Y -Y +Z -Z
  6930. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  6931. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  6932. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  6933. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  6934. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  6935. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  6936. }
  6937. }
  6938. else {
  6939. // Data are known to be in +X +Y +Z -X -Y -Z
  6940. for (var index = 0; index < facesIndex.length; index++) {
  6941. var faceData = rgbeDataArrays[index];
  6942. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  6943. }
  6944. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6945. }
  6946. }
  6947. else {
  6948. noMipmap = true;
  6949. }
  6950. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  6951. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  6952. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  6953. }
  6954. else {
  6955. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6956. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6957. }
  6958. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6959. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6960. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6961. texture.isReady = true;
  6962. _this.resetTextureCache();
  6963. scene._removePendingData(texture);
  6964. };
  6965. BABYLON.Tools.LoadFile(url, function (data) {
  6966. internalCallback(data);
  6967. }, onerror, scene.database, true);
  6968. return texture;
  6969. };
  6970. ;
  6971. Engine.prototype._releaseTexture = function (texture) {
  6972. var gl = this._gl;
  6973. if (texture._framebuffer) {
  6974. gl.deleteFramebuffer(texture._framebuffer);
  6975. }
  6976. if (texture._depthBuffer) {
  6977. gl.deleteRenderbuffer(texture._depthBuffer);
  6978. }
  6979. gl.deleteTexture(texture);
  6980. // Unbind channels
  6981. this.unbindAllTextures();
  6982. var index = this._loadedTexturesCache.indexOf(texture);
  6983. if (index !== -1) {
  6984. this._loadedTexturesCache.splice(index, 1);
  6985. }
  6986. };
  6987. Engine.prototype.bindSamplers = function (effect) {
  6988. this._gl.useProgram(effect.getProgram());
  6989. var samplers = effect.getSamplers();
  6990. for (var index = 0; index < samplers.length; index++) {
  6991. var uniform = effect.getUniform(samplers[index]);
  6992. this._gl.uniform1i(uniform, index);
  6993. }
  6994. this._currentEffect = null;
  6995. };
  6996. Engine.prototype._bindTexture = function (channel, texture) {
  6997. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6998. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6999. this._activeTexturesCache[channel] = null;
  7000. };
  7001. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  7002. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  7003. };
  7004. Engine.prototype.unbindAllTextures = function () {
  7005. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  7006. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7007. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7008. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  7009. this._activeTexturesCache[channel] = null;
  7010. }
  7011. };
  7012. Engine.prototype.setTexture = function (channel, texture) {
  7013. if (channel < 0) {
  7014. return;
  7015. }
  7016. // Not ready?
  7017. if (!texture || !texture.isReady()) {
  7018. if (this._activeTexturesCache[channel] != null) {
  7019. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7020. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  7021. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  7022. this._activeTexturesCache[channel] = null;
  7023. }
  7024. return;
  7025. }
  7026. // Video
  7027. var alreadyActivated = false;
  7028. if (texture instanceof BABYLON.VideoTexture) {
  7029. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7030. alreadyActivated = true;
  7031. texture.update();
  7032. }
  7033. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  7034. texture.delayLoad();
  7035. return;
  7036. }
  7037. if (this._activeTexturesCache[channel] === texture) {
  7038. return;
  7039. }
  7040. this._activeTexturesCache[channel] = texture;
  7041. var internalTexture = texture.getInternalTexture();
  7042. if (!alreadyActivated) {
  7043. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7044. }
  7045. if (internalTexture.isCube) {
  7046. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  7047. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  7048. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  7049. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  7050. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  7051. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  7052. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  7053. }
  7054. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  7055. }
  7056. else {
  7057. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  7058. if (internalTexture._cachedWrapU !== texture.wrapU) {
  7059. internalTexture._cachedWrapU = texture.wrapU;
  7060. switch (texture.wrapU) {
  7061. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7062. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  7063. break;
  7064. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7065. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  7066. break;
  7067. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7068. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  7069. break;
  7070. }
  7071. }
  7072. if (internalTexture._cachedWrapV !== texture.wrapV) {
  7073. internalTexture._cachedWrapV = texture.wrapV;
  7074. switch (texture.wrapV) {
  7075. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7076. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  7077. break;
  7078. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7079. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  7080. break;
  7081. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7082. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  7083. break;
  7084. }
  7085. }
  7086. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  7087. }
  7088. };
  7089. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  7090. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  7091. var value = texture.anisotropicFilteringLevel;
  7092. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7093. value = 1;
  7094. }
  7095. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  7096. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  7097. texture._cachedAnisotropicFilteringLevel = value;
  7098. }
  7099. };
  7100. Engine.prototype.readPixels = function (x, y, width, height) {
  7101. var data = new Uint8Array(height * width * 4);
  7102. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  7103. return data;
  7104. };
  7105. Engine.prototype.releaseInternalTexture = function (texture) {
  7106. if (!texture) {
  7107. return;
  7108. }
  7109. texture.references--;
  7110. // Final reference ?
  7111. if (texture.references === 0) {
  7112. var texturesCache = this.getLoadedTexturesCache();
  7113. var index = texturesCache.indexOf(texture);
  7114. if (index > -1) {
  7115. texturesCache.splice(index, 1);
  7116. }
  7117. this._releaseTexture(texture);
  7118. }
  7119. };
  7120. // Dispose
  7121. Engine.prototype.dispose = function () {
  7122. this.hideLoadingUI();
  7123. this.stopRenderLoop();
  7124. // Release scenes
  7125. while (this.scenes.length) {
  7126. this.scenes[0].dispose();
  7127. }
  7128. // Release audio engine
  7129. Engine.audioEngine.dispose();
  7130. // Release effects
  7131. for (var name in this._compiledEffects) {
  7132. this._gl.deleteProgram(this._compiledEffects[name]._program);
  7133. }
  7134. // Unbind
  7135. for (var i in this._vertexAttribArrays) {
  7136. //making sure this is a string
  7137. var iAsNumber = +i;
  7138. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  7139. continue;
  7140. }
  7141. this._gl.disableVertexAttribArray(iAsNumber);
  7142. }
  7143. this._gl = null;
  7144. // Events
  7145. window.removeEventListener("blur", this._onBlur);
  7146. window.removeEventListener("focus", this._onFocus);
  7147. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  7148. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  7149. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  7150. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  7151. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  7152. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  7153. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  7154. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  7155. };
  7156. // Loading screen
  7157. Engine.prototype.displayLoadingUI = function () {
  7158. this._loadingScreen.displayLoadingUI();
  7159. };
  7160. Engine.prototype.hideLoadingUI = function () {
  7161. this._loadingScreen.hideLoadingUI();
  7162. };
  7163. Object.defineProperty(Engine.prototype, "loadingScreen", {
  7164. get: function () {
  7165. return this._loadingScreen;
  7166. },
  7167. set: function (loadingScreen) {
  7168. this._loadingScreen = loadingScreen;
  7169. },
  7170. enumerable: true,
  7171. configurable: true
  7172. });
  7173. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7174. set: function (text) {
  7175. this._loadingScreen.loadingUIText = text;
  7176. },
  7177. enumerable: true,
  7178. configurable: true
  7179. });
  7180. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7181. set: function (color) {
  7182. this._loadingScreen.loadingUIBackgroundColor = color;
  7183. },
  7184. enumerable: true,
  7185. configurable: true
  7186. });
  7187. // FPS
  7188. Engine.prototype.getFps = function () {
  7189. return this.fps;
  7190. };
  7191. Engine.prototype.getDeltaTime = function () {
  7192. return this.deltaTime;
  7193. };
  7194. Engine.prototype._measureFps = function () {
  7195. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7196. var length = this.previousFramesDuration.length;
  7197. if (length >= 2) {
  7198. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7199. }
  7200. if (length >= this.fpsRange) {
  7201. if (length > this.fpsRange) {
  7202. this.previousFramesDuration.splice(0, 1);
  7203. length = this.previousFramesDuration.length;
  7204. }
  7205. var sum = 0;
  7206. for (var id = 0; id < length - 1; id++) {
  7207. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7208. }
  7209. this.fps = 1000.0 / (sum / (length - 1));
  7210. }
  7211. };
  7212. // Statics
  7213. Engine.isSupported = function () {
  7214. try {
  7215. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7216. if (navigator.isCocoonJS) {
  7217. return true;
  7218. }
  7219. var tempcanvas = document.createElement("canvas");
  7220. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7221. return gl != null && !!window.WebGLRenderingContext;
  7222. }
  7223. catch (e) {
  7224. return false;
  7225. }
  7226. };
  7227. // Const statics
  7228. Engine._ALPHA_DISABLE = 0;
  7229. Engine._ALPHA_ADD = 1;
  7230. Engine._ALPHA_COMBINE = 2;
  7231. Engine._ALPHA_SUBTRACT = 3;
  7232. Engine._ALPHA_MULTIPLY = 4;
  7233. Engine._ALPHA_MAXIMIZED = 5;
  7234. Engine._ALPHA_ONEONE = 6;
  7235. Engine._DELAYLOADSTATE_NONE = 0;
  7236. Engine._DELAYLOADSTATE_LOADED = 1;
  7237. Engine._DELAYLOADSTATE_LOADING = 2;
  7238. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7239. Engine._TEXTUREFORMAT_ALPHA = 0;
  7240. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7241. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7242. Engine._TEXTUREFORMAT_RGB = 4;
  7243. Engine._TEXTUREFORMAT_RGBA = 5;
  7244. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7245. Engine._TEXTURETYPE_FLOAT = 1;
  7246. // Updatable statics so stick with vars here
  7247. Engine.CollisionsEpsilon = 0.001;
  7248. Engine.CodeRepository = "src/";
  7249. Engine.ShadersRepository = "src/Shaders/";
  7250. return Engine;
  7251. })();
  7252. BABYLON.Engine = Engine;
  7253. })(BABYLON || (BABYLON = {}));
  7254. var BABYLON;
  7255. (function (BABYLON) {
  7256. /**
  7257. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7258. */
  7259. var Node = (function () {
  7260. /**
  7261. * @constructor
  7262. * @param {string} name - the name and id to be given to this node
  7263. * @param {BABYLON.Scene} the scene this node will be added to
  7264. */
  7265. function Node(name, scene) {
  7266. this.state = "";
  7267. this.animations = new Array();
  7268. this._ranges = {};
  7269. this._childrenFlag = -1;
  7270. this._isEnabled = true;
  7271. this._isReady = true;
  7272. this._currentRenderId = -1;
  7273. this._parentRenderId = -1;
  7274. this.name = name;
  7275. this.id = name;
  7276. this._scene = scene;
  7277. this._initCache();
  7278. }
  7279. Object.defineProperty(Node.prototype, "parent", {
  7280. get: function () {
  7281. return this._parentNode;
  7282. },
  7283. set: function (parent) {
  7284. if (this._parentNode === parent) {
  7285. return;
  7286. }
  7287. if (this._parentNode) {
  7288. var index = this._parentNode._children.indexOf(this);
  7289. if (index !== -1) {
  7290. this._parentNode._children.splice(index, 1);
  7291. }
  7292. }
  7293. this._parentNode = parent;
  7294. if (this._parentNode) {
  7295. if (!this._parentNode._children) {
  7296. this._parentNode._children = new Array();
  7297. }
  7298. this._parentNode._children.push(this);
  7299. }
  7300. },
  7301. enumerable: true,
  7302. configurable: true
  7303. });
  7304. Node.prototype.getScene = function () {
  7305. return this._scene;
  7306. };
  7307. Node.prototype.getEngine = function () {
  7308. return this._scene.getEngine();
  7309. };
  7310. // override it in derived class
  7311. Node.prototype.getWorldMatrix = function () {
  7312. return BABYLON.Matrix.Identity();
  7313. };
  7314. // override it in derived class if you add new variables to the cache
  7315. // and call the parent class method
  7316. Node.prototype._initCache = function () {
  7317. this._cache = {};
  7318. this._cache.parent = undefined;
  7319. };
  7320. Node.prototype.updateCache = function (force) {
  7321. if (!force && this.isSynchronized())
  7322. return;
  7323. this._cache.parent = this.parent;
  7324. this._updateCache();
  7325. };
  7326. // override it in derived class if you add new variables to the cache
  7327. // and call the parent class method if !ignoreParentClass
  7328. Node.prototype._updateCache = function (ignoreParentClass) {
  7329. };
  7330. // override it in derived class if you add new variables to the cache
  7331. Node.prototype._isSynchronized = function () {
  7332. return true;
  7333. };
  7334. Node.prototype._markSyncedWithParent = function () {
  7335. this._parentRenderId = this.parent._currentRenderId;
  7336. };
  7337. Node.prototype.isSynchronizedWithParent = function () {
  7338. if (!this.parent) {
  7339. return true;
  7340. }
  7341. if (this._parentRenderId !== this.parent._currentRenderId) {
  7342. return false;
  7343. }
  7344. return this.parent.isSynchronized();
  7345. };
  7346. Node.prototype.isSynchronized = function (updateCache) {
  7347. var check = this.hasNewParent();
  7348. check = check || !this.isSynchronizedWithParent();
  7349. check = check || !this._isSynchronized();
  7350. if (updateCache)
  7351. this.updateCache(true);
  7352. return !check;
  7353. };
  7354. Node.prototype.hasNewParent = function (update) {
  7355. if (this._cache.parent === this.parent)
  7356. return false;
  7357. if (update)
  7358. this._cache.parent = this.parent;
  7359. return true;
  7360. };
  7361. /**
  7362. * Is this node ready to be used/rendered
  7363. * @return {boolean} is it ready
  7364. */
  7365. Node.prototype.isReady = function () {
  7366. return this._isReady;
  7367. };
  7368. /**
  7369. * Is this node enabled.
  7370. * If the node has a parent and is enabled, the parent will be inspected as well.
  7371. * @return {boolean} whether this node (and its parent) is enabled.
  7372. * @see setEnabled
  7373. */
  7374. Node.prototype.isEnabled = function () {
  7375. if (!this._isEnabled) {
  7376. return false;
  7377. }
  7378. if (this.parent) {
  7379. return this.parent.isEnabled();
  7380. }
  7381. return true;
  7382. };
  7383. /**
  7384. * Set the enabled state of this node.
  7385. * @param {boolean} value - the new enabled state
  7386. * @see isEnabled
  7387. */
  7388. Node.prototype.setEnabled = function (value) {
  7389. this._isEnabled = value;
  7390. };
  7391. /**
  7392. * Is this node a descendant of the given node.
  7393. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7394. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7395. * @see parent
  7396. */
  7397. Node.prototype.isDescendantOf = function (ancestor) {
  7398. if (this.parent) {
  7399. if (this.parent === ancestor) {
  7400. return true;
  7401. }
  7402. return this.parent.isDescendantOf(ancestor);
  7403. }
  7404. return false;
  7405. };
  7406. /**
  7407. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  7408. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  7409. * @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.
  7410. * @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.
  7411. */
  7412. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  7413. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  7414. if (!this._children) {
  7415. return;
  7416. }
  7417. for (var index = 0; index < this._children.length; index++) {
  7418. var item = this._children[index];
  7419. if (!predicate || predicate(item)) {
  7420. results.push(item);
  7421. }
  7422. if (!directDescendantsOnly) {
  7423. item._getDescendants(results, false, predicate);
  7424. }
  7425. }
  7426. };
  7427. /**
  7428. * Will return all nodes that have this node as ascendant.
  7429. * @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.
  7430. * @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.
  7431. * @return {BABYLON.Node[]} all children nodes of all types.
  7432. */
  7433. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  7434. var results = [];
  7435. this._getDescendants(results, directDescendantsOnly, predicate);
  7436. return results;
  7437. };
  7438. /**
  7439. * @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.
  7440. * @Deprecated, legacy support.
  7441. * use getDecendants instead.
  7442. */
  7443. Node.prototype.getChildren = function (predicate) {
  7444. return this.getDescendants(true, predicate);
  7445. };
  7446. /**
  7447. * Get all child-meshes of this node.
  7448. */
  7449. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  7450. var results = [];
  7451. this._getDescendants(results, directDecendantsOnly, function (node) {
  7452. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  7453. });
  7454. return results;
  7455. };
  7456. Node.prototype._setReady = function (state) {
  7457. if (state === this._isReady) {
  7458. return;
  7459. }
  7460. if (!state) {
  7461. this._isReady = false;
  7462. return;
  7463. }
  7464. this._isReady = true;
  7465. if (this.onReady) {
  7466. this.onReady(this);
  7467. }
  7468. };
  7469. Node.prototype.getAnimationByName = function (name) {
  7470. for (var i = 0; i < this.animations.length; i++) {
  7471. var animation = this.animations[i];
  7472. if (animation.name === name) {
  7473. return animation;
  7474. }
  7475. }
  7476. return null;
  7477. };
  7478. Node.prototype.createAnimationRange = function (name, from, to) {
  7479. // check name not already in use
  7480. if (!this._ranges[name]) {
  7481. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7482. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7483. if (this.animations[i]) {
  7484. this.animations[i].createRange(name, from, to);
  7485. }
  7486. }
  7487. }
  7488. };
  7489. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7490. if (deleteFrames === void 0) { deleteFrames = true; }
  7491. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7492. if (this.animations[i]) {
  7493. this.animations[i].deleteRange(name, deleteFrames);
  7494. }
  7495. }
  7496. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7497. };
  7498. Node.prototype.getAnimationRange = function (name) {
  7499. return this._ranges[name];
  7500. };
  7501. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7502. var range = this.getAnimationRange(name);
  7503. if (!range) {
  7504. return null;
  7505. }
  7506. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7507. };
  7508. Node.prototype.serializeAnimationRanges = function () {
  7509. var serializationRanges = [];
  7510. for (var name in this._ranges) {
  7511. var range = {};
  7512. range.name = name;
  7513. range.from = this._ranges[name].from;
  7514. range.to = this._ranges[name].to;
  7515. serializationRanges.push(range);
  7516. }
  7517. return serializationRanges;
  7518. };
  7519. Node.prototype.dispose = function () {
  7520. this.parent = null;
  7521. };
  7522. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7523. if (parsedNode.ranges) {
  7524. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7525. var data = parsedNode.ranges[index];
  7526. node.createAnimationRange(data.name, data.from, data.to);
  7527. }
  7528. }
  7529. };
  7530. __decorate([
  7531. BABYLON.serialize()
  7532. ], Node.prototype, "name", void 0);
  7533. __decorate([
  7534. BABYLON.serialize()
  7535. ], Node.prototype, "id", void 0);
  7536. __decorate([
  7537. BABYLON.serialize()
  7538. ], Node.prototype, "uniqueId", void 0);
  7539. __decorate([
  7540. BABYLON.serialize()
  7541. ], Node.prototype, "state", void 0);
  7542. return Node;
  7543. })();
  7544. BABYLON.Node = Node;
  7545. })(BABYLON || (BABYLON = {}));
  7546. var BABYLON;
  7547. (function (BABYLON) {
  7548. var FilesInput = (function () {
  7549. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7550. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7551. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7552. this._engine = p_engine;
  7553. this._canvas = p_canvas;
  7554. this._currentScene = p_scene;
  7555. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7556. this._progressCallback = p_progressCallback;
  7557. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7558. this._textureLoadingCallback = p_textureLoadingCallback;
  7559. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7560. }
  7561. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7562. var _this = this;
  7563. if (p_elementToMonitor) {
  7564. this._elementToMonitor = p_elementToMonitor;
  7565. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7566. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7567. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7568. }
  7569. };
  7570. FilesInput.prototype.renderFunction = function () {
  7571. if (this._additionnalRenderLoopLogicCallback) {
  7572. this._additionnalRenderLoopLogicCallback();
  7573. }
  7574. if (this._currentScene) {
  7575. if (this._textureLoadingCallback) {
  7576. var remaining = this._currentScene.getWaitingItemsCount();
  7577. if (remaining > 0) {
  7578. this._textureLoadingCallback(remaining);
  7579. }
  7580. }
  7581. this._currentScene.render();
  7582. }
  7583. };
  7584. FilesInput.prototype.drag = function (e) {
  7585. e.stopPropagation();
  7586. e.preventDefault();
  7587. };
  7588. FilesInput.prototype.drop = function (eventDrop) {
  7589. eventDrop.stopPropagation();
  7590. eventDrop.preventDefault();
  7591. this.loadFiles(eventDrop);
  7592. };
  7593. FilesInput.prototype.loadFiles = function (event) {
  7594. if (this._startingProcessingFilesCallback)
  7595. this._startingProcessingFilesCallback();
  7596. // Handling data transfer via drag'n'drop
  7597. if (event && event.dataTransfer && event.dataTransfer.files) {
  7598. this._filesToLoad = event.dataTransfer.files;
  7599. }
  7600. // Handling files from input files
  7601. if (event && event.target && event.target.files) {
  7602. this._filesToLoad = event.target.files;
  7603. }
  7604. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7605. for (var i = 0; i < this._filesToLoad.length; i++) {
  7606. switch (this._filesToLoad[i].type) {
  7607. case "image/jpeg":
  7608. case "image/png":
  7609. case "image/bmp":
  7610. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7611. break;
  7612. case "image/targa":
  7613. case "image/vnd.ms-dds":
  7614. case "audio/wav":
  7615. case "audio/x-wav":
  7616. case "audio/mp3":
  7617. case "audio/mpeg":
  7618. case "audio/mpeg3":
  7619. case "audio/x-mpeg-3":
  7620. case "audio/ogg":
  7621. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7622. break;
  7623. default:
  7624. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  7625. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7626. }
  7627. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  7628. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7629. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  7630. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7631. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7632. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7633. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7634. this._sceneFileToLoad = this._filesToLoad[i];
  7635. }
  7636. break;
  7637. }
  7638. }
  7639. this.reload();
  7640. }
  7641. };
  7642. FilesInput.prototype.reload = function () {
  7643. var _this = this;
  7644. var that = this;
  7645. // If a ".babylon" file has been provided
  7646. if (this._sceneFileToLoad) {
  7647. if (this._currentScene) {
  7648. if (BABYLON.Tools.errorsCount > 0) {
  7649. BABYLON.Tools.ClearLogCache();
  7650. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7651. }
  7652. this._engine.stopRenderLoop();
  7653. this._currentScene.dispose();
  7654. }
  7655. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7656. that._currentScene = newScene;
  7657. // Wait for textures and shaders to be ready
  7658. that._currentScene.executeWhenReady(function () {
  7659. // Attach camera to canvas inputs
  7660. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7661. that._currentScene.createDefaultCameraOrLight();
  7662. }
  7663. that._currentScene.activeCamera.attachControl(that._canvas);
  7664. if (that._sceneLoadedCallback) {
  7665. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7666. }
  7667. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7668. });
  7669. }, function (progress) {
  7670. if (_this._progressCallback) {
  7671. _this._progressCallback(progress);
  7672. }
  7673. });
  7674. }
  7675. else {
  7676. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7677. }
  7678. };
  7679. FilesInput.FilesTextures = new Array();
  7680. FilesInput.FilesToLoad = new Array();
  7681. return FilesInput;
  7682. })();
  7683. BABYLON.FilesInput = FilesInput;
  7684. })(BABYLON || (BABYLON = {}));
  7685. var BABYLON;
  7686. (function (BABYLON) {
  7687. var IntersectionInfo = (function () {
  7688. function IntersectionInfo(bu, bv, distance) {
  7689. this.bu = bu;
  7690. this.bv = bv;
  7691. this.distance = distance;
  7692. this.faceId = 0;
  7693. this.subMeshId = 0;
  7694. }
  7695. return IntersectionInfo;
  7696. })();
  7697. BABYLON.IntersectionInfo = IntersectionInfo;
  7698. var PickingInfo = (function () {
  7699. function PickingInfo() {
  7700. this.hit = false;
  7701. this.distance = 0;
  7702. this.pickedPoint = null;
  7703. this.pickedMesh = null;
  7704. this.bu = 0;
  7705. this.bv = 0;
  7706. this.faceId = -1;
  7707. this.subMeshId = 0;
  7708. this.pickedSprite = null;
  7709. }
  7710. // Methods
  7711. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7712. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7713. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7714. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7715. return null;
  7716. }
  7717. var indices = this.pickedMesh.getIndices();
  7718. var result;
  7719. if (useVerticesNormals) {
  7720. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7721. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7722. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7723. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7724. normal0 = normal0.scale(this.bu);
  7725. normal1 = normal1.scale(this.bv);
  7726. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7727. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7728. }
  7729. else {
  7730. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7731. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7732. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7733. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7734. var p1p2 = vertex1.subtract(vertex2);
  7735. var p3p2 = vertex3.subtract(vertex2);
  7736. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7737. }
  7738. if (useWorldCoordinates) {
  7739. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7740. }
  7741. return BABYLON.Vector3.Normalize(result);
  7742. };
  7743. PickingInfo.prototype.getTextureCoordinates = function () {
  7744. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7745. return null;
  7746. }
  7747. var indices = this.pickedMesh.getIndices();
  7748. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7749. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7750. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7751. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7752. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7753. uv1 = uv1.scale(this.bu);
  7754. uv2 = uv2.scale(this.bv);
  7755. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7756. };
  7757. return PickingInfo;
  7758. })();
  7759. BABYLON.PickingInfo = PickingInfo;
  7760. })(BABYLON || (BABYLON = {}));
  7761. var BABYLON;
  7762. (function (BABYLON) {
  7763. var BoundingSphere = (function () {
  7764. function BoundingSphere(minimum, maximum) {
  7765. this.minimum = minimum;
  7766. this.maximum = maximum;
  7767. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7768. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7769. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7770. this.radius = distance * 0.5;
  7771. this.centerWorld = BABYLON.Vector3.Zero();
  7772. this._update(BABYLON.Matrix.Identity());
  7773. }
  7774. // Methods
  7775. BoundingSphere.prototype._update = function (world) {
  7776. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7777. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7778. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7779. };
  7780. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7781. for (var i = 0; i < 6; i++) {
  7782. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7783. return false;
  7784. }
  7785. return true;
  7786. };
  7787. BoundingSphere.prototype.intersectsPoint = function (point) {
  7788. var x = this.centerWorld.x - point.x;
  7789. var y = this.centerWorld.y - point.y;
  7790. var z = this.centerWorld.z - point.z;
  7791. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7792. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  7793. return false;
  7794. return true;
  7795. };
  7796. // Statics
  7797. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7798. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7799. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7800. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7801. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7802. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7803. return false;
  7804. return true;
  7805. };
  7806. return BoundingSphere;
  7807. })();
  7808. BABYLON.BoundingSphere = BoundingSphere;
  7809. })(BABYLON || (BABYLON = {}));
  7810. var BABYLON;
  7811. (function (BABYLON) {
  7812. var BoundingBox = (function () {
  7813. function BoundingBox(minimum, maximum) {
  7814. this.minimum = minimum;
  7815. this.maximum = maximum;
  7816. this.vectors = new Array();
  7817. this.vectorsWorld = new Array();
  7818. // Bounding vectors
  7819. this.vectors.push(this.minimum.clone());
  7820. this.vectors.push(this.maximum.clone());
  7821. this.vectors.push(this.minimum.clone());
  7822. this.vectors[2].x = this.maximum.x;
  7823. this.vectors.push(this.minimum.clone());
  7824. this.vectors[3].y = this.maximum.y;
  7825. this.vectors.push(this.minimum.clone());
  7826. this.vectors[4].z = this.maximum.z;
  7827. this.vectors.push(this.maximum.clone());
  7828. this.vectors[5].z = this.minimum.z;
  7829. this.vectors.push(this.maximum.clone());
  7830. this.vectors[6].x = this.minimum.x;
  7831. this.vectors.push(this.maximum.clone());
  7832. this.vectors[7].y = this.minimum.y;
  7833. // OBB
  7834. this.center = this.maximum.add(this.minimum).scale(0.5);
  7835. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7836. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7837. // World
  7838. for (var index = 0; index < this.vectors.length; index++) {
  7839. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7840. }
  7841. this.minimumWorld = BABYLON.Vector3.Zero();
  7842. this.maximumWorld = BABYLON.Vector3.Zero();
  7843. this._update(BABYLON.Matrix.Identity());
  7844. }
  7845. // Methods
  7846. BoundingBox.prototype.getWorldMatrix = function () {
  7847. return this._worldMatrix;
  7848. };
  7849. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  7850. this._worldMatrix.copyFrom(matrix);
  7851. return this;
  7852. };
  7853. BoundingBox.prototype._update = function (world) {
  7854. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7855. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7856. for (var index = 0; index < this.vectors.length; index++) {
  7857. var v = this.vectorsWorld[index];
  7858. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7859. if (v.x < this.minimumWorld.x)
  7860. this.minimumWorld.x = v.x;
  7861. if (v.y < this.minimumWorld.y)
  7862. this.minimumWorld.y = v.y;
  7863. if (v.z < this.minimumWorld.z)
  7864. this.minimumWorld.z = v.z;
  7865. if (v.x > this.maximumWorld.x)
  7866. this.maximumWorld.x = v.x;
  7867. if (v.y > this.maximumWorld.y)
  7868. this.maximumWorld.y = v.y;
  7869. if (v.z > this.maximumWorld.z)
  7870. this.maximumWorld.z = v.z;
  7871. }
  7872. // OBB
  7873. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7874. this.center.scaleInPlace(0.5);
  7875. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7876. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7877. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7878. this._worldMatrix = world;
  7879. };
  7880. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7881. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7882. };
  7883. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7884. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7885. };
  7886. BoundingBox.prototype.intersectsPoint = function (point) {
  7887. var delta = -BABYLON.Epsilon;
  7888. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7889. return false;
  7890. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7891. return false;
  7892. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7893. return false;
  7894. return true;
  7895. };
  7896. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7897. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7898. };
  7899. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7900. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7901. return false;
  7902. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7903. return false;
  7904. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7905. return false;
  7906. return true;
  7907. };
  7908. // Statics
  7909. BoundingBox.Intersects = function (box0, box1) {
  7910. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7911. return false;
  7912. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7913. return false;
  7914. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7915. return false;
  7916. return true;
  7917. };
  7918. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7919. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7920. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7921. return (num <= (sphereRadius * sphereRadius));
  7922. };
  7923. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7924. for (var p = 0; p < 6; p++) {
  7925. for (var i = 0; i < 8; i++) {
  7926. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7927. return false;
  7928. }
  7929. }
  7930. }
  7931. return true;
  7932. };
  7933. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7934. for (var p = 0; p < 6; p++) {
  7935. var inCount = 8;
  7936. for (var i = 0; i < 8; i++) {
  7937. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7938. --inCount;
  7939. }
  7940. else {
  7941. break;
  7942. }
  7943. }
  7944. if (inCount === 0)
  7945. return false;
  7946. }
  7947. return true;
  7948. };
  7949. return BoundingBox;
  7950. })();
  7951. BABYLON.BoundingBox = BoundingBox;
  7952. })(BABYLON || (BABYLON = {}));
  7953. var BABYLON;
  7954. (function (BABYLON) {
  7955. var computeBoxExtents = function (axis, box) {
  7956. var p = BABYLON.Vector3.Dot(box.center, axis);
  7957. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7958. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7959. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7960. var r = r0 + r1 + r2;
  7961. return {
  7962. min: p - r,
  7963. max: p + r
  7964. };
  7965. };
  7966. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7967. var axisOverlap = function (axis, box0, box1) {
  7968. var result0 = computeBoxExtents(axis, box0);
  7969. var result1 = computeBoxExtents(axis, box1);
  7970. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7971. };
  7972. var BoundingInfo = (function () {
  7973. function BoundingInfo(minimum, maximum) {
  7974. this.minimum = minimum;
  7975. this.maximum = maximum;
  7976. this._isLocked = false;
  7977. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7978. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7979. }
  7980. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  7981. get: function () {
  7982. return this._isLocked;
  7983. },
  7984. set: function (value) {
  7985. this._isLocked = value;
  7986. },
  7987. enumerable: true,
  7988. configurable: true
  7989. });
  7990. // Methods
  7991. BoundingInfo.prototype.update = function (world) {
  7992. if (this._isLocked) {
  7993. return;
  7994. }
  7995. this.boundingBox._update(world);
  7996. this.boundingSphere._update(world);
  7997. };
  7998. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7999. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  8000. return false;
  8001. return this.boundingBox.isInFrustum(frustumPlanes);
  8002. };
  8003. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  8004. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  8005. };
  8006. BoundingInfo.prototype._checkCollision = function (collider) {
  8007. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  8008. };
  8009. BoundingInfo.prototype.intersectsPoint = function (point) {
  8010. if (!this.boundingSphere.centerWorld) {
  8011. return false;
  8012. }
  8013. if (!this.boundingSphere.intersectsPoint(point)) {
  8014. return false;
  8015. }
  8016. if (!this.boundingBox.intersectsPoint(point)) {
  8017. return false;
  8018. }
  8019. return true;
  8020. };
  8021. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  8022. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  8023. return false;
  8024. }
  8025. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  8026. return false;
  8027. }
  8028. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  8029. return false;
  8030. }
  8031. if (!precise) {
  8032. return true;
  8033. }
  8034. var box0 = this.boundingBox;
  8035. var box1 = boundingInfo.boundingBox;
  8036. if (!axisOverlap(box0.directions[0], box0, box1))
  8037. return false;
  8038. if (!axisOverlap(box0.directions[1], box0, box1))
  8039. return false;
  8040. if (!axisOverlap(box0.directions[2], box0, box1))
  8041. return false;
  8042. if (!axisOverlap(box1.directions[0], box0, box1))
  8043. return false;
  8044. if (!axisOverlap(box1.directions[1], box0, box1))
  8045. return false;
  8046. if (!axisOverlap(box1.directions[2], box0, box1))
  8047. return false;
  8048. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  8049. return false;
  8050. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  8051. return false;
  8052. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  8053. return false;
  8054. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  8055. return false;
  8056. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  8057. return false;
  8058. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  8059. return false;
  8060. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  8061. return false;
  8062. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  8063. return false;
  8064. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  8065. return false;
  8066. return true;
  8067. };
  8068. return BoundingInfo;
  8069. })();
  8070. BABYLON.BoundingInfo = BoundingInfo;
  8071. })(BABYLON || (BABYLON = {}));
  8072. var BABYLON;
  8073. (function (BABYLON) {
  8074. var Ray = (function () {
  8075. function Ray(origin, direction, length) {
  8076. if (length === void 0) { length = Number.MAX_VALUE; }
  8077. this.origin = origin;
  8078. this.direction = direction;
  8079. this.length = length;
  8080. }
  8081. // Methods
  8082. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  8083. var d = 0.0;
  8084. var maxValue = Number.MAX_VALUE;
  8085. var inv;
  8086. var min;
  8087. var max;
  8088. var temp;
  8089. if (Math.abs(this.direction.x) < 0.0000001) {
  8090. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  8091. return false;
  8092. }
  8093. }
  8094. else {
  8095. inv = 1.0 / this.direction.x;
  8096. min = (minimum.x - this.origin.x) * inv;
  8097. max = (maximum.x - this.origin.x) * inv;
  8098. if (max === -Infinity) {
  8099. max = Infinity;
  8100. }
  8101. if (min > max) {
  8102. temp = min;
  8103. min = max;
  8104. max = temp;
  8105. }
  8106. d = Math.max(min, d);
  8107. maxValue = Math.min(max, maxValue);
  8108. if (d > maxValue) {
  8109. return false;
  8110. }
  8111. }
  8112. if (Math.abs(this.direction.y) < 0.0000001) {
  8113. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  8114. return false;
  8115. }
  8116. }
  8117. else {
  8118. inv = 1.0 / this.direction.y;
  8119. min = (minimum.y - this.origin.y) * inv;
  8120. max = (maximum.y - this.origin.y) * inv;
  8121. if (max === -Infinity) {
  8122. max = Infinity;
  8123. }
  8124. if (min > max) {
  8125. temp = min;
  8126. min = max;
  8127. max = temp;
  8128. }
  8129. d = Math.max(min, d);
  8130. maxValue = Math.min(max, maxValue);
  8131. if (d > maxValue) {
  8132. return false;
  8133. }
  8134. }
  8135. if (Math.abs(this.direction.z) < 0.0000001) {
  8136. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  8137. return false;
  8138. }
  8139. }
  8140. else {
  8141. inv = 1.0 / this.direction.z;
  8142. min = (minimum.z - this.origin.z) * inv;
  8143. max = (maximum.z - this.origin.z) * inv;
  8144. if (max === -Infinity) {
  8145. max = Infinity;
  8146. }
  8147. if (min > max) {
  8148. temp = min;
  8149. min = max;
  8150. max = temp;
  8151. }
  8152. d = Math.max(min, d);
  8153. maxValue = Math.min(max, maxValue);
  8154. if (d > maxValue) {
  8155. return false;
  8156. }
  8157. }
  8158. return true;
  8159. };
  8160. Ray.prototype.intersectsBox = function (box) {
  8161. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  8162. };
  8163. Ray.prototype.intersectsSphere = function (sphere) {
  8164. var x = sphere.center.x - this.origin.x;
  8165. var y = sphere.center.y - this.origin.y;
  8166. var z = sphere.center.z - this.origin.z;
  8167. var pyth = (x * x) + (y * y) + (z * z);
  8168. var rr = sphere.radius * sphere.radius;
  8169. if (pyth <= rr) {
  8170. return true;
  8171. }
  8172. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  8173. if (dot < 0.0) {
  8174. return false;
  8175. }
  8176. var temp = pyth - (dot * dot);
  8177. return temp <= rr;
  8178. };
  8179. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  8180. if (!this._edge1) {
  8181. this._edge1 = BABYLON.Vector3.Zero();
  8182. this._edge2 = BABYLON.Vector3.Zero();
  8183. this._pvec = BABYLON.Vector3.Zero();
  8184. this._tvec = BABYLON.Vector3.Zero();
  8185. this._qvec = BABYLON.Vector3.Zero();
  8186. }
  8187. vertex1.subtractToRef(vertex0, this._edge1);
  8188. vertex2.subtractToRef(vertex0, this._edge2);
  8189. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  8190. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  8191. if (det === 0) {
  8192. return null;
  8193. }
  8194. var invdet = 1 / det;
  8195. this.origin.subtractToRef(vertex0, this._tvec);
  8196. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  8197. if (bu < 0 || bu > 1.0) {
  8198. return null;
  8199. }
  8200. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  8201. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  8202. if (bv < 0 || bu + bv > 1.0) {
  8203. return null;
  8204. }
  8205. //check if the distance is longer than the predefined length.
  8206. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  8207. if (distance > this.length) {
  8208. return null;
  8209. }
  8210. return new BABYLON.IntersectionInfo(bu, bv, distance);
  8211. };
  8212. Ray.prototype.intersectsPlane = function (plane) {
  8213. var distance;
  8214. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  8215. if (Math.abs(result1) < 9.99999997475243E-07) {
  8216. return null;
  8217. }
  8218. else {
  8219. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  8220. distance = (-plane.d - result2) / result1;
  8221. if (distance < 0.0) {
  8222. if (distance < -9.99999997475243E-07) {
  8223. return null;
  8224. }
  8225. else {
  8226. return 0;
  8227. }
  8228. }
  8229. return distance;
  8230. }
  8231. };
  8232. /**
  8233. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  8234. * @param sega the first point of the segment to test the intersection against
  8235. * @param segb the second point of the segment to test the intersection against
  8236. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  8237. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  8238. */
  8239. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  8240. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  8241. var u = segb.subtract(sega);
  8242. var v = rsegb.subtract(this.origin);
  8243. var w = sega.subtract(this.origin);
  8244. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  8245. var b = BABYLON.Vector3.Dot(u, v);
  8246. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  8247. var d = BABYLON.Vector3.Dot(u, w);
  8248. var e = BABYLON.Vector3.Dot(v, w);
  8249. var D = a * c - b * b; // always >= 0
  8250. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  8251. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  8252. // compute the line parameters of the two closest points
  8253. if (D < Ray.smallnum) {
  8254. sN = 0.0; // force using point P0 on segment S1
  8255. sD = 1.0; // to prevent possible division by 0.0 later
  8256. tN = e;
  8257. tD = c;
  8258. }
  8259. else {
  8260. sN = (b * e - c * d);
  8261. tN = (a * e - b * d);
  8262. if (sN < 0.0) {
  8263. sN = 0.0;
  8264. tN = e;
  8265. tD = c;
  8266. }
  8267. else if (sN > sD) {
  8268. sN = sD;
  8269. tN = e + b;
  8270. tD = c;
  8271. }
  8272. }
  8273. if (tN < 0.0) {
  8274. tN = 0.0;
  8275. // recompute sc for this edge
  8276. if (-d < 0.0) {
  8277. sN = 0.0;
  8278. }
  8279. else if (-d > a)
  8280. sN = sD;
  8281. else {
  8282. sN = -d;
  8283. sD = a;
  8284. }
  8285. }
  8286. else if (tN > tD) {
  8287. tN = tD;
  8288. // recompute sc for this edge
  8289. if ((-d + b) < 0.0) {
  8290. sN = 0;
  8291. }
  8292. else if ((-d + b) > a) {
  8293. sN = sD;
  8294. }
  8295. else {
  8296. sN = (-d + b);
  8297. sD = a;
  8298. }
  8299. }
  8300. // finally do the division to get sc and tc
  8301. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  8302. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  8303. // get the difference of the two closest points
  8304. var qtc = v.multiplyByFloats(tc, tc, tc);
  8305. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  8306. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  8307. if (isIntersected) {
  8308. return qtc.length();
  8309. }
  8310. return -1;
  8311. };
  8312. // Statics
  8313. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  8314. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  8315. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  8316. var direction = end.subtract(start);
  8317. direction.normalize();
  8318. return new Ray(start, direction);
  8319. };
  8320. /**
  8321. * 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
  8322. * transformed to the given world matrix.
  8323. * @param origin The origin point
  8324. * @param end The end point
  8325. * @param world a matrix to transform the ray to. Default is the identity matrix.
  8326. */
  8327. Ray.CreateNewFromTo = function (origin, end, world) {
  8328. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  8329. var direction = end.subtract(origin);
  8330. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  8331. direction.normalize();
  8332. return Ray.Transform(new Ray(origin, direction, length), world);
  8333. };
  8334. Ray.Transform = function (ray, matrix) {
  8335. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  8336. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  8337. newDirection.normalize();
  8338. return new Ray(newOrigin, newDirection, ray.length);
  8339. };
  8340. Ray.smallnum = 0.00000001;
  8341. Ray.rayl = 10e8;
  8342. return Ray;
  8343. })();
  8344. BABYLON.Ray = Ray;
  8345. })(BABYLON || (BABYLON = {}));
  8346. var BABYLON;
  8347. (function (BABYLON) {
  8348. var AbstractMesh = (function (_super) {
  8349. __extends(AbstractMesh, _super);
  8350. // Constructor
  8351. function AbstractMesh(name, scene) {
  8352. var _this = this;
  8353. _super.call(this, name, scene);
  8354. // Events
  8355. /**
  8356. * An event triggered when this mesh collides with another one
  8357. * @type {BABYLON.Observable}
  8358. */
  8359. this.onCollideObservable = new BABYLON.Observable();
  8360. /**
  8361. * An event triggered when the collision's position changes
  8362. * @type {BABYLON.Observable}
  8363. */
  8364. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  8365. /**
  8366. * An event triggered after the world matrix is updated
  8367. * @type {BABYLON.Observable}
  8368. */
  8369. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  8370. // Properties
  8371. this.definedFacingForward = true; // orientation for POV movement & rotation
  8372. this.position = new BABYLON.Vector3(0, 0, 0);
  8373. this._rotation = new BABYLON.Vector3(0, 0, 0);
  8374. this._scaling = new BABYLON.Vector3(1, 1, 1);
  8375. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8376. this.visibility = 1.0;
  8377. this.alphaIndex = Number.MAX_VALUE;
  8378. this.infiniteDistance = false;
  8379. this.isVisible = true;
  8380. this.isPickable = true;
  8381. this.showBoundingBox = false;
  8382. this.showSubMeshesBoundingBox = false;
  8383. this.onDispose = null;
  8384. this.isBlocker = false;
  8385. this.renderingGroupId = 0;
  8386. this.receiveShadows = false;
  8387. this.renderOutline = false;
  8388. this.outlineColor = BABYLON.Color3.Red();
  8389. this.outlineWidth = 0.02;
  8390. this.renderOverlay = false;
  8391. this.overlayColor = BABYLON.Color3.Red();
  8392. this.overlayAlpha = 0.5;
  8393. this.hasVertexAlpha = false;
  8394. this.useVertexColors = true;
  8395. this.applyFog = true;
  8396. this.computeBonesUsingShaders = true;
  8397. this.scalingDeterminant = 1;
  8398. this.numBoneInfluencers = 4;
  8399. this.useOctreeForRenderingSelection = true;
  8400. this.useOctreeForPicking = true;
  8401. this.useOctreeForCollisions = true;
  8402. this.layerMask = 0x0FFFFFFF;
  8403. this.alwaysSelectAsActiveMesh = false;
  8404. // Collisions
  8405. this._checkCollisions = false;
  8406. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8407. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8408. this._collider = new BABYLON.Collider();
  8409. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8410. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8411. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8412. // Edges
  8413. this.edgesWidth = 1;
  8414. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  8415. // Cache
  8416. this._localWorld = BABYLON.Matrix.Zero();
  8417. this._worldMatrix = BABYLON.Matrix.Zero();
  8418. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8419. this._absolutePosition = BABYLON.Vector3.Zero();
  8420. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8421. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8422. this._isDirty = false;
  8423. this._pivotMatrix = BABYLON.Matrix.Identity();
  8424. this._isDisposed = false;
  8425. this._renderId = 0;
  8426. this._intersectionsInProgress = new Array();
  8427. this._isWorldMatrixFrozen = false;
  8428. this._unIndexed = false;
  8429. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  8430. if (collidedMesh === void 0) { collidedMesh = null; }
  8431. //TODO move this to the collision coordinator!
  8432. if (_this.getScene().workerCollisions)
  8433. newPosition.multiplyInPlace(_this._collider.radius);
  8434. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  8435. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8436. _this.position.addInPlace(_this._diffPositionForCollisions);
  8437. }
  8438. if (collidedMesh) {
  8439. _this.onCollideObservable.notifyObservers(collidedMesh);
  8440. }
  8441. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  8442. };
  8443. scene.addMesh(this);
  8444. }
  8445. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8446. get: function () {
  8447. return AbstractMesh._BILLBOARDMODE_NONE;
  8448. },
  8449. enumerable: true,
  8450. configurable: true
  8451. });
  8452. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8453. get: function () {
  8454. return AbstractMesh._BILLBOARDMODE_X;
  8455. },
  8456. enumerable: true,
  8457. configurable: true
  8458. });
  8459. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8460. get: function () {
  8461. return AbstractMesh._BILLBOARDMODE_Y;
  8462. },
  8463. enumerable: true,
  8464. configurable: true
  8465. });
  8466. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8467. get: function () {
  8468. return AbstractMesh._BILLBOARDMODE_Z;
  8469. },
  8470. enumerable: true,
  8471. configurable: true
  8472. });
  8473. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8474. get: function () {
  8475. return AbstractMesh._BILLBOARDMODE_ALL;
  8476. },
  8477. enumerable: true,
  8478. configurable: true
  8479. });
  8480. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  8481. set: function (callback) {
  8482. if (this._onCollideObserver) {
  8483. this.onCollideObservable.remove(this._onCollideObserver);
  8484. }
  8485. this._onCollideObserver = this.onCollideObservable.add(callback);
  8486. },
  8487. enumerable: true,
  8488. configurable: true
  8489. });
  8490. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  8491. set: function (callback) {
  8492. if (this._onCollisionPositionChangeObserver) {
  8493. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  8494. }
  8495. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  8496. },
  8497. enumerable: true,
  8498. configurable: true
  8499. });
  8500. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  8501. get: function () {
  8502. return this._skeleton;
  8503. },
  8504. set: function (value) {
  8505. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  8506. this._skeleton._unregisterMeshWithPoseMatrix(this);
  8507. }
  8508. if (value && value.needInitialSkinMatrix) {
  8509. value._registerMeshWithPoseMatrix(this);
  8510. }
  8511. this._skeleton = value;
  8512. if (!this._skeleton) {
  8513. this._bonesTransformMatrices = null;
  8514. }
  8515. },
  8516. enumerable: true,
  8517. configurable: true
  8518. });
  8519. /**
  8520. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  8521. */
  8522. AbstractMesh.prototype.toString = function (fullDetails) {
  8523. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  8524. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  8525. if (this._skeleton) {
  8526. ret += ", skeleton: " + this._skeleton.name;
  8527. }
  8528. if (fullDetails) {
  8529. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  8530. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  8531. }
  8532. return ret;
  8533. };
  8534. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  8535. /**
  8536. * Getting the rotation object.
  8537. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  8538. */
  8539. get: function () {
  8540. return this._rotation;
  8541. },
  8542. set: function (newRotation) {
  8543. this._rotation = newRotation;
  8544. },
  8545. enumerable: true,
  8546. configurable: true
  8547. });
  8548. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  8549. get: function () {
  8550. return this._scaling;
  8551. },
  8552. set: function (newScaling) {
  8553. this._scaling = newScaling;
  8554. if (this.physicsImpostor) {
  8555. this.physicsImpostor.forceUpdate();
  8556. }
  8557. },
  8558. enumerable: true,
  8559. configurable: true
  8560. });
  8561. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  8562. get: function () {
  8563. return this._rotationQuaternion;
  8564. },
  8565. set: function (quaternion) {
  8566. this._rotationQuaternion = quaternion;
  8567. //reset the rotation vector.
  8568. if (quaternion && this.rotation.length()) {
  8569. this.rotation.copyFromFloats(0, 0, 0);
  8570. }
  8571. },
  8572. enumerable: true,
  8573. configurable: true
  8574. });
  8575. // Methods
  8576. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  8577. this._poseMatrix.copyFrom(matrix);
  8578. };
  8579. AbstractMesh.prototype.getPoseMatrix = function () {
  8580. return this._poseMatrix;
  8581. };
  8582. AbstractMesh.prototype.disableEdgesRendering = function () {
  8583. if (this._edgesRenderer !== undefined) {
  8584. this._edgesRenderer.dispose();
  8585. this._edgesRenderer = undefined;
  8586. }
  8587. };
  8588. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  8589. if (epsilon === void 0) { epsilon = 0.95; }
  8590. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  8591. this.disableEdgesRendering();
  8592. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  8593. };
  8594. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8595. get: function () {
  8596. return false;
  8597. },
  8598. enumerable: true,
  8599. configurable: true
  8600. });
  8601. AbstractMesh.prototype.getLOD = function (camera) {
  8602. return this;
  8603. };
  8604. AbstractMesh.prototype.getTotalVertices = function () {
  8605. return 0;
  8606. };
  8607. AbstractMesh.prototype.getIndices = function () {
  8608. return null;
  8609. };
  8610. AbstractMesh.prototype.getVerticesData = function (kind) {
  8611. return null;
  8612. };
  8613. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8614. return false;
  8615. };
  8616. AbstractMesh.prototype.getBoundingInfo = function () {
  8617. if (this._masterMesh) {
  8618. return this._masterMesh.getBoundingInfo();
  8619. }
  8620. if (!this._boundingInfo) {
  8621. this._updateBoundingInfo();
  8622. }
  8623. return this._boundingInfo;
  8624. };
  8625. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  8626. get: function () {
  8627. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  8628. },
  8629. enumerable: true,
  8630. configurable: true
  8631. });
  8632. AbstractMesh.prototype._preActivate = function () {
  8633. };
  8634. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  8635. };
  8636. AbstractMesh.prototype._activate = function (renderId) {
  8637. this._renderId = renderId;
  8638. };
  8639. AbstractMesh.prototype.getWorldMatrix = function () {
  8640. if (this._masterMesh) {
  8641. return this._masterMesh.getWorldMatrix();
  8642. }
  8643. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8644. this.computeWorldMatrix();
  8645. }
  8646. return this._worldMatrix;
  8647. };
  8648. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8649. get: function () {
  8650. return this._worldMatrix;
  8651. },
  8652. enumerable: true,
  8653. configurable: true
  8654. });
  8655. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8656. get: function () {
  8657. return this._absolutePosition;
  8658. },
  8659. enumerable: true,
  8660. configurable: true
  8661. });
  8662. AbstractMesh.prototype.freezeWorldMatrix = function () {
  8663. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  8664. this.computeWorldMatrix(true);
  8665. this._isWorldMatrixFrozen = true;
  8666. };
  8667. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  8668. this._isWorldMatrixFrozen = false;
  8669. this.computeWorldMatrix(true);
  8670. };
  8671. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8672. get: function () {
  8673. return this._isWorldMatrixFrozen;
  8674. },
  8675. enumerable: true,
  8676. configurable: true
  8677. });
  8678. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8679. axis.normalize();
  8680. if (!this.rotationQuaternion) {
  8681. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8682. this.rotation = BABYLON.Vector3.Zero();
  8683. }
  8684. var rotationQuaternion;
  8685. if (!space || space === BABYLON.Space.LOCAL) {
  8686. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8687. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8688. }
  8689. else {
  8690. if (this.parent) {
  8691. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8692. invertParentWorldMatrix.invert();
  8693. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8694. }
  8695. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8696. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8697. }
  8698. };
  8699. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8700. var displacementVector = axis.scale(distance);
  8701. if (!space || space === BABYLON.Space.LOCAL) {
  8702. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8703. this.setPositionWithLocalVector(tempV3);
  8704. }
  8705. else {
  8706. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8707. }
  8708. };
  8709. AbstractMesh.prototype.getAbsolutePosition = function () {
  8710. this.computeWorldMatrix();
  8711. return this._absolutePosition;
  8712. };
  8713. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8714. if (!absolutePosition) {
  8715. return;
  8716. }
  8717. var absolutePositionX;
  8718. var absolutePositionY;
  8719. var absolutePositionZ;
  8720. if (absolutePosition.x === undefined) {
  8721. if (arguments.length < 3) {
  8722. return;
  8723. }
  8724. absolutePositionX = arguments[0];
  8725. absolutePositionY = arguments[1];
  8726. absolutePositionZ = arguments[2];
  8727. }
  8728. else {
  8729. absolutePositionX = absolutePosition.x;
  8730. absolutePositionY = absolutePosition.y;
  8731. absolutePositionZ = absolutePosition.z;
  8732. }
  8733. if (this.parent) {
  8734. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8735. invertParentWorldMatrix.invert();
  8736. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8737. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8738. }
  8739. else {
  8740. this.position.x = absolutePositionX;
  8741. this.position.y = absolutePositionY;
  8742. this.position.z = absolutePositionZ;
  8743. }
  8744. };
  8745. // ================================== Point of View Movement =================================
  8746. /**
  8747. * Perform relative position change from the point of view of behind the front of the mesh.
  8748. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8749. * Supports definition of mesh facing forward or backward.
  8750. * @param {number} amountRight
  8751. * @param {number} amountUp
  8752. * @param {number} amountForward
  8753. */
  8754. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8755. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8756. };
  8757. /**
  8758. * Calculate relative position change from the point of view of behind the front of the mesh.
  8759. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8760. * Supports definition of mesh facing forward or backward.
  8761. * @param {number} amountRight
  8762. * @param {number} amountUp
  8763. * @param {number} amountForward
  8764. */
  8765. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8766. var rotMatrix = new BABYLON.Matrix();
  8767. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8768. rotQuaternion.toRotationMatrix(rotMatrix);
  8769. var translationDelta = BABYLON.Vector3.Zero();
  8770. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8771. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8772. return translationDelta;
  8773. };
  8774. // ================================== Point of View Rotation =================================
  8775. /**
  8776. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8777. * Supports definition of mesh facing forward or backward.
  8778. * @param {number} flipBack
  8779. * @param {number} twirlClockwise
  8780. * @param {number} tiltRight
  8781. */
  8782. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8783. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8784. };
  8785. /**
  8786. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8787. * Supports definition of mesh facing forward or backward.
  8788. * @param {number} flipBack
  8789. * @param {number} twirlClockwise
  8790. * @param {number} tiltRight
  8791. */
  8792. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8793. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8794. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8795. };
  8796. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8797. this._pivotMatrix = matrix;
  8798. this._cache.pivotMatrixUpdated = true;
  8799. };
  8800. AbstractMesh.prototype.getPivotMatrix = function () {
  8801. return this._pivotMatrix;
  8802. };
  8803. AbstractMesh.prototype._isSynchronized = function () {
  8804. if (this._isDirty) {
  8805. return false;
  8806. }
  8807. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8808. return false;
  8809. if (this._cache.pivotMatrixUpdated) {
  8810. return false;
  8811. }
  8812. if (this.infiniteDistance) {
  8813. return false;
  8814. }
  8815. if (!this._cache.position.equals(this.position))
  8816. return false;
  8817. if (this.rotationQuaternion) {
  8818. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8819. return false;
  8820. }
  8821. else {
  8822. if (!this._cache.rotation.equals(this.rotation))
  8823. return false;
  8824. }
  8825. if (!this._cache.scaling.equals(this.scaling))
  8826. return false;
  8827. return true;
  8828. };
  8829. AbstractMesh.prototype._initCache = function () {
  8830. _super.prototype._initCache.call(this);
  8831. this._cache.localMatrixUpdated = false;
  8832. this._cache.position = BABYLON.Vector3.Zero();
  8833. this._cache.scaling = BABYLON.Vector3.Zero();
  8834. this._cache.rotation = BABYLON.Vector3.Zero();
  8835. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8836. this._cache.billboardMode = -1;
  8837. };
  8838. AbstractMesh.prototype.markAsDirty = function (property) {
  8839. if (property === "rotation") {
  8840. this.rotationQuaternion = null;
  8841. }
  8842. this._currentRenderId = Number.MAX_VALUE;
  8843. this._isDirty = true;
  8844. };
  8845. AbstractMesh.prototype._updateBoundingInfo = function () {
  8846. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8847. this._boundingInfo.update(this.worldMatrixFromCache);
  8848. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8849. };
  8850. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8851. if (!this.subMeshes) {
  8852. return;
  8853. }
  8854. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8855. var subMesh = this.subMeshes[subIndex];
  8856. if (!subMesh.IsGlobal) {
  8857. subMesh.updateBoundingInfo(matrix);
  8858. }
  8859. }
  8860. };
  8861. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8862. if (this._isWorldMatrixFrozen) {
  8863. return this._worldMatrix;
  8864. }
  8865. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8866. this._currentRenderId = this.getScene().getRenderId();
  8867. return this._worldMatrix;
  8868. }
  8869. this._cache.position.copyFrom(this.position);
  8870. this._cache.scaling.copyFrom(this.scaling);
  8871. this._cache.pivotMatrixUpdated = false;
  8872. this._cache.billboardMode = this.billboardMode;
  8873. this._currentRenderId = this.getScene().getRenderId();
  8874. this._isDirty = false;
  8875. // Scaling
  8876. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8877. // Rotation
  8878. //rotate, if quaternion is set and rotation was used
  8879. if (this.rotationQuaternion) {
  8880. var len = this.rotation.length();
  8881. if (len) {
  8882. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  8883. this.rotation.copyFromFloats(0, 0, 0);
  8884. }
  8885. }
  8886. if (this.rotationQuaternion) {
  8887. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8888. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8889. }
  8890. else {
  8891. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8892. this._cache.rotation.copyFrom(this.rotation);
  8893. }
  8894. // Translation
  8895. if (this.infiniteDistance && !this.parent) {
  8896. var camera = this.getScene().activeCamera;
  8897. if (camera) {
  8898. var cameraWorldMatrix = camera.getWorldMatrix();
  8899. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8900. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8901. }
  8902. }
  8903. else {
  8904. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8905. }
  8906. // Composing transformations
  8907. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8908. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8909. // Billboarding
  8910. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8911. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  8912. var localPosition = BABYLON.Tmp.Vector3[0];
  8913. if (this.parent && this.parent.getWorldMatrix) {
  8914. this._markSyncedWithParent();
  8915. var parentMatrix;
  8916. if (this._meshToBoneReferal) {
  8917. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8918. parentMatrix = BABYLON.Tmp.Matrix[6];
  8919. }
  8920. else {
  8921. parentMatrix = this.parent.getWorldMatrix();
  8922. }
  8923. BABYLON.Vector3.TransformCoordinatesToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  8924. localPosition = BABYLON.Tmp.Vector3[1];
  8925. }
  8926. var zero = this.getScene().activeCamera.globalPosition.clone();
  8927. if (this.parent && this.parent.position) {
  8928. localPosition.addInPlace(this.parent.position);
  8929. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  8930. }
  8931. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8932. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8933. zero.x = localPosition.x + BABYLON.Epsilon;
  8934. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8935. zero.y = localPosition.y + BABYLON.Epsilon;
  8936. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8937. zero.z = localPosition.z + BABYLON.Epsilon;
  8938. }
  8939. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  8940. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  8941. BABYLON.Tmp.Matrix[3].invert();
  8942. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  8943. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  8944. }
  8945. // Local world
  8946. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  8947. // Parent
  8948. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8949. this._markSyncedWithParent();
  8950. if (this._meshToBoneReferal) {
  8951. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8952. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8953. }
  8954. else {
  8955. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8956. }
  8957. }
  8958. else {
  8959. this._worldMatrix.copyFrom(this._localWorld);
  8960. }
  8961. // Bounding info
  8962. this._updateBoundingInfo();
  8963. // Absolute position
  8964. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8965. // Callbacks
  8966. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  8967. if (!this._poseMatrix) {
  8968. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  8969. }
  8970. return this._worldMatrix;
  8971. };
  8972. /**
  8973. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8974. * @param func: callback function to add
  8975. */
  8976. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8977. this.onAfterWorldMatrixUpdateObservable.add(func);
  8978. };
  8979. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8980. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  8981. };
  8982. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8983. this.computeWorldMatrix();
  8984. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8985. };
  8986. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8987. this.computeWorldMatrix();
  8988. var invLocalWorldMatrix = this._localWorld.clone();
  8989. invLocalWorldMatrix.invert();
  8990. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8991. };
  8992. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8993. this.computeWorldMatrix(true);
  8994. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8995. };
  8996. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8997. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8998. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8999. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9000. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9001. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9002. /// <returns>Mesh oriented towards targetMesh</returns>
  9003. yawCor = yawCor || 0; // default to zero if undefined
  9004. pitchCor = pitchCor || 0;
  9005. rollCor = rollCor || 0;
  9006. var dv = targetPoint.subtract(this.position);
  9007. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9008. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9009. var pitch = Math.atan2(dv.y, len);
  9010. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9011. };
  9012. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  9013. this._meshToBoneReferal = affectedMesh;
  9014. this.parent = bone;
  9015. if (bone.getWorldMatrix().determinant() < 0) {
  9016. this.scalingDeterminant *= -1;
  9017. }
  9018. };
  9019. AbstractMesh.prototype.detachFromBone = function () {
  9020. if (this.parent.getWorldMatrix().determinant() < 0) {
  9021. this.scalingDeterminant *= -1;
  9022. }
  9023. this._meshToBoneReferal = null;
  9024. this.parent = null;
  9025. };
  9026. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9027. return this._boundingInfo.isInFrustum(frustumPlanes);
  9028. };
  9029. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9030. if (!camera) {
  9031. camera = this.getScene().activeCamera;
  9032. }
  9033. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9034. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9035. return false;
  9036. }
  9037. return true;
  9038. };
  9039. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9040. if (!this._boundingInfo || !mesh._boundingInfo) {
  9041. return false;
  9042. }
  9043. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9044. };
  9045. AbstractMesh.prototype.intersectsPoint = function (point) {
  9046. if (!this._boundingInfo) {
  9047. return false;
  9048. }
  9049. return this._boundingInfo.intersectsPoint(point);
  9050. };
  9051. // Physics
  9052. /**
  9053. * @Deprecated. Use new PhysicsImpostor instead.
  9054. * */
  9055. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9056. //legacy support
  9057. if (impostor.impostor) {
  9058. options = impostor;
  9059. impostor = impostor.impostor;
  9060. }
  9061. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  9062. return this.physicsImpostor.physicsBody;
  9063. };
  9064. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9065. return this.physicsImpostor;
  9066. };
  9067. /**
  9068. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  9069. */
  9070. AbstractMesh.prototype.getPhysicsMass = function () {
  9071. return this.physicsImpostor.getParam("mass");
  9072. };
  9073. /**
  9074. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  9075. */
  9076. AbstractMesh.prototype.getPhysicsFriction = function () {
  9077. return this.physicsImpostor.getParam("friction");
  9078. };
  9079. /**
  9080. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  9081. */
  9082. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9083. return this.physicsImpostor.getParam("resitution");
  9084. };
  9085. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9086. if (!camera) {
  9087. camera = this.getScene().activeCamera;
  9088. }
  9089. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9090. };
  9091. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9092. if (!camera) {
  9093. camera = this.getScene().activeCamera;
  9094. }
  9095. return this.absolutePosition.subtract(camera.position).length();
  9096. };
  9097. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9098. if (!this.physicsImpostor) {
  9099. return;
  9100. }
  9101. this.physicsImpostor.applyImpulse(force, contactPoint);
  9102. };
  9103. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9104. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  9105. return;
  9106. }
  9107. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  9108. mainPivot: pivot1,
  9109. connectedPivot: pivot2,
  9110. nativeParams: options
  9111. });
  9112. };
  9113. /**
  9114. * @Deprecated
  9115. */
  9116. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9117. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  9118. this.updatePhysicsBody();
  9119. };
  9120. /**
  9121. * @Deprecated
  9122. * Calling this function is not needed anymore.
  9123. * The physics engine takes care of transofmration automatically.
  9124. */
  9125. AbstractMesh.prototype.updatePhysicsBody = function () {
  9126. //Unneeded
  9127. };
  9128. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  9129. // Collisions
  9130. get: function () {
  9131. return this._checkCollisions;
  9132. },
  9133. set: function (collisionEnabled) {
  9134. this._checkCollisions = collisionEnabled;
  9135. if (this.getScene().workerCollisions) {
  9136. this.getScene().collisionCoordinator.onMeshUpdated(this);
  9137. }
  9138. },
  9139. enumerable: true,
  9140. configurable: true
  9141. });
  9142. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9143. var globalPosition = this.getAbsolutePosition();
  9144. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9145. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9146. this._collider.radius = this.ellipsoid;
  9147. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  9148. };
  9149. // Submeshes octree
  9150. /**
  9151. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9152. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9153. */
  9154. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9155. if (maxCapacity === void 0) { maxCapacity = 64; }
  9156. if (maxDepth === void 0) { maxDepth = 2; }
  9157. if (!this._submeshesOctree) {
  9158. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9159. }
  9160. this.computeWorldMatrix(true);
  9161. // Update octree
  9162. var bbox = this.getBoundingInfo().boundingBox;
  9163. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9164. return this._submeshesOctree;
  9165. };
  9166. // Collisions
  9167. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9168. this._generatePointsArray();
  9169. // Transformation
  9170. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9171. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9172. subMesh._lastColliderWorldVertices = [];
  9173. subMesh._trianglePlanes = [];
  9174. var start = subMesh.verticesStart;
  9175. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9176. for (var i = start; i < end; i++) {
  9177. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9178. }
  9179. }
  9180. // Collide
  9181. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  9182. if (collider.collisionFound) {
  9183. collider.collidedMesh = this;
  9184. }
  9185. };
  9186. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9187. var subMeshes;
  9188. var len;
  9189. // Octrees
  9190. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9191. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9192. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9193. len = intersections.length;
  9194. subMeshes = intersections.data;
  9195. }
  9196. else {
  9197. subMeshes = this.subMeshes;
  9198. len = subMeshes.length;
  9199. }
  9200. for (var index = 0; index < len; index++) {
  9201. var subMesh = subMeshes[index];
  9202. // Bounding test
  9203. if (len > 1 && !subMesh._checkCollision(collider))
  9204. continue;
  9205. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9206. }
  9207. };
  9208. AbstractMesh.prototype._checkCollision = function (collider) {
  9209. // Bounding box test
  9210. if (!this._boundingInfo._checkCollision(collider))
  9211. return;
  9212. // Transformation matrix
  9213. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9214. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9215. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9216. };
  9217. // Picking
  9218. AbstractMesh.prototype._generatePointsArray = function () {
  9219. return false;
  9220. };
  9221. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9222. var pickingInfo = new BABYLON.PickingInfo();
  9223. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9224. return pickingInfo;
  9225. }
  9226. if (!this._generatePointsArray()) {
  9227. return pickingInfo;
  9228. }
  9229. var intersectInfo = null;
  9230. // Octrees
  9231. var subMeshes;
  9232. var len;
  9233. if (this._submeshesOctree && this.useOctreeForPicking) {
  9234. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9235. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9236. len = intersections.length;
  9237. subMeshes = intersections.data;
  9238. }
  9239. else {
  9240. subMeshes = this.subMeshes;
  9241. len = subMeshes.length;
  9242. }
  9243. for (var index = 0; index < len; index++) {
  9244. var subMesh = subMeshes[index];
  9245. // Bounding test
  9246. if (len > 1 && !subMesh.canIntersects(ray))
  9247. continue;
  9248. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9249. if (currentIntersectInfo) {
  9250. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9251. intersectInfo = currentIntersectInfo;
  9252. intersectInfo.subMeshId = index;
  9253. if (fastCheck) {
  9254. break;
  9255. }
  9256. }
  9257. }
  9258. }
  9259. if (intersectInfo) {
  9260. // Get picked point
  9261. var world = this.getWorldMatrix();
  9262. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9263. var direction = ray.direction.clone();
  9264. direction = direction.scale(intersectInfo.distance);
  9265. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9266. var pickedPoint = worldOrigin.add(worldDirection);
  9267. // Return result
  9268. pickingInfo.hit = true;
  9269. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9270. pickingInfo.pickedPoint = pickedPoint;
  9271. pickingInfo.pickedMesh = this;
  9272. pickingInfo.bu = intersectInfo.bu;
  9273. pickingInfo.bv = intersectInfo.bv;
  9274. pickingInfo.faceId = intersectInfo.faceId;
  9275. pickingInfo.subMeshId = intersectInfo.subMeshId;
  9276. return pickingInfo;
  9277. }
  9278. return pickingInfo;
  9279. };
  9280. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9281. return null;
  9282. };
  9283. AbstractMesh.prototype.releaseSubMeshes = function () {
  9284. if (this.subMeshes) {
  9285. while (this.subMeshes.length) {
  9286. this.subMeshes[0].dispose();
  9287. }
  9288. }
  9289. else {
  9290. this.subMeshes = new Array();
  9291. }
  9292. };
  9293. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9294. var _this = this;
  9295. var index;
  9296. // Action manager
  9297. if (this.actionManager) {
  9298. this.actionManager.dispose();
  9299. this.actionManager = null;
  9300. }
  9301. // Skeleton
  9302. this.skeleton = null;
  9303. // Animations
  9304. this.getScene().stopAnimation(this);
  9305. // Physics
  9306. if (this.physicsImpostor) {
  9307. this.physicsImpostor.dispose();
  9308. }
  9309. // Intersections in progress
  9310. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9311. var other = this._intersectionsInProgress[index];
  9312. var pos = other._intersectionsInProgress.indexOf(this);
  9313. other._intersectionsInProgress.splice(pos, 1);
  9314. }
  9315. this._intersectionsInProgress = [];
  9316. // Lights
  9317. var lights = this.getScene().lights;
  9318. lights.forEach(function (light) {
  9319. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  9320. if (meshIndex !== -1) {
  9321. light.includedOnlyMeshes.splice(meshIndex, 1);
  9322. }
  9323. meshIndex = light.excludedMeshes.indexOf(_this);
  9324. if (meshIndex !== -1) {
  9325. light.excludedMeshes.splice(meshIndex, 1);
  9326. }
  9327. });
  9328. // Edges
  9329. if (this._edgesRenderer) {
  9330. this._edgesRenderer.dispose();
  9331. this._edgesRenderer = null;
  9332. }
  9333. // SubMeshes
  9334. this.releaseSubMeshes();
  9335. // Remove from scene
  9336. this.getScene().removeMesh(this);
  9337. if (!doNotRecurse) {
  9338. // Particles
  9339. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9340. if (this.getScene().particleSystems[index].emitter === this) {
  9341. this.getScene().particleSystems[index].dispose();
  9342. index--;
  9343. }
  9344. }
  9345. // Children
  9346. var objects = this.getDescendants(true);
  9347. for (index = 0; index < objects.length; index++) {
  9348. objects[index].dispose();
  9349. }
  9350. }
  9351. else {
  9352. var childMeshes = this.getChildMeshes(true);
  9353. for (index = 0; index < childMeshes.length; index++) {
  9354. var child = childMeshes[index];
  9355. child.parent = null;
  9356. child.computeWorldMatrix(true);
  9357. }
  9358. }
  9359. _super.prototype.dispose.call(this);
  9360. this.onAfterWorldMatrixUpdateObservable.clear();
  9361. this._isDisposed = true;
  9362. // Callback
  9363. if (this.onDispose) {
  9364. this.onDispose();
  9365. }
  9366. };
  9367. // Statics
  9368. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9369. AbstractMesh._BILLBOARDMODE_X = 1;
  9370. AbstractMesh._BILLBOARDMODE_Y = 2;
  9371. AbstractMesh._BILLBOARDMODE_Z = 4;
  9372. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9373. return AbstractMesh;
  9374. })(BABYLON.Node);
  9375. BABYLON.AbstractMesh = AbstractMesh;
  9376. })(BABYLON || (BABYLON = {}));
  9377. var BABYLON;
  9378. (function (BABYLON) {
  9379. var Light = (function (_super) {
  9380. __extends(Light, _super);
  9381. function Light(name, scene) {
  9382. _super.call(this, name, scene);
  9383. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  9384. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  9385. this.intensity = 1.0;
  9386. this.range = Number.MAX_VALUE;
  9387. this.includeOnlyWithLayerMask = 0;
  9388. this.includedOnlyMeshes = new Array();
  9389. this.excludedMeshes = new Array();
  9390. this.excludeWithLayerMask = 0;
  9391. // PBR Properties.
  9392. this.radius = 0.00001;
  9393. this._excludedMeshesIds = new Array();
  9394. this._includedOnlyMeshesIds = new Array();
  9395. scene.addLight(this);
  9396. }
  9397. /**
  9398. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9399. */
  9400. Light.prototype.toString = function (fullDetails) {
  9401. var ret = "Name: " + this.name;
  9402. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  9403. if (this.animations) {
  9404. for (var i = 0; i < this.animations.length; i++) {
  9405. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  9406. }
  9407. }
  9408. if (fullDetails) {
  9409. }
  9410. return ret;
  9411. };
  9412. Light.prototype.getShadowGenerator = function () {
  9413. return this._shadowGenerator;
  9414. };
  9415. Light.prototype.getAbsolutePosition = function () {
  9416. return BABYLON.Vector3.Zero();
  9417. };
  9418. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  9419. };
  9420. Light.prototype._getWorldMatrix = function () {
  9421. return BABYLON.Matrix.Identity();
  9422. };
  9423. Light.prototype.canAffectMesh = function (mesh) {
  9424. if (!mesh) {
  9425. return true;
  9426. }
  9427. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  9428. return false;
  9429. }
  9430. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  9431. return false;
  9432. }
  9433. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  9434. return false;
  9435. }
  9436. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  9437. return false;
  9438. }
  9439. return true;
  9440. };
  9441. Light.prototype.getWorldMatrix = function () {
  9442. this._currentRenderId = this.getScene().getRenderId();
  9443. var worldMatrix = this._getWorldMatrix();
  9444. if (this.parent && this.parent.getWorldMatrix) {
  9445. if (!this._parentedWorldMatrix) {
  9446. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  9447. }
  9448. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  9449. this._markSyncedWithParent();
  9450. return this._parentedWorldMatrix;
  9451. }
  9452. return worldMatrix;
  9453. };
  9454. Light.prototype.dispose = function () {
  9455. if (this._shadowGenerator) {
  9456. this._shadowGenerator.dispose();
  9457. this._shadowGenerator = null;
  9458. }
  9459. // Animations
  9460. this.getScene().stopAnimation(this);
  9461. // Remove from scene
  9462. this.getScene().removeLight(this);
  9463. _super.prototype.dispose.call(this);
  9464. };
  9465. Light.prototype.getTypeID = function () {
  9466. return 0;
  9467. };
  9468. Light.prototype.clone = function (name) {
  9469. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  9470. };
  9471. Light.prototype.serialize = function () {
  9472. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  9473. // Type
  9474. serializationObject.type = this.getTypeID();
  9475. // Parent
  9476. if (this.parent) {
  9477. serializationObject.parentId = this.parent.id;
  9478. }
  9479. // Inclusion / exclusions
  9480. if (this.excludedMeshes.length > 0) {
  9481. serializationObject.excludedMeshesIds = [];
  9482. this.excludedMeshes.forEach(function (mesh) {
  9483. serializationObject.excludedMeshesIds.push(mesh.id);
  9484. });
  9485. }
  9486. if (this.includedOnlyMeshes.length > 0) {
  9487. serializationObject.includedOnlyMeshesIds = [];
  9488. this.includedOnlyMeshes.forEach(function (mesh) {
  9489. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  9490. });
  9491. }
  9492. // Animations
  9493. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  9494. serializationObject.ranges = this.serializeAnimationRanges();
  9495. return serializationObject;
  9496. };
  9497. Light.GetConstructorFromName = function (type, name, scene) {
  9498. switch (type) {
  9499. case 0:
  9500. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  9501. case 1:
  9502. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  9503. case 2:
  9504. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  9505. case 3:
  9506. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  9507. }
  9508. };
  9509. Light.Parse = function (parsedLight, scene) {
  9510. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  9511. // Inclusion / exclusions
  9512. if (parsedLight.excludedMeshesIds) {
  9513. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  9514. }
  9515. if (parsedLight.includedOnlyMeshesIds) {
  9516. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  9517. }
  9518. // Parent
  9519. if (parsedLight.parentId) {
  9520. light._waitingParentId = parsedLight.parentId;
  9521. }
  9522. // Animations
  9523. if (parsedLight.animations) {
  9524. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  9525. var parsedAnimation = parsedLight.animations[animationIndex];
  9526. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  9527. }
  9528. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  9529. }
  9530. if (parsedLight.autoAnimate) {
  9531. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  9532. }
  9533. return light;
  9534. };
  9535. __decorate([
  9536. BABYLON.serializeAsColor3()
  9537. ], Light.prototype, "diffuse", void 0);
  9538. __decorate([
  9539. BABYLON.serializeAsColor3()
  9540. ], Light.prototype, "specular", void 0);
  9541. __decorate([
  9542. BABYLON.serialize()
  9543. ], Light.prototype, "intensity", void 0);
  9544. __decorate([
  9545. BABYLON.serialize()
  9546. ], Light.prototype, "range", void 0);
  9547. __decorate([
  9548. BABYLON.serialize()
  9549. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  9550. __decorate([
  9551. BABYLON.serialize()
  9552. ], Light.prototype, "excludeWithLayerMask", void 0);
  9553. __decorate([
  9554. BABYLON.serialize()
  9555. ], Light.prototype, "radius", void 0);
  9556. return Light;
  9557. })(BABYLON.Node);
  9558. BABYLON.Light = Light;
  9559. })(BABYLON || (BABYLON = {}));
  9560. var BABYLON;
  9561. (function (BABYLON) {
  9562. var PointLight = (function (_super) {
  9563. __extends(PointLight, _super);
  9564. function PointLight(name, position, scene) {
  9565. _super.call(this, name, scene);
  9566. this.position = position;
  9567. }
  9568. PointLight.prototype.getAbsolutePosition = function () {
  9569. return this.transformedPosition ? this.transformedPosition : this.position;
  9570. };
  9571. PointLight.prototype.computeTransformedPosition = function () {
  9572. if (this.parent && this.parent.getWorldMatrix) {
  9573. if (!this.transformedPosition) {
  9574. this.transformedPosition = BABYLON.Vector3.Zero();
  9575. }
  9576. BABYLON.Vector3.TransformCoordinatesToRef(this.getAbsolutePosition(), this.parent.getWorldMatrix(), this.transformedPosition);
  9577. return true;
  9578. }
  9579. return false;
  9580. };
  9581. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  9582. if (this.parent && this.parent.getWorldMatrix) {
  9583. this.computeTransformedPosition();
  9584. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  9585. return;
  9586. }
  9587. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  9588. };
  9589. PointLight.prototype.needCube = function () {
  9590. return true;
  9591. };
  9592. PointLight.prototype.supportsVSM = function () {
  9593. return false;
  9594. };
  9595. PointLight.prototype.needRefreshPerFrame = function () {
  9596. return false;
  9597. };
  9598. PointLight.prototype.getShadowDirection = function (faceIndex) {
  9599. switch (faceIndex) {
  9600. case 0:
  9601. return new BABYLON.Vector3(1, 0, 0);
  9602. case 1:
  9603. return new BABYLON.Vector3(-1, 0, 0);
  9604. case 2:
  9605. return new BABYLON.Vector3(0, -1, 0);
  9606. case 3:
  9607. return new BABYLON.Vector3(0, 1, 0);
  9608. case 4:
  9609. return new BABYLON.Vector3(0, 0, 1);
  9610. case 5:
  9611. return new BABYLON.Vector3(0, 0, -1);
  9612. }
  9613. return BABYLON.Vector3.Zero();
  9614. };
  9615. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9616. var activeCamera = this.getScene().activeCamera;
  9617. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9618. };
  9619. PointLight.prototype._getWorldMatrix = function () {
  9620. if (!this._worldMatrix) {
  9621. this._worldMatrix = BABYLON.Matrix.Identity();
  9622. }
  9623. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9624. return this._worldMatrix;
  9625. };
  9626. PointLight.prototype.getTypeID = function () {
  9627. return 0;
  9628. };
  9629. __decorate([
  9630. BABYLON.serializeAsVector3()
  9631. ], PointLight.prototype, "position", void 0);
  9632. return PointLight;
  9633. })(BABYLON.Light);
  9634. BABYLON.PointLight = PointLight;
  9635. })(BABYLON || (BABYLON = {}));
  9636. var BABYLON;
  9637. (function (BABYLON) {
  9638. var SpotLight = (function (_super) {
  9639. __extends(SpotLight, _super);
  9640. function SpotLight(name, position, direction, angle, exponent, scene) {
  9641. _super.call(this, name, scene);
  9642. this.position = position;
  9643. this.direction = direction;
  9644. this.angle = angle;
  9645. this.exponent = exponent;
  9646. }
  9647. SpotLight.prototype.getAbsolutePosition = function () {
  9648. return this.transformedPosition ? this.transformedPosition : this.position;
  9649. };
  9650. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9651. var activeCamera = this.getScene().activeCamera;
  9652. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9653. };
  9654. SpotLight.prototype.needCube = function () {
  9655. return false;
  9656. };
  9657. SpotLight.prototype.supportsVSM = function () {
  9658. return true;
  9659. };
  9660. SpotLight.prototype.needRefreshPerFrame = function () {
  9661. return false;
  9662. };
  9663. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  9664. return this.direction;
  9665. };
  9666. SpotLight.prototype.setDirectionToTarget = function (target) {
  9667. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9668. return this.direction;
  9669. };
  9670. SpotLight.prototype.computeTransformedPosition = function () {
  9671. if (this.parent && this.parent.getWorldMatrix) {
  9672. if (!this.transformedPosition) {
  9673. this.transformedPosition = BABYLON.Vector3.Zero();
  9674. }
  9675. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9676. return true;
  9677. }
  9678. return false;
  9679. };
  9680. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  9681. var normalizeDirection;
  9682. if (this.parent && this.parent.getWorldMatrix) {
  9683. if (!this._transformedDirection) {
  9684. this._transformedDirection = BABYLON.Vector3.Zero();
  9685. }
  9686. this.computeTransformedPosition();
  9687. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9688. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  9689. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  9690. }
  9691. else {
  9692. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  9693. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9694. }
  9695. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  9696. };
  9697. SpotLight.prototype._getWorldMatrix = function () {
  9698. if (!this._worldMatrix) {
  9699. this._worldMatrix = BABYLON.Matrix.Identity();
  9700. }
  9701. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9702. return this._worldMatrix;
  9703. };
  9704. SpotLight.prototype.getTypeID = function () {
  9705. return 2;
  9706. };
  9707. __decorate([
  9708. BABYLON.serializeAsVector3()
  9709. ], SpotLight.prototype, "position", void 0);
  9710. __decorate([
  9711. BABYLON.serializeAsVector3()
  9712. ], SpotLight.prototype, "direction", void 0);
  9713. __decorate([
  9714. BABYLON.serialize()
  9715. ], SpotLight.prototype, "angle", void 0);
  9716. __decorate([
  9717. BABYLON.serialize()
  9718. ], SpotLight.prototype, "exponent", void 0);
  9719. return SpotLight;
  9720. })(BABYLON.Light);
  9721. BABYLON.SpotLight = SpotLight;
  9722. })(BABYLON || (BABYLON = {}));
  9723. var BABYLON;
  9724. (function (BABYLON) {
  9725. var HemisphericLight = (function (_super) {
  9726. __extends(HemisphericLight, _super);
  9727. function HemisphericLight(name, direction, scene) {
  9728. _super.call(this, name, scene);
  9729. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  9730. this.direction = direction;
  9731. }
  9732. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  9733. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  9734. return this.direction;
  9735. };
  9736. HemisphericLight.prototype.getShadowGenerator = function () {
  9737. return null;
  9738. };
  9739. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  9740. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9741. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  9742. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  9743. };
  9744. HemisphericLight.prototype._getWorldMatrix = function () {
  9745. if (!this._worldMatrix) {
  9746. this._worldMatrix = BABYLON.Matrix.Identity();
  9747. }
  9748. return this._worldMatrix;
  9749. };
  9750. HemisphericLight.prototype.getTypeID = function () {
  9751. return 3;
  9752. };
  9753. __decorate([
  9754. BABYLON.serializeAsColor3()
  9755. ], HemisphericLight.prototype, "groundColor", void 0);
  9756. __decorate([
  9757. BABYLON.serializeAsVector3()
  9758. ], HemisphericLight.prototype, "direction", void 0);
  9759. return HemisphericLight;
  9760. })(BABYLON.Light);
  9761. BABYLON.HemisphericLight = HemisphericLight;
  9762. })(BABYLON || (BABYLON = {}));
  9763. var BABYLON;
  9764. (function (BABYLON) {
  9765. var DirectionalLight = (function (_super) {
  9766. __extends(DirectionalLight, _super);
  9767. function DirectionalLight(name, direction, scene) {
  9768. _super.call(this, name, scene);
  9769. this.shadowOrthoScale = 0.5;
  9770. this.autoUpdateExtends = true;
  9771. // Cache
  9772. this._orthoLeft = Number.MAX_VALUE;
  9773. this._orthoRight = Number.MIN_VALUE;
  9774. this._orthoTop = Number.MIN_VALUE;
  9775. this._orthoBottom = Number.MAX_VALUE;
  9776. this.position = direction.scale(-1);
  9777. this.direction = direction;
  9778. }
  9779. DirectionalLight.prototype.getAbsolutePosition = function () {
  9780. return this.transformedPosition ? this.transformedPosition : this.position;
  9781. };
  9782. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  9783. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9784. return this.direction;
  9785. };
  9786. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9787. var activeCamera = this.getScene().activeCamera;
  9788. // Check extends
  9789. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  9790. var tempVector3 = BABYLON.Vector3.Zero();
  9791. this._orthoLeft = Number.MAX_VALUE;
  9792. this._orthoRight = Number.MIN_VALUE;
  9793. this._orthoTop = Number.MIN_VALUE;
  9794. this._orthoBottom = Number.MAX_VALUE;
  9795. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  9796. var mesh = renderList[meshIndex];
  9797. if (!mesh) {
  9798. continue;
  9799. }
  9800. var boundingInfo = mesh.getBoundingInfo();
  9801. if (!boundingInfo) {
  9802. continue;
  9803. }
  9804. var boundingBox = boundingInfo.boundingBox;
  9805. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  9806. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  9807. if (tempVector3.x < this._orthoLeft)
  9808. this._orthoLeft = tempVector3.x;
  9809. if (tempVector3.y < this._orthoBottom)
  9810. this._orthoBottom = tempVector3.y;
  9811. if (tempVector3.x > this._orthoRight)
  9812. this._orthoRight = tempVector3.x;
  9813. if (tempVector3.y > this._orthoTop)
  9814. this._orthoTop = tempVector3.y;
  9815. }
  9816. }
  9817. }
  9818. var xOffset = this._orthoRight - this._orthoLeft;
  9819. var yOffset = this._orthoTop - this._orthoBottom;
  9820. 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);
  9821. };
  9822. DirectionalLight.prototype.supportsVSM = function () {
  9823. return true;
  9824. };
  9825. DirectionalLight.prototype.needRefreshPerFrame = function () {
  9826. return true;
  9827. };
  9828. DirectionalLight.prototype.needCube = function () {
  9829. return false;
  9830. };
  9831. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  9832. return this.direction;
  9833. };
  9834. DirectionalLight.prototype.computeTransformedPosition = function () {
  9835. if (this.parent && this.parent.getWorldMatrix) {
  9836. if (!this.transformedPosition) {
  9837. this.transformedPosition = BABYLON.Vector3.Zero();
  9838. }
  9839. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9840. return true;
  9841. }
  9842. return false;
  9843. };
  9844. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  9845. if (this.parent && this.parent.getWorldMatrix) {
  9846. if (!this._transformedDirection) {
  9847. this._transformedDirection = BABYLON.Vector3.Zero();
  9848. }
  9849. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9850. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  9851. return;
  9852. }
  9853. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  9854. };
  9855. DirectionalLight.prototype._getWorldMatrix = function () {
  9856. if (!this._worldMatrix) {
  9857. this._worldMatrix = BABYLON.Matrix.Identity();
  9858. }
  9859. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9860. return this._worldMatrix;
  9861. };
  9862. DirectionalLight.prototype.getTypeID = function () {
  9863. return 1;
  9864. };
  9865. __decorate([
  9866. BABYLON.serializeAsVector3()
  9867. ], DirectionalLight.prototype, "position", void 0);
  9868. __decorate([
  9869. BABYLON.serializeAsVector3()
  9870. ], DirectionalLight.prototype, "direction", void 0);
  9871. __decorate([
  9872. BABYLON.serialize()
  9873. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  9874. __decorate([
  9875. BABYLON.serialize()
  9876. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  9877. return DirectionalLight;
  9878. })(BABYLON.Light);
  9879. BABYLON.DirectionalLight = DirectionalLight;
  9880. })(BABYLON || (BABYLON = {}));
  9881. var BABYLON;
  9882. (function (BABYLON) {
  9883. var ShadowGenerator = (function () {
  9884. function ShadowGenerator(mapSize, light) {
  9885. var _this = this;
  9886. // Members
  9887. this._filter = ShadowGenerator.FILTER_NONE;
  9888. this.blurScale = 2;
  9889. this._blurBoxOffset = 0;
  9890. this._bias = 0.00005;
  9891. this._lightDirection = BABYLON.Vector3.Zero();
  9892. this.forceBackFacesOnly = false;
  9893. this._darkness = 0;
  9894. this._transparencyShadow = false;
  9895. this._viewMatrix = BABYLON.Matrix.Zero();
  9896. this._projectionMatrix = BABYLON.Matrix.Zero();
  9897. this._transformMatrix = BABYLON.Matrix.Zero();
  9898. this._worldViewProjection = BABYLON.Matrix.Zero();
  9899. this._currentFaceIndex = 0;
  9900. this._currentFaceIndexCache = 0;
  9901. this._light = light;
  9902. this._scene = light.getScene();
  9903. this._mapSize = mapSize;
  9904. light._shadowGenerator = this;
  9905. // Render target
  9906. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  9907. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9908. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9909. this._shadowMap.anisotropicFilteringLevel = 1;
  9910. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9911. this._shadowMap.renderParticles = false;
  9912. this._shadowMap.onBeforeRender = function (faceIndex) {
  9913. _this._currentFaceIndex = faceIndex;
  9914. };
  9915. this._shadowMap.onAfterUnbind = function () {
  9916. if (!_this.useBlurVarianceShadowMap) {
  9917. return;
  9918. }
  9919. if (!_this._shadowMap2) {
  9920. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9921. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9922. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9923. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9924. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9925. _this._downSamplePostprocess.onApply = function (effect) {
  9926. effect.setTexture("textureSampler", _this._shadowMap);
  9927. };
  9928. _this.blurBoxOffset = 1;
  9929. }
  9930. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9931. };
  9932. // Custom render function
  9933. var renderSubMesh = function (subMesh) {
  9934. var mesh = subMesh.getRenderingMesh();
  9935. var scene = _this._scene;
  9936. var engine = scene.getEngine();
  9937. // Culling
  9938. engine.setState(subMesh.getMaterial().backFaceCulling);
  9939. // Managing instances
  9940. var batch = mesh._getInstancesRenderList(subMesh._id);
  9941. if (batch.mustReturn) {
  9942. return;
  9943. }
  9944. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9945. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9946. engine.enableEffect(_this._effect);
  9947. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9948. var material = subMesh.getMaterial();
  9949. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9950. _this._effect.setVector3("lightPosition", _this.getLight().position);
  9951. if (_this.getLight().needCube()) {
  9952. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  9953. }
  9954. // Alpha test
  9955. if (material && material.needAlphaTesting()) {
  9956. var alphaTexture = material.getAlphaTestTexture();
  9957. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9958. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9959. }
  9960. // Bones
  9961. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9962. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  9963. }
  9964. if (_this.forceBackFacesOnly) {
  9965. engine.setState(true, 0, false, true);
  9966. }
  9967. // Draw
  9968. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9969. if (_this.forceBackFacesOnly) {
  9970. engine.setState(true, 0, false, false);
  9971. }
  9972. }
  9973. else {
  9974. // Need to reset refresh rate of the shadowMap
  9975. _this._shadowMap.resetRefreshCounter();
  9976. }
  9977. };
  9978. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9979. var index;
  9980. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9981. renderSubMesh(opaqueSubMeshes.data[index]);
  9982. }
  9983. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9984. renderSubMesh(alphaTestSubMeshes.data[index]);
  9985. }
  9986. if (_this._transparencyShadow) {
  9987. for (index = 0; index < transparentSubMeshes.length; index++) {
  9988. renderSubMesh(transparentSubMeshes.data[index]);
  9989. }
  9990. }
  9991. };
  9992. this._shadowMap.onClear = function (engine) {
  9993. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9994. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9995. }
  9996. else {
  9997. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9998. }
  9999. };
  10000. }
  10001. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  10002. // Static
  10003. get: function () {
  10004. return ShadowGenerator._FILTER_NONE;
  10005. },
  10006. enumerable: true,
  10007. configurable: true
  10008. });
  10009. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  10010. get: function () {
  10011. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  10012. },
  10013. enumerable: true,
  10014. configurable: true
  10015. });
  10016. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  10017. get: function () {
  10018. return ShadowGenerator._FILTER_POISSONSAMPLING;
  10019. },
  10020. enumerable: true,
  10021. configurable: true
  10022. });
  10023. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  10024. get: function () {
  10025. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  10026. },
  10027. enumerable: true,
  10028. configurable: true
  10029. });
  10030. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  10031. get: function () {
  10032. return this._bias;
  10033. },
  10034. set: function (bias) {
  10035. this._bias = bias;
  10036. },
  10037. enumerable: true,
  10038. configurable: true
  10039. });
  10040. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  10041. get: function () {
  10042. return this._blurBoxOffset;
  10043. },
  10044. set: function (value) {
  10045. var _this = this;
  10046. if (this._blurBoxOffset === value) {
  10047. return;
  10048. }
  10049. this._blurBoxOffset = value;
  10050. if (this._boxBlurPostprocess) {
  10051. this._boxBlurPostprocess.dispose();
  10052. }
  10053. 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);
  10054. this._boxBlurPostprocess.onApply = function (effect) {
  10055. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  10056. };
  10057. },
  10058. enumerable: true,
  10059. configurable: true
  10060. });
  10061. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  10062. get: function () {
  10063. return this._filter;
  10064. },
  10065. set: function (value) {
  10066. if (this._filter === value) {
  10067. return;
  10068. }
  10069. this._filter = value;
  10070. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  10071. this._shadowMap.anisotropicFilteringLevel = 16;
  10072. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  10073. }
  10074. else {
  10075. this._shadowMap.anisotropicFilteringLevel = 1;
  10076. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10077. }
  10078. },
  10079. enumerable: true,
  10080. configurable: true
  10081. });
  10082. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  10083. get: function () {
  10084. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  10085. },
  10086. set: function (value) {
  10087. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10088. },
  10089. enumerable: true,
  10090. configurable: true
  10091. });
  10092. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  10093. get: function () {
  10094. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  10095. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  10096. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  10097. },
  10098. set: function (value) {
  10099. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  10100. },
  10101. enumerable: true,
  10102. configurable: true
  10103. });
  10104. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  10105. get: function () {
  10106. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  10107. },
  10108. set: function (value) {
  10109. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10110. },
  10111. enumerable: true,
  10112. configurable: true
  10113. });
  10114. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  10115. var defines = [];
  10116. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  10117. defines.push("#define VSM");
  10118. }
  10119. if (this.getLight().needCube()) {
  10120. defines.push("#define CUBEMAP");
  10121. }
  10122. var attribs = [BABYLON.VertexBuffer.PositionKind];
  10123. var mesh = subMesh.getMesh();
  10124. var material = subMesh.getMaterial();
  10125. // Alpha test
  10126. if (material && material.needAlphaTesting()) {
  10127. defines.push("#define ALPHATEST");
  10128. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10129. attribs.push(BABYLON.VertexBuffer.UVKind);
  10130. defines.push("#define UV1");
  10131. }
  10132. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10133. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10134. defines.push("#define UV2");
  10135. }
  10136. }
  10137. // Bones
  10138. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10139. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10140. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10141. if (mesh.numBoneInfluencers > 4) {
  10142. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  10143. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  10144. }
  10145. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  10146. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10147. }
  10148. else {
  10149. defines.push("#define NUM_BONE_INFLUENCERS 0");
  10150. }
  10151. // Instances
  10152. if (useInstances) {
  10153. defines.push("#define INSTANCES");
  10154. attribs.push("world0");
  10155. attribs.push("world1");
  10156. attribs.push("world2");
  10157. attribs.push("world3");
  10158. }
  10159. // Get correct effect
  10160. var join = defines.join("\n");
  10161. if (this._cachedDefines !== join) {
  10162. this._cachedDefines = join;
  10163. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  10164. }
  10165. return this._effect.isReady();
  10166. };
  10167. ShadowGenerator.prototype.getShadowMap = function () {
  10168. return this._shadowMap;
  10169. };
  10170. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  10171. if (this._shadowMap2) {
  10172. return this._shadowMap2;
  10173. }
  10174. return this._shadowMap;
  10175. };
  10176. ShadowGenerator.prototype.getLight = function () {
  10177. return this._light;
  10178. };
  10179. // Methods
  10180. ShadowGenerator.prototype.getTransformMatrix = function () {
  10181. var scene = this._scene;
  10182. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  10183. return this._transformMatrix;
  10184. }
  10185. this._currentRenderID = scene.getRenderId();
  10186. this._currentFaceIndexCache = this._currentFaceIndex;
  10187. var lightPosition = this._light.position;
  10188. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  10189. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  10190. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  10191. }
  10192. if (this._light.computeTransformedPosition()) {
  10193. lightPosition = this._light.transformedPosition;
  10194. }
  10195. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  10196. this._cachedPosition = lightPosition.clone();
  10197. this._cachedDirection = this._lightDirection.clone();
  10198. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  10199. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  10200. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  10201. }
  10202. return this._transformMatrix;
  10203. };
  10204. ShadowGenerator.prototype.getDarkness = function () {
  10205. return this._darkness;
  10206. };
  10207. ShadowGenerator.prototype.setDarkness = function (darkness) {
  10208. if (darkness >= 1.0)
  10209. this._darkness = 1.0;
  10210. else if (darkness <= 0.0)
  10211. this._darkness = 0.0;
  10212. else
  10213. this._darkness = darkness;
  10214. };
  10215. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  10216. this._transparencyShadow = hasShadow;
  10217. };
  10218. ShadowGenerator.prototype._packHalf = function (depth) {
  10219. var scale = depth * 255.0;
  10220. var fract = scale - Math.floor(scale);
  10221. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  10222. };
  10223. ShadowGenerator.prototype.dispose = function () {
  10224. this._shadowMap.dispose();
  10225. if (this._shadowMap2) {
  10226. this._shadowMap2.dispose();
  10227. }
  10228. if (this._downSamplePostprocess) {
  10229. this._downSamplePostprocess.dispose();
  10230. }
  10231. if (this._boxBlurPostprocess) {
  10232. this._boxBlurPostprocess.dispose();
  10233. }
  10234. };
  10235. ShadowGenerator.prototype.serialize = function () {
  10236. var serializationObject = {};
  10237. serializationObject.lightId = this._light.id;
  10238. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  10239. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  10240. serializationObject.usePoissonSampling = this.usePoissonSampling;
  10241. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  10242. serializationObject.renderList = [];
  10243. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  10244. var mesh = this.getShadowMap().renderList[meshIndex];
  10245. serializationObject.renderList.push(mesh.id);
  10246. }
  10247. return serializationObject;
  10248. };
  10249. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  10250. //casting to point light, as light is missing the position attr and typescript complains.
  10251. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  10252. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  10253. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  10254. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  10255. shadowGenerator.getShadowMap().renderList.push(mesh);
  10256. }
  10257. if (parsedShadowGenerator.usePoissonSampling) {
  10258. shadowGenerator.usePoissonSampling = true;
  10259. }
  10260. else if (parsedShadowGenerator.useVarianceShadowMap) {
  10261. shadowGenerator.useVarianceShadowMap = true;
  10262. }
  10263. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  10264. shadowGenerator.useBlurVarianceShadowMap = true;
  10265. if (parsedShadowGenerator.blurScale) {
  10266. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  10267. }
  10268. if (parsedShadowGenerator.blurBoxOffset) {
  10269. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  10270. }
  10271. }
  10272. if (parsedShadowGenerator.bias !== undefined) {
  10273. shadowGenerator.bias = parsedShadowGenerator.bias;
  10274. }
  10275. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  10276. return shadowGenerator;
  10277. };
  10278. ShadowGenerator._FILTER_NONE = 0;
  10279. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  10280. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  10281. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  10282. return ShadowGenerator;
  10283. })();
  10284. BABYLON.ShadowGenerator = ShadowGenerator;
  10285. })(BABYLON || (BABYLON = {}));
  10286. var BABYLON;
  10287. (function (BABYLON) {
  10288. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  10289. if (boxMin.x > sphereCenter.x + sphereRadius)
  10290. return false;
  10291. if (sphereCenter.x - sphereRadius > boxMax.x)
  10292. return false;
  10293. if (boxMin.y > sphereCenter.y + sphereRadius)
  10294. return false;
  10295. if (sphereCenter.y - sphereRadius > boxMax.y)
  10296. return false;
  10297. if (boxMin.z > sphereCenter.z + sphereRadius)
  10298. return false;
  10299. if (sphereCenter.z - sphereRadius > boxMax.z)
  10300. return false;
  10301. return true;
  10302. };
  10303. var getLowestRoot = function (a, b, c, maxR) {
  10304. var determinant = b * b - 4.0 * a * c;
  10305. var result = { root: 0, found: false };
  10306. if (determinant < 0)
  10307. return result;
  10308. var sqrtD = Math.sqrt(determinant);
  10309. var r1 = (-b - sqrtD) / (2.0 * a);
  10310. var r2 = (-b + sqrtD) / (2.0 * a);
  10311. if (r1 > r2) {
  10312. var temp = r2;
  10313. r2 = r1;
  10314. r1 = temp;
  10315. }
  10316. if (r1 > 0 && r1 < maxR) {
  10317. result.root = r1;
  10318. result.found = true;
  10319. return result;
  10320. }
  10321. if (r2 > 0 && r2 < maxR) {
  10322. result.root = r2;
  10323. result.found = true;
  10324. return result;
  10325. }
  10326. return result;
  10327. };
  10328. var Collider = (function () {
  10329. function Collider() {
  10330. this.radius = new BABYLON.Vector3(1, 1, 1);
  10331. this.retry = 0;
  10332. this.basePointWorld = BABYLON.Vector3.Zero();
  10333. this.velocityWorld = BABYLON.Vector3.Zero();
  10334. this.normalizedVelocity = BABYLON.Vector3.Zero();
  10335. this._collisionPoint = BABYLON.Vector3.Zero();
  10336. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  10337. this._tempVector = BABYLON.Vector3.Zero();
  10338. this._tempVector2 = BABYLON.Vector3.Zero();
  10339. this._tempVector3 = BABYLON.Vector3.Zero();
  10340. this._tempVector4 = BABYLON.Vector3.Zero();
  10341. this._edge = BABYLON.Vector3.Zero();
  10342. this._baseToVertex = BABYLON.Vector3.Zero();
  10343. this._destinationPoint = BABYLON.Vector3.Zero();
  10344. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  10345. this._displacementVector = BABYLON.Vector3.Zero();
  10346. }
  10347. // Methods
  10348. Collider.prototype._initialize = function (source, dir, e) {
  10349. this.velocity = dir;
  10350. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  10351. this.basePoint = source;
  10352. source.multiplyToRef(this.radius, this.basePointWorld);
  10353. dir.multiplyToRef(this.radius, this.velocityWorld);
  10354. this.velocityWorldLength = this.velocityWorld.length();
  10355. this.epsilon = e;
  10356. this.collisionFound = false;
  10357. };
  10358. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  10359. pa.subtractToRef(point, this._tempVector);
  10360. pb.subtractToRef(point, this._tempVector2);
  10361. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  10362. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10363. if (d < 0)
  10364. return false;
  10365. pc.subtractToRef(point, this._tempVector3);
  10366. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  10367. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10368. if (d < 0)
  10369. return false;
  10370. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  10371. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10372. return d >= 0;
  10373. };
  10374. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  10375. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  10376. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  10377. if (distance > this.velocityWorldLength + max + sphereRadius) {
  10378. return false;
  10379. }
  10380. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  10381. return false;
  10382. return true;
  10383. };
  10384. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  10385. var t0;
  10386. var embeddedInPlane = false;
  10387. //defensive programming, actually not needed.
  10388. if (!trianglePlaneArray) {
  10389. trianglePlaneArray = [];
  10390. }
  10391. if (!trianglePlaneArray[faceIndex]) {
  10392. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  10393. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  10394. }
  10395. var trianglePlane = trianglePlaneArray[faceIndex];
  10396. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  10397. return;
  10398. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  10399. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  10400. if (normalDotVelocity == 0) {
  10401. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  10402. return;
  10403. embeddedInPlane = true;
  10404. t0 = 0;
  10405. }
  10406. else {
  10407. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10408. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10409. if (t0 > t1) {
  10410. var temp = t1;
  10411. t1 = t0;
  10412. t0 = temp;
  10413. }
  10414. if (t0 > 1.0 || t1 < 0.0)
  10415. return;
  10416. if (t0 < 0)
  10417. t0 = 0;
  10418. if (t0 > 1.0)
  10419. t0 = 1.0;
  10420. }
  10421. this._collisionPoint.copyFromFloats(0, 0, 0);
  10422. var found = false;
  10423. var t = 1.0;
  10424. if (!embeddedInPlane) {
  10425. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  10426. this.velocity.scaleToRef(t0, this._tempVector);
  10427. this._planeIntersectionPoint.addInPlace(this._tempVector);
  10428. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  10429. found = true;
  10430. t = t0;
  10431. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  10432. }
  10433. }
  10434. if (!found) {
  10435. var velocitySquaredLength = this.velocity.lengthSquared();
  10436. var a = velocitySquaredLength;
  10437. this.basePoint.subtractToRef(p1, this._tempVector);
  10438. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10439. var c = this._tempVector.lengthSquared() - 1.0;
  10440. var lowestRoot = getLowestRoot(a, b, c, t);
  10441. if (lowestRoot.found) {
  10442. t = lowestRoot.root;
  10443. found = true;
  10444. this._collisionPoint.copyFrom(p1);
  10445. }
  10446. this.basePoint.subtractToRef(p2, this._tempVector);
  10447. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10448. c = this._tempVector.lengthSquared() - 1.0;
  10449. lowestRoot = getLowestRoot(a, b, c, t);
  10450. if (lowestRoot.found) {
  10451. t = lowestRoot.root;
  10452. found = true;
  10453. this._collisionPoint.copyFrom(p2);
  10454. }
  10455. this.basePoint.subtractToRef(p3, this._tempVector);
  10456. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10457. c = this._tempVector.lengthSquared() - 1.0;
  10458. lowestRoot = getLowestRoot(a, b, c, t);
  10459. if (lowestRoot.found) {
  10460. t = lowestRoot.root;
  10461. found = true;
  10462. this._collisionPoint.copyFrom(p3);
  10463. }
  10464. p2.subtractToRef(p1, this._edge);
  10465. p1.subtractToRef(this.basePoint, this._baseToVertex);
  10466. var edgeSquaredLength = this._edge.lengthSquared();
  10467. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10468. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10469. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10470. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10471. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10472. lowestRoot = getLowestRoot(a, b, c, t);
  10473. if (lowestRoot.found) {
  10474. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10475. if (f >= 0.0 && f <= 1.0) {
  10476. t = lowestRoot.root;
  10477. found = true;
  10478. this._edge.scaleInPlace(f);
  10479. p1.addToRef(this._edge, this._collisionPoint);
  10480. }
  10481. }
  10482. p3.subtractToRef(p2, this._edge);
  10483. p2.subtractToRef(this.basePoint, this._baseToVertex);
  10484. edgeSquaredLength = this._edge.lengthSquared();
  10485. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10486. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10487. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10488. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10489. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10490. lowestRoot = getLowestRoot(a, b, c, t);
  10491. if (lowestRoot.found) {
  10492. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10493. if (f >= 0.0 && f <= 1.0) {
  10494. t = lowestRoot.root;
  10495. found = true;
  10496. this._edge.scaleInPlace(f);
  10497. p2.addToRef(this._edge, this._collisionPoint);
  10498. }
  10499. }
  10500. p1.subtractToRef(p3, this._edge);
  10501. p3.subtractToRef(this.basePoint, this._baseToVertex);
  10502. edgeSquaredLength = this._edge.lengthSquared();
  10503. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10504. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10505. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10506. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10507. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10508. lowestRoot = getLowestRoot(a, b, c, t);
  10509. if (lowestRoot.found) {
  10510. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10511. if (f >= 0.0 && f <= 1.0) {
  10512. t = lowestRoot.root;
  10513. found = true;
  10514. this._edge.scaleInPlace(f);
  10515. p3.addToRef(this._edge, this._collisionPoint);
  10516. }
  10517. }
  10518. }
  10519. if (found) {
  10520. var distToCollision = t * this.velocity.length();
  10521. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  10522. if (!this.intersectionPoint) {
  10523. this.intersectionPoint = this._collisionPoint.clone();
  10524. }
  10525. else {
  10526. this.intersectionPoint.copyFrom(this._collisionPoint);
  10527. }
  10528. this.nearestDistance = distToCollision;
  10529. this.collisionFound = true;
  10530. }
  10531. }
  10532. };
  10533. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  10534. for (var i = indexStart; i < indexEnd; i += 3) {
  10535. var p1 = pts[indices[i] - decal];
  10536. var p2 = pts[indices[i + 1] - decal];
  10537. var p3 = pts[indices[i + 2] - decal];
  10538. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  10539. }
  10540. };
  10541. Collider.prototype._getResponse = function (pos, vel) {
  10542. pos.addToRef(vel, this._destinationPoint);
  10543. vel.scaleInPlace((this.nearestDistance / vel.length()));
  10544. this.basePoint.addToRef(vel, pos);
  10545. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  10546. this._slidePlaneNormal.normalize();
  10547. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  10548. pos.addInPlace(this._displacementVector);
  10549. this.intersectionPoint.addInPlace(this._displacementVector);
  10550. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  10551. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  10552. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  10553. };
  10554. return Collider;
  10555. })();
  10556. BABYLON.Collider = Collider;
  10557. })(BABYLON || (BABYLON = {}));
  10558. var BABYLON;
  10559. (function (BABYLON) {
  10560. //WebWorker code will be inserted to this variable.
  10561. BABYLON.CollisionWorker = "";
  10562. (function (WorkerTaskType) {
  10563. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  10564. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  10565. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  10566. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  10567. var WorkerTaskType = BABYLON.WorkerTaskType;
  10568. (function (WorkerReplyType) {
  10569. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  10570. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  10571. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  10572. var WorkerReplyType = BABYLON.WorkerReplyType;
  10573. var CollisionCoordinatorWorker = (function () {
  10574. function CollisionCoordinatorWorker() {
  10575. var _this = this;
  10576. this._scaledPosition = BABYLON.Vector3.Zero();
  10577. this._scaledVelocity = BABYLON.Vector3.Zero();
  10578. this.onMeshUpdated = function (mesh) {
  10579. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  10580. };
  10581. this.onGeometryUpdated = function (geometry) {
  10582. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  10583. };
  10584. this._afterRender = function () {
  10585. if (!_this._init)
  10586. return;
  10587. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  10588. return;
  10589. }
  10590. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  10591. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  10592. if (_this._runningUpdated > 4) {
  10593. return;
  10594. }
  10595. ++_this._runningUpdated;
  10596. var payload = {
  10597. updatedMeshes: _this._addUpdateMeshesList,
  10598. updatedGeometries: _this._addUpdateGeometriesList,
  10599. removedGeometries: _this._toRemoveGeometryArray,
  10600. removedMeshes: _this._toRemoveMeshesArray
  10601. };
  10602. var message = {
  10603. payload: payload,
  10604. taskType: WorkerTaskType.UPDATE
  10605. };
  10606. var serializable = [];
  10607. for (var id in payload.updatedGeometries) {
  10608. if (payload.updatedGeometries.hasOwnProperty(id)) {
  10609. //prepare transferables
  10610. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  10611. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  10612. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  10613. }
  10614. }
  10615. _this._worker.postMessage(message, serializable);
  10616. _this._addUpdateMeshesList = {};
  10617. _this._addUpdateGeometriesList = {};
  10618. _this._toRemoveGeometryArray = [];
  10619. _this._toRemoveMeshesArray = [];
  10620. };
  10621. this._onMessageFromWorker = function (e) {
  10622. var returnData = e.data;
  10623. if (returnData.error != WorkerReplyType.SUCCESS) {
  10624. //TODO what errors can be returned from the worker?
  10625. BABYLON.Tools.Warn("error returned from worker!");
  10626. return;
  10627. }
  10628. switch (returnData.taskType) {
  10629. case WorkerTaskType.INIT:
  10630. _this._init = true;
  10631. //Update the worked with ALL of the scene's current state
  10632. _this._scene.meshes.forEach(function (mesh) {
  10633. _this.onMeshAdded(mesh);
  10634. });
  10635. _this._scene.getGeometries().forEach(function (geometry) {
  10636. _this.onGeometryAdded(geometry);
  10637. });
  10638. break;
  10639. case WorkerTaskType.UPDATE:
  10640. _this._runningUpdated--;
  10641. break;
  10642. case WorkerTaskType.COLLIDE:
  10643. _this._runningCollisionTask = false;
  10644. var returnPayload = returnData.payload;
  10645. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  10646. return;
  10647. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  10648. //cleanup
  10649. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  10650. break;
  10651. }
  10652. };
  10653. this._collisionsCallbackArray = [];
  10654. this._init = false;
  10655. this._runningUpdated = 0;
  10656. this._runningCollisionTask = false;
  10657. this._addUpdateMeshesList = {};
  10658. this._addUpdateGeometriesList = {};
  10659. this._toRemoveGeometryArray = [];
  10660. this._toRemoveMeshesArray = [];
  10661. }
  10662. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10663. if (!this._init)
  10664. return;
  10665. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  10666. return;
  10667. position.divideToRef(collider.radius, this._scaledPosition);
  10668. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10669. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  10670. var payload = {
  10671. collider: {
  10672. position: this._scaledPosition.asArray(),
  10673. velocity: this._scaledVelocity.asArray(),
  10674. radius: collider.radius.asArray()
  10675. },
  10676. collisionId: collisionIndex,
  10677. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  10678. maximumRetry: maximumRetry
  10679. };
  10680. var message = {
  10681. payload: payload,
  10682. taskType: WorkerTaskType.COLLIDE
  10683. };
  10684. this._worker.postMessage(message);
  10685. };
  10686. CollisionCoordinatorWorker.prototype.init = function (scene) {
  10687. this._scene = scene;
  10688. this._scene.registerAfterRender(this._afterRender);
  10689. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  10690. this._worker = new Worker(workerUrl);
  10691. this._worker.onmessage = this._onMessageFromWorker;
  10692. var message = {
  10693. payload: {},
  10694. taskType: WorkerTaskType.INIT
  10695. };
  10696. this._worker.postMessage(message);
  10697. };
  10698. CollisionCoordinatorWorker.prototype.destroy = function () {
  10699. this._scene.unregisterAfterRender(this._afterRender);
  10700. this._worker.terminate();
  10701. };
  10702. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  10703. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  10704. this.onMeshUpdated(mesh);
  10705. };
  10706. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  10707. this._toRemoveMeshesArray.push(mesh.uniqueId);
  10708. };
  10709. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  10710. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  10711. geometry.onGeometryUpdated = this.onGeometryUpdated;
  10712. this.onGeometryUpdated(geometry);
  10713. };
  10714. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  10715. this._toRemoveGeometryArray.push(geometry.id);
  10716. };
  10717. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  10718. var submeshes = [];
  10719. if (mesh.subMeshes) {
  10720. submeshes = mesh.subMeshes.map(function (sm, idx) {
  10721. return {
  10722. position: idx,
  10723. verticesStart: sm.verticesStart,
  10724. verticesCount: sm.verticesCount,
  10725. indexStart: sm.indexStart,
  10726. indexCount: sm.indexCount,
  10727. hasMaterial: !!sm.getMaterial(),
  10728. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10729. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  10730. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10731. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  10732. };
  10733. });
  10734. }
  10735. var geometryId = null;
  10736. if (mesh instanceof BABYLON.Mesh) {
  10737. geometryId = mesh.geometry ? mesh.geometry.id : null;
  10738. }
  10739. else if (mesh instanceof BABYLON.InstancedMesh) {
  10740. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  10741. }
  10742. return {
  10743. uniqueId: mesh.uniqueId,
  10744. id: mesh.id,
  10745. name: mesh.name,
  10746. geometryId: geometryId,
  10747. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10748. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  10749. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10750. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  10751. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  10752. subMeshes: submeshes,
  10753. checkCollisions: mesh.checkCollisions
  10754. };
  10755. };
  10756. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  10757. return {
  10758. id: geometry.id,
  10759. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  10760. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  10761. indices: new Int32Array(geometry.getIndices() || []),
  10762. };
  10763. };
  10764. return CollisionCoordinatorWorker;
  10765. })();
  10766. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  10767. var CollisionCoordinatorLegacy = (function () {
  10768. function CollisionCoordinatorLegacy() {
  10769. this._scaledPosition = BABYLON.Vector3.Zero();
  10770. this._scaledVelocity = BABYLON.Vector3.Zero();
  10771. this._finalPosition = BABYLON.Vector3.Zero();
  10772. }
  10773. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10774. position.divideToRef(collider.radius, this._scaledPosition);
  10775. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10776. collider.collidedMesh = null;
  10777. collider.retry = 0;
  10778. collider.initialVelocity = this._scaledVelocity;
  10779. collider.initialPosition = this._scaledPosition;
  10780. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  10781. this._finalPosition.multiplyInPlace(collider.radius);
  10782. //run the callback
  10783. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  10784. };
  10785. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  10786. this._scene = scene;
  10787. };
  10788. CollisionCoordinatorLegacy.prototype.destroy = function () {
  10789. //Legacy need no destruction method.
  10790. };
  10791. //No update in legacy mode
  10792. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  10793. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  10794. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  10795. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  10796. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  10797. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  10798. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  10799. if (excludedMesh === void 0) { excludedMesh = null; }
  10800. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  10801. if (collider.retry >= maximumRetry) {
  10802. finalPosition.copyFrom(position);
  10803. return;
  10804. }
  10805. collider._initialize(position, velocity, closeDistance);
  10806. // Check all meshes
  10807. for (var index = 0; index < this._scene.meshes.length; index++) {
  10808. var mesh = this._scene.meshes[index];
  10809. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  10810. mesh._checkCollision(collider);
  10811. }
  10812. }
  10813. if (!collider.collisionFound) {
  10814. position.addToRef(velocity, finalPosition);
  10815. return;
  10816. }
  10817. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  10818. collider._getResponse(position, velocity);
  10819. }
  10820. if (velocity.length() <= closeDistance) {
  10821. finalPosition.copyFrom(position);
  10822. return;
  10823. }
  10824. collider.retry++;
  10825. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  10826. };
  10827. return CollisionCoordinatorLegacy;
  10828. })();
  10829. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  10830. })(BABYLON || (BABYLON = {}));
  10831. var BABYLON;
  10832. (function (BABYLON) {
  10833. var Camera = (function (_super) {
  10834. __extends(Camera, _super);
  10835. function Camera(name, position, scene) {
  10836. _super.call(this, name, scene);
  10837. this.upVector = BABYLON.Vector3.Up();
  10838. this.orthoLeft = null;
  10839. this.orthoRight = null;
  10840. this.orthoBottom = null;
  10841. this.orthoTop = null;
  10842. this.fov = 0.8;
  10843. this.minZ = 1.0;
  10844. this.maxZ = 10000.0;
  10845. this.inertia = 0.9;
  10846. this.mode = Camera.PERSPECTIVE_CAMERA;
  10847. this.isIntermediate = false;
  10848. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  10849. this.layerMask = 0x0FFFFFFF;
  10850. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  10851. // Camera rig members
  10852. this.cameraRigMode = Camera.RIG_MODE_NONE;
  10853. this._rigCameras = new Array();
  10854. // Cache
  10855. this._computedViewMatrix = BABYLON.Matrix.Identity();
  10856. this._projectionMatrix = new BABYLON.Matrix();
  10857. this._postProcesses = new Array();
  10858. this._postProcessesTakenIndices = [];
  10859. this._activeMeshes = new BABYLON.SmartArray(256);
  10860. this._globalPosition = BABYLON.Vector3.Zero();
  10861. scene.addCamera(this);
  10862. if (!scene.activeCamera) {
  10863. scene.activeCamera = this;
  10864. }
  10865. this.position = position;
  10866. }
  10867. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  10868. get: function () {
  10869. return Camera._PERSPECTIVE_CAMERA;
  10870. },
  10871. enumerable: true,
  10872. configurable: true
  10873. });
  10874. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10875. get: function () {
  10876. return Camera._ORTHOGRAPHIC_CAMERA;
  10877. },
  10878. enumerable: true,
  10879. configurable: true
  10880. });
  10881. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10882. get: function () {
  10883. return Camera._FOVMODE_VERTICAL_FIXED;
  10884. },
  10885. enumerable: true,
  10886. configurable: true
  10887. });
  10888. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10889. get: function () {
  10890. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10891. },
  10892. enumerable: true,
  10893. configurable: true
  10894. });
  10895. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10896. get: function () {
  10897. return Camera._RIG_MODE_NONE;
  10898. },
  10899. enumerable: true,
  10900. configurable: true
  10901. });
  10902. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10903. get: function () {
  10904. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10905. },
  10906. enumerable: true,
  10907. configurable: true
  10908. });
  10909. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10910. get: function () {
  10911. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10912. },
  10913. enumerable: true,
  10914. configurable: true
  10915. });
  10916. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10917. get: function () {
  10918. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10919. },
  10920. enumerable: true,
  10921. configurable: true
  10922. });
  10923. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10924. get: function () {
  10925. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10926. },
  10927. enumerable: true,
  10928. configurable: true
  10929. });
  10930. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10931. get: function () {
  10932. return Camera._RIG_MODE_VR;
  10933. },
  10934. enumerable: true,
  10935. configurable: true
  10936. });
  10937. /**
  10938. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10939. */
  10940. Camera.prototype.toString = function (fullDetails) {
  10941. var ret = "Name: " + this.name;
  10942. ret += ", type: " + this.getTypeName();
  10943. if (this.animations) {
  10944. for (var i = 0; i < this.animations.length; i++) {
  10945. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  10946. }
  10947. }
  10948. if (fullDetails) {
  10949. }
  10950. return ret;
  10951. };
  10952. Object.defineProperty(Camera.prototype, "globalPosition", {
  10953. get: function () {
  10954. return this._globalPosition;
  10955. },
  10956. enumerable: true,
  10957. configurable: true
  10958. });
  10959. Camera.prototype.getActiveMeshes = function () {
  10960. return this._activeMeshes;
  10961. };
  10962. Camera.prototype.isActiveMesh = function (mesh) {
  10963. return (this._activeMeshes.indexOf(mesh) !== -1);
  10964. };
  10965. //Cache
  10966. Camera.prototype._initCache = function () {
  10967. _super.prototype._initCache.call(this);
  10968. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10969. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10970. this._cache.mode = undefined;
  10971. this._cache.minZ = undefined;
  10972. this._cache.maxZ = undefined;
  10973. this._cache.fov = undefined;
  10974. this._cache.aspectRatio = undefined;
  10975. this._cache.orthoLeft = undefined;
  10976. this._cache.orthoRight = undefined;
  10977. this._cache.orthoBottom = undefined;
  10978. this._cache.orthoTop = undefined;
  10979. this._cache.renderWidth = undefined;
  10980. this._cache.renderHeight = undefined;
  10981. };
  10982. Camera.prototype._updateCache = function (ignoreParentClass) {
  10983. if (!ignoreParentClass) {
  10984. _super.prototype._updateCache.call(this);
  10985. }
  10986. var engine = this.getEngine();
  10987. this._cache.position.copyFrom(this.position);
  10988. this._cache.upVector.copyFrom(this.upVector);
  10989. this._cache.mode = this.mode;
  10990. this._cache.minZ = this.minZ;
  10991. this._cache.maxZ = this.maxZ;
  10992. this._cache.fov = this.fov;
  10993. this._cache.aspectRatio = engine.getAspectRatio(this);
  10994. this._cache.orthoLeft = this.orthoLeft;
  10995. this._cache.orthoRight = this.orthoRight;
  10996. this._cache.orthoBottom = this.orthoBottom;
  10997. this._cache.orthoTop = this.orthoTop;
  10998. this._cache.renderWidth = engine.getRenderWidth();
  10999. this._cache.renderHeight = engine.getRenderHeight();
  11000. };
  11001. Camera.prototype._updateFromScene = function () {
  11002. this.updateCache();
  11003. this._update();
  11004. };
  11005. // Synchronized
  11006. Camera.prototype._isSynchronized = function () {
  11007. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  11008. };
  11009. Camera.prototype._isSynchronizedViewMatrix = function () {
  11010. if (!_super.prototype._isSynchronized.call(this))
  11011. return false;
  11012. return this._cache.position.equals(this.position)
  11013. && this._cache.upVector.equals(this.upVector)
  11014. && this.isSynchronizedWithParent();
  11015. };
  11016. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  11017. var check = this._cache.mode === this.mode
  11018. && this._cache.minZ === this.minZ
  11019. && this._cache.maxZ === this.maxZ;
  11020. if (!check) {
  11021. return false;
  11022. }
  11023. var engine = this.getEngine();
  11024. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11025. check = this._cache.fov === this.fov
  11026. && this._cache.aspectRatio === engine.getAspectRatio(this);
  11027. }
  11028. else {
  11029. check = this._cache.orthoLeft === this.orthoLeft
  11030. && this._cache.orthoRight === this.orthoRight
  11031. && this._cache.orthoBottom === this.orthoBottom
  11032. && this._cache.orthoTop === this.orthoTop
  11033. && this._cache.renderWidth === engine.getRenderWidth()
  11034. && this._cache.renderHeight === engine.getRenderHeight();
  11035. }
  11036. return check;
  11037. };
  11038. // Controls
  11039. Camera.prototype.attachControl = function (element, noPreventDefault) {
  11040. };
  11041. Camera.prototype.detachControl = function (element) {
  11042. };
  11043. Camera.prototype._update = function () {
  11044. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  11045. this._updateRigCameras();
  11046. }
  11047. this._checkInputs();
  11048. };
  11049. Camera.prototype._checkInputs = function () {
  11050. };
  11051. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  11052. if (insertAt === void 0) { insertAt = null; }
  11053. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  11054. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  11055. return 0;
  11056. }
  11057. if (insertAt == null || insertAt < 0) {
  11058. this._postProcesses.push(postProcess);
  11059. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  11060. return this._postProcesses.length - 1;
  11061. }
  11062. var add = 0;
  11063. var i;
  11064. var start;
  11065. if (this._postProcesses[insertAt]) {
  11066. start = this._postProcesses.length - 1;
  11067. for (i = start; i >= insertAt + 1; --i) {
  11068. this._postProcesses[i + 1] = this._postProcesses[i];
  11069. }
  11070. add = 1;
  11071. }
  11072. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  11073. if (this._postProcessesTakenIndices[i] < insertAt) {
  11074. continue;
  11075. }
  11076. start = this._postProcessesTakenIndices.length - 1;
  11077. for (var j = start; j >= i; --j) {
  11078. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  11079. }
  11080. this._postProcessesTakenIndices[i] = insertAt;
  11081. break;
  11082. }
  11083. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  11084. this._postProcessesTakenIndices.push(insertAt);
  11085. }
  11086. var result = insertAt + add;
  11087. this._postProcesses[result] = postProcess;
  11088. return result;
  11089. };
  11090. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  11091. if (atIndices === void 0) { atIndices = null; }
  11092. var result = [];
  11093. var i;
  11094. var index;
  11095. if (!atIndices) {
  11096. var length = this._postProcesses.length;
  11097. for (i = 0; i < length; i++) {
  11098. if (this._postProcesses[i] !== postProcess) {
  11099. continue;
  11100. }
  11101. delete this._postProcesses[i];
  11102. index = this._postProcessesTakenIndices.indexOf(i);
  11103. this._postProcessesTakenIndices.splice(index, 1);
  11104. }
  11105. }
  11106. else {
  11107. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  11108. for (i = 0; i < atIndices.length; i++) {
  11109. var foundPostProcess = this._postProcesses[atIndices[i]];
  11110. if (foundPostProcess !== postProcess) {
  11111. result.push(i);
  11112. continue;
  11113. }
  11114. delete this._postProcesses[atIndices[i]];
  11115. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  11116. this._postProcessesTakenIndices.splice(index, 1);
  11117. }
  11118. }
  11119. return result;
  11120. };
  11121. Camera.prototype.getWorldMatrix = function () {
  11122. if (!this._worldMatrix) {
  11123. this._worldMatrix = BABYLON.Matrix.Identity();
  11124. }
  11125. var viewMatrix = this.getViewMatrix();
  11126. viewMatrix.invertToRef(this._worldMatrix);
  11127. return this._worldMatrix;
  11128. };
  11129. Camera.prototype._getViewMatrix = function () {
  11130. return BABYLON.Matrix.Identity();
  11131. };
  11132. Camera.prototype.getViewMatrix = function (force) {
  11133. this._computedViewMatrix = this._computeViewMatrix(force);
  11134. if (!force && this._isSynchronizedViewMatrix()) {
  11135. return this._computedViewMatrix;
  11136. }
  11137. if (!this.parent || !this.parent.getWorldMatrix) {
  11138. this._globalPosition.copyFrom(this.position);
  11139. }
  11140. else {
  11141. if (!this._worldMatrix) {
  11142. this._worldMatrix = BABYLON.Matrix.Identity();
  11143. }
  11144. this._computedViewMatrix.invertToRef(this._worldMatrix);
  11145. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  11146. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  11147. this._computedViewMatrix.invert();
  11148. this._markSyncedWithParent();
  11149. }
  11150. this._currentRenderId = this.getScene().getRenderId();
  11151. return this._computedViewMatrix;
  11152. };
  11153. Camera.prototype._computeViewMatrix = function (force) {
  11154. if (!force && this._isSynchronizedViewMatrix()) {
  11155. return this._computedViewMatrix;
  11156. }
  11157. this._computedViewMatrix = this._getViewMatrix();
  11158. this._currentRenderId = this.getScene().getRenderId();
  11159. return this._computedViewMatrix;
  11160. };
  11161. Camera.prototype.getProjectionMatrix = function (force) {
  11162. if (!force && this._isSynchronizedProjectionMatrix()) {
  11163. return this._projectionMatrix;
  11164. }
  11165. var engine = this.getEngine();
  11166. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11167. if (this.minZ <= 0) {
  11168. this.minZ = 0.1;
  11169. }
  11170. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  11171. return this._projectionMatrix;
  11172. }
  11173. var halfWidth = engine.getRenderWidth() / 2.0;
  11174. var halfHeight = engine.getRenderHeight() / 2.0;
  11175. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  11176. return this._projectionMatrix;
  11177. };
  11178. Camera.prototype.dispose = function () {
  11179. // Animations
  11180. this.getScene().stopAnimation(this);
  11181. // Remove from scene
  11182. this.getScene().removeCamera(this);
  11183. while (this._rigCameras.length > 0) {
  11184. this._rigCameras.pop().dispose();
  11185. }
  11186. // Postprocesses
  11187. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  11188. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  11189. }
  11190. _super.prototype.dispose.call(this);
  11191. };
  11192. // ---- Camera rigs section ----
  11193. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  11194. while (this._rigCameras.length > 0) {
  11195. this._rigCameras.pop().dispose();
  11196. }
  11197. this.cameraRigMode = mode;
  11198. this._cameraRigParams = {};
  11199. switch (this.cameraRigMode) {
  11200. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11201. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11202. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11203. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11204. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  11205. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  11206. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  11207. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  11208. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  11209. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  11210. break;
  11211. }
  11212. var postProcesses = new Array();
  11213. switch (this.cameraRigMode) {
  11214. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11215. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  11216. this._rigCameras[0].isIntermediate = true;
  11217. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  11218. postProcesses[1].onApply = function (effect) {
  11219. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  11220. };
  11221. break;
  11222. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11223. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11224. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11225. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  11226. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  11227. var secondCamIndex = 1 - firstCamIndex;
  11228. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  11229. this._rigCameras[firstCamIndex].isIntermediate = true;
  11230. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  11231. break;
  11232. case Camera.RIG_MODE_VR:
  11233. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  11234. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  11235. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  11236. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  11237. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  11238. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  11239. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  11240. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11241. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  11242. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  11243. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  11244. if (metrics.compensateDistortion) {
  11245. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  11246. }
  11247. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  11248. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  11249. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11250. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  11251. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  11252. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  11253. if (metrics.compensateDistortion) {
  11254. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  11255. }
  11256. break;
  11257. }
  11258. this._update();
  11259. };
  11260. Camera.prototype._getVRProjectionMatrix = function () {
  11261. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  11262. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  11263. return this._projectionMatrix;
  11264. };
  11265. Camera.prototype.setCameraRigParameter = function (name, value) {
  11266. this._cameraRigParams[name] = value;
  11267. //provisionnally:
  11268. if (name === "interaxialDistance") {
  11269. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  11270. }
  11271. };
  11272. /**
  11273. * May needs to be overridden by children so sub has required properties to be copied
  11274. */
  11275. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  11276. return null;
  11277. };
  11278. /**
  11279. * May needs to be overridden by children
  11280. */
  11281. Camera.prototype._updateRigCameras = function () {
  11282. for (var i = 0; i < this._rigCameras.length; i++) {
  11283. this._rigCameras[i].minZ = this.minZ;
  11284. this._rigCameras[i].maxZ = this.maxZ;
  11285. this._rigCameras[i].fov = this.fov;
  11286. }
  11287. // only update viewport when ANAGLYPH
  11288. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  11289. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  11290. }
  11291. };
  11292. Camera.prototype._setupInputs = function () {
  11293. };
  11294. Camera.prototype.serialize = function () {
  11295. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11296. // Type
  11297. serializationObject.type = this.getTypeName();
  11298. // Parent
  11299. if (this.parent) {
  11300. serializationObject.parentId = this.parent.id;
  11301. }
  11302. if (this.inputs) {
  11303. this.inputs.serialize(serializationObject);
  11304. }
  11305. // Animations
  11306. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11307. serializationObject.ranges = this.serializeAnimationRanges();
  11308. return serializationObject;
  11309. };
  11310. Camera.prototype.getTypeName = function () {
  11311. return "Camera";
  11312. };
  11313. Camera.prototype.clone = function (name) {
  11314. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  11315. };
  11316. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  11317. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  11318. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  11319. switch (type) {
  11320. case "ArcRotateCamera":
  11321. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  11322. case "DeviceOrientationCamera":
  11323. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  11324. case "FollowCamera":
  11325. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  11326. case "ArcFollowCamera":
  11327. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  11328. case "GamepadCamera":
  11329. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  11330. case "TouchCamera":
  11331. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  11332. case "VirtualJoysticksCamera":
  11333. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  11334. case "WebVRFreeCamera":
  11335. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11336. case "VRDeviceOrientationFreeCamera":
  11337. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11338. case "AnaglyphArcRotateCamera":
  11339. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11340. case "AnaglyphFreeCamera":
  11341. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11342. case "AnaglyphGamepadCamera":
  11343. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11344. case "AnaglyphUniversalCamera":
  11345. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11346. case "StereoscopicArcRotateCamera":
  11347. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11348. case "StereoscopicFreeCamera":
  11349. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11350. case "StereoscopicGamepadCamera":
  11351. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11352. case "StereoscopicUniversalCamera":
  11353. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11354. case "FreeCamera":
  11355. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11356. default:
  11357. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11358. }
  11359. };
  11360. Camera.Parse = function (parsedCamera, scene) {
  11361. var type = parsedCamera.type;
  11362. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  11363. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  11364. // Parent
  11365. if (parsedCamera.parentId) {
  11366. camera._waitingParentId = parsedCamera.parentId;
  11367. }
  11368. //If camera has an input manager, let it parse inputs settings
  11369. if (camera.inputs) {
  11370. camera.inputs.parse(parsedCamera);
  11371. camera._setupInputs();
  11372. }
  11373. // Target
  11374. if (parsedCamera.target) {
  11375. if (camera.setTarget) {
  11376. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  11377. }
  11378. }
  11379. // Apply 3d rig, when found
  11380. if (parsedCamera.cameraRigMode) {
  11381. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  11382. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  11383. }
  11384. // Animations
  11385. if (parsedCamera.animations) {
  11386. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  11387. var parsedAnimation = parsedCamera.animations[animationIndex];
  11388. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11389. }
  11390. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  11391. }
  11392. if (parsedCamera.autoAnimate) {
  11393. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  11394. }
  11395. return camera;
  11396. };
  11397. // Statics
  11398. Camera._PERSPECTIVE_CAMERA = 0;
  11399. Camera._ORTHOGRAPHIC_CAMERA = 1;
  11400. Camera._FOVMODE_VERTICAL_FIXED = 0;
  11401. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  11402. Camera._RIG_MODE_NONE = 0;
  11403. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  11404. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  11405. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  11406. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  11407. Camera._RIG_MODE_VR = 20;
  11408. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  11409. __decorate([
  11410. BABYLON.serializeAsVector3()
  11411. ], Camera.prototype, "position", void 0);
  11412. __decorate([
  11413. BABYLON.serializeAsVector3()
  11414. ], Camera.prototype, "upVector", void 0);
  11415. __decorate([
  11416. BABYLON.serialize()
  11417. ], Camera.prototype, "orthoLeft", void 0);
  11418. __decorate([
  11419. BABYLON.serialize()
  11420. ], Camera.prototype, "orthoRight", void 0);
  11421. __decorate([
  11422. BABYLON.serialize()
  11423. ], Camera.prototype, "orthoBottom", void 0);
  11424. __decorate([
  11425. BABYLON.serialize()
  11426. ], Camera.prototype, "orthoTop", void 0);
  11427. __decorate([
  11428. BABYLON.serialize()
  11429. ], Camera.prototype, "fov", void 0);
  11430. __decorate([
  11431. BABYLON.serialize()
  11432. ], Camera.prototype, "minZ", void 0);
  11433. __decorate([
  11434. BABYLON.serialize()
  11435. ], Camera.prototype, "maxZ", void 0);
  11436. __decorate([
  11437. BABYLON.serialize()
  11438. ], Camera.prototype, "inertia", void 0);
  11439. __decorate([
  11440. BABYLON.serialize()
  11441. ], Camera.prototype, "mode", void 0);
  11442. __decorate([
  11443. BABYLON.serialize()
  11444. ], Camera.prototype, "layerMask", void 0);
  11445. __decorate([
  11446. BABYLON.serialize()
  11447. ], Camera.prototype, "fovMode", void 0);
  11448. __decorate([
  11449. BABYLON.serialize()
  11450. ], Camera.prototype, "cameraRigMode", void 0);
  11451. __decorate([
  11452. BABYLON.serialize()
  11453. ], Camera.prototype, "interaxialDistance", void 0);
  11454. __decorate([
  11455. BABYLON.serialize()
  11456. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  11457. return Camera;
  11458. })(BABYLON.Node);
  11459. BABYLON.Camera = Camera;
  11460. })(BABYLON || (BABYLON = {}));
  11461. var BABYLON;
  11462. (function (BABYLON) {
  11463. BABYLON.CameraInputTypes = {};
  11464. var CameraInputsManager = (function () {
  11465. function CameraInputsManager(camera) {
  11466. this.attached = {};
  11467. this.camera = camera;
  11468. this.checkInputs = function () { };
  11469. }
  11470. CameraInputsManager.prototype.add = function (input) {
  11471. var type = input.getSimpleName();
  11472. if (this.attached[type]) {
  11473. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  11474. return;
  11475. }
  11476. this.attached[type] = input;
  11477. input.camera = this.camera;
  11478. //for checkInputs, we are dynamically creating a function
  11479. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  11480. if (input.checkInputs) {
  11481. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11482. }
  11483. if (this.attachedElement) {
  11484. input.attachControl(this.attachedElement);
  11485. }
  11486. };
  11487. CameraInputsManager.prototype.remove = function (inputToRemove) {
  11488. for (var cam in this.attached) {
  11489. var input = this.attached[cam];
  11490. if (input === inputToRemove) {
  11491. input.detachControl(this.attachedElement);
  11492. delete this.attached[cam];
  11493. this.rebuildInputCheck();
  11494. }
  11495. }
  11496. };
  11497. CameraInputsManager.prototype.removeByType = function (inputType) {
  11498. for (var cam in this.attached) {
  11499. var input = this.attached[cam];
  11500. if (input.getTypeName() === inputType) {
  11501. input.detachControl(this.attachedElement);
  11502. delete this.attached[cam];
  11503. this.rebuildInputCheck();
  11504. }
  11505. }
  11506. };
  11507. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  11508. var current = this.checkInputs;
  11509. return function () {
  11510. current();
  11511. fn();
  11512. };
  11513. };
  11514. CameraInputsManager.prototype.attachInput = function (input) {
  11515. input.attachControl(this.attachedElement, this.noPreventDefault);
  11516. };
  11517. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  11518. if (this.attachedElement) {
  11519. return;
  11520. }
  11521. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  11522. this.attachedElement = element;
  11523. this.noPreventDefault = noPreventDefault;
  11524. for (var cam in this.attached) {
  11525. var input = this.attached[cam];
  11526. this.attached[cam].attachControl(element, noPreventDefault);
  11527. }
  11528. };
  11529. CameraInputsManager.prototype.detachElement = function (element) {
  11530. if (this.attachedElement !== element) {
  11531. return;
  11532. }
  11533. for (var cam in this.attached) {
  11534. var input = this.attached[cam];
  11535. this.attached[cam].detachControl(element);
  11536. }
  11537. this.attachedElement = null;
  11538. };
  11539. CameraInputsManager.prototype.rebuildInputCheck = function () {
  11540. this.checkInputs = function () { };
  11541. for (var cam in this.attached) {
  11542. var input = this.attached[cam];
  11543. if (input.checkInputs) {
  11544. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11545. }
  11546. }
  11547. };
  11548. CameraInputsManager.prototype.clear = function () {
  11549. if (this.attachedElement) {
  11550. this.detachElement(this.attachedElement);
  11551. }
  11552. this.attached = {};
  11553. this.attachedElement = null;
  11554. this.checkInputs = function () { };
  11555. };
  11556. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  11557. var inputs = {};
  11558. for (var cam in this.attached) {
  11559. var input = this.attached[cam];
  11560. var res = BABYLON.SerializationHelper.Serialize(input);
  11561. inputs[input.getTypeName()] = res;
  11562. }
  11563. serializedCamera.inputsmgr = inputs;
  11564. };
  11565. CameraInputsManager.prototype.parse = function (parsedCamera) {
  11566. var parsedInputs = parsedCamera.inputsmgr;
  11567. if (parsedInputs) {
  11568. this.clear();
  11569. for (var n in parsedInputs) {
  11570. var construct = BABYLON.CameraInputTypes[n];
  11571. if (construct) {
  11572. var parsedinput = parsedInputs[n];
  11573. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  11574. this.add(input);
  11575. }
  11576. }
  11577. }
  11578. else {
  11579. //2016-03-08 this part is for managing backward compatibility
  11580. for (var n in this.attached) {
  11581. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  11582. if (construct) {
  11583. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  11584. this.remove(this.attached[n]);
  11585. this.add(input);
  11586. }
  11587. }
  11588. }
  11589. };
  11590. return CameraInputsManager;
  11591. })();
  11592. BABYLON.CameraInputsManager = CameraInputsManager;
  11593. })(BABYLON || (BABYLON = {}));
  11594. var BABYLON;
  11595. (function (BABYLON) {
  11596. var FreeCameraMouseInput = (function () {
  11597. function FreeCameraMouseInput(touchEnabled) {
  11598. if (touchEnabled === void 0) { touchEnabled = true; }
  11599. this.touchEnabled = touchEnabled;
  11600. this.angularSensibility = 2000.0;
  11601. }
  11602. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  11603. var _this = this;
  11604. if (!this._pointerInput) {
  11605. var camera = this.camera;
  11606. var engine = this.camera.getEngine();
  11607. this._pointerInput = function (p, s) {
  11608. var evt = p.event;
  11609. if (!_this.touchEnabled && evt.pointerType === "touch") {
  11610. return;
  11611. }
  11612. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  11613. try {
  11614. evt.srcElement.setPointerCapture(evt.pointerId);
  11615. }
  11616. catch (e) {
  11617. }
  11618. _this.previousPosition = {
  11619. x: evt.clientX,
  11620. y: evt.clientY
  11621. };
  11622. if (!noPreventDefault) {
  11623. evt.preventDefault();
  11624. }
  11625. }
  11626. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  11627. try {
  11628. evt.srcElement.releasePointerCapture(evt.pointerId);
  11629. }
  11630. catch (e) {
  11631. }
  11632. _this.previousPosition = null;
  11633. if (!noPreventDefault) {
  11634. evt.preventDefault();
  11635. }
  11636. }
  11637. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  11638. if (!_this.previousPosition && !engine.isPointerLock) {
  11639. return;
  11640. }
  11641. var offsetX;
  11642. var offsetY;
  11643. if (!engine.isPointerLock) {
  11644. offsetX = evt.clientX - _this.previousPosition.x;
  11645. offsetY = evt.clientY - _this.previousPosition.y;
  11646. }
  11647. else {
  11648. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11649. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11650. }
  11651. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  11652. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  11653. _this.previousPosition = {
  11654. x: evt.clientX,
  11655. y: evt.clientY
  11656. };
  11657. if (!noPreventDefault) {
  11658. evt.preventDefault();
  11659. }
  11660. }
  11661. };
  11662. }
  11663. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  11664. };
  11665. FreeCameraMouseInput.prototype.detachControl = function (element) {
  11666. if (this._observer && element) {
  11667. this.camera.getScene().onPointerObservable.remove(this._observer);
  11668. this._observer = null;
  11669. this.previousPosition = null;
  11670. }
  11671. };
  11672. FreeCameraMouseInput.prototype.getTypeName = function () {
  11673. return "FreeCameraMouseInput";
  11674. };
  11675. FreeCameraMouseInput.prototype.getSimpleName = function () {
  11676. return "mouse";
  11677. };
  11678. __decorate([
  11679. BABYLON.serialize()
  11680. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  11681. return FreeCameraMouseInput;
  11682. })();
  11683. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  11684. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  11685. })(BABYLON || (BABYLON = {}));
  11686. var BABYLON;
  11687. (function (BABYLON) {
  11688. var FreeCameraKeyboardMoveInput = (function () {
  11689. function FreeCameraKeyboardMoveInput() {
  11690. this._keys = [];
  11691. this.keysUp = [38];
  11692. this.keysDown = [40];
  11693. this.keysLeft = [37];
  11694. this.keysRight = [39];
  11695. }
  11696. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  11697. var _this = this;
  11698. if (!this._onKeyDown) {
  11699. this._onKeyDown = function (evt) {
  11700. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11701. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11702. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11703. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11704. var index = _this._keys.indexOf(evt.keyCode);
  11705. if (index === -1) {
  11706. _this._keys.push(evt.keyCode);
  11707. }
  11708. if (!noPreventDefault) {
  11709. evt.preventDefault();
  11710. }
  11711. }
  11712. };
  11713. this._onKeyUp = function (evt) {
  11714. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11715. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11716. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11717. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11718. var index = _this._keys.indexOf(evt.keyCode);
  11719. if (index >= 0) {
  11720. _this._keys.splice(index, 1);
  11721. }
  11722. if (!noPreventDefault) {
  11723. evt.preventDefault();
  11724. }
  11725. }
  11726. };
  11727. BABYLON.Tools.RegisterTopRootEvents([
  11728. { name: "keydown", handler: this._onKeyDown },
  11729. { name: "keyup", handler: this._onKeyUp },
  11730. { name: "blur", handler: this._onLostFocus }
  11731. ]);
  11732. }
  11733. };
  11734. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  11735. if (this._onKeyDown) {
  11736. BABYLON.Tools.UnregisterTopRootEvents([
  11737. { name: "keydown", handler: this._onKeyDown },
  11738. { name: "keyup", handler: this._onKeyUp },
  11739. { name: "blur", handler: this._onLostFocus }
  11740. ]);
  11741. this._keys = [];
  11742. this._onKeyDown = null;
  11743. this._onKeyUp = null;
  11744. }
  11745. };
  11746. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  11747. if (this._onKeyDown) {
  11748. var camera = this.camera;
  11749. // Keyboard
  11750. for (var index = 0; index < this._keys.length; index++) {
  11751. var keyCode = this._keys[index];
  11752. var speed = camera._computeLocalCameraSpeed();
  11753. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11754. camera._localDirection.copyFromFloats(-speed, 0, 0);
  11755. }
  11756. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11757. camera._localDirection.copyFromFloats(0, 0, speed);
  11758. }
  11759. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11760. camera._localDirection.copyFromFloats(speed, 0, 0);
  11761. }
  11762. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11763. camera._localDirection.copyFromFloats(0, 0, -speed);
  11764. }
  11765. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  11766. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  11767. camera.cameraDirection.addInPlace(camera._transformedDirection);
  11768. }
  11769. }
  11770. };
  11771. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  11772. return "FreeCameraKeyboardMoveInput";
  11773. };
  11774. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  11775. this._keys = [];
  11776. };
  11777. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  11778. return "keyboard";
  11779. };
  11780. __decorate([
  11781. BABYLON.serialize()
  11782. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  11783. __decorate([
  11784. BABYLON.serialize()
  11785. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  11786. __decorate([
  11787. BABYLON.serialize()
  11788. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  11789. __decorate([
  11790. BABYLON.serialize()
  11791. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  11792. return FreeCameraKeyboardMoveInput;
  11793. })();
  11794. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  11795. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  11796. })(BABYLON || (BABYLON = {}));
  11797. var BABYLON;
  11798. (function (BABYLON) {
  11799. var FreeCameraTouchInput = (function () {
  11800. function FreeCameraTouchInput() {
  11801. this._offsetX = null;
  11802. this._offsetY = null;
  11803. this._pointerCount = 0;
  11804. this._pointerPressed = [];
  11805. this.touchAngularSensibility = 200000.0;
  11806. this.touchMoveSensibility = 250.0;
  11807. }
  11808. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  11809. var _this = this;
  11810. var previousPosition;
  11811. if (this._pointerInput === undefined) {
  11812. this._onLostFocus = function (evt) {
  11813. _this._offsetX = null;
  11814. _this._offsetY = null;
  11815. };
  11816. this._pointerInput = function (p, s) {
  11817. var evt = p.event;
  11818. if (evt.pointerType === "mouse") {
  11819. return;
  11820. }
  11821. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  11822. if (!noPreventDefault) {
  11823. evt.preventDefault();
  11824. }
  11825. _this._pointerPressed.push(evt.pointerId);
  11826. if (_this._pointerPressed.length !== 1) {
  11827. return;
  11828. }
  11829. previousPosition = {
  11830. x: evt.clientX,
  11831. y: evt.clientY
  11832. };
  11833. }
  11834. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  11835. if (!noPreventDefault) {
  11836. evt.preventDefault();
  11837. }
  11838. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11839. if (index === -1) {
  11840. return;
  11841. }
  11842. _this._pointerPressed.splice(index, 1);
  11843. if (index != 0) {
  11844. return;
  11845. }
  11846. previousPosition = null;
  11847. _this._offsetX = null;
  11848. _this._offsetY = null;
  11849. }
  11850. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  11851. if (!noPreventDefault) {
  11852. evt.preventDefault();
  11853. }
  11854. if (!previousPosition) {
  11855. return;
  11856. }
  11857. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11858. if (index != 0) {
  11859. return;
  11860. }
  11861. _this._offsetX = evt.clientX - previousPosition.x;
  11862. _this._offsetY = -(evt.clientY - previousPosition.y);
  11863. }
  11864. };
  11865. }
  11866. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  11867. element.addEventListener("blur", this._onLostFocus);
  11868. };
  11869. FreeCameraTouchInput.prototype.detachControl = function (element) {
  11870. if (this._pointerInput && element) {
  11871. this.camera.getScene().onPointerObservable.remove(this._observer);
  11872. this._observer = null;
  11873. element.removeEventListener("blur", this._onLostFocus);
  11874. this._onLostFocus = null;
  11875. this._pointerPressed = [];
  11876. this._offsetX = null;
  11877. this._offsetY = null;
  11878. this._pointerCount = 0;
  11879. }
  11880. };
  11881. FreeCameraTouchInput.prototype.checkInputs = function () {
  11882. if (this._offsetX) {
  11883. var camera = this.camera;
  11884. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11885. if (this._pointerPressed.length > 1) {
  11886. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11887. }
  11888. else {
  11889. var speed = camera._computeLocalCameraSpeed();
  11890. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11891. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  11892. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  11893. }
  11894. }
  11895. };
  11896. FreeCameraTouchInput.prototype.getTypeName = function () {
  11897. return "FreeCameraTouchInput";
  11898. };
  11899. FreeCameraTouchInput.prototype.getSimpleName = function () {
  11900. return "touch";
  11901. };
  11902. __decorate([
  11903. BABYLON.serialize()
  11904. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  11905. __decorate([
  11906. BABYLON.serialize()
  11907. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  11908. return FreeCameraTouchInput;
  11909. })();
  11910. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  11911. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  11912. })(BABYLON || (BABYLON = {}));
  11913. var BABYLON;
  11914. (function (BABYLON) {
  11915. var FreeCameraDeviceOrientationInput = (function () {
  11916. function FreeCameraDeviceOrientationInput() {
  11917. this._offsetX = null;
  11918. this._offsetY = null;
  11919. this._orientationGamma = 0;
  11920. this._orientationBeta = 0;
  11921. this._initialOrientationGamma = 0;
  11922. this._initialOrientationBeta = 0;
  11923. this.angularSensibility = 10000.0;
  11924. this.moveSensibility = 50.0;
  11925. this._resetOrientationGamma = this.resetOrientationGamma.bind(this);
  11926. this._orientationChanged = this.orientationChanged.bind(this);
  11927. }
  11928. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  11929. window.addEventListener("resize", this._resetOrientationGamma, false);
  11930. window.addEventListener("deviceorientation", this._orientationChanged);
  11931. };
  11932. FreeCameraDeviceOrientationInput.prototype.resetOrientationGamma = function () {
  11933. this._initialOrientationGamma = null;
  11934. };
  11935. FreeCameraDeviceOrientationInput.prototype.orientationChanged = function (evt) {
  11936. if (!this._initialOrientationGamma) {
  11937. this._initialOrientationGamma = evt.gamma;
  11938. this._initialOrientationBeta = evt.beta;
  11939. }
  11940. this._orientationGamma = evt.gamma;
  11941. this._orientationBeta = evt.beta;
  11942. this._offsetY = (this._initialOrientationBeta - this._orientationBeta);
  11943. this._offsetX = (this._initialOrientationGamma - this._orientationGamma);
  11944. };
  11945. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  11946. window.removeEventListener("resize", this._resetOrientationGamma);
  11947. window.removeEventListener("deviceorientation", this._orientationChanged);
  11948. this._orientationGamma = 0;
  11949. this._orientationBeta = 0;
  11950. this._initialOrientationGamma = 0;
  11951. this._initialOrientationBeta = 0;
  11952. this._offsetX = null;
  11953. this._offsetY = null;
  11954. };
  11955. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  11956. if (!this._offsetX) {
  11957. return;
  11958. }
  11959. var camera = this.camera;
  11960. camera.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11961. var speed = camera._computeLocalCameraSpeed();
  11962. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11963. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  11964. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  11965. };
  11966. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  11967. return "FreeCameraDeviceOrientationInput";
  11968. };
  11969. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  11970. return "deviceOrientation";
  11971. };
  11972. __decorate([
  11973. BABYLON.serialize()
  11974. ], FreeCameraDeviceOrientationInput.prototype, "angularSensibility", void 0);
  11975. __decorate([
  11976. BABYLON.serialize()
  11977. ], FreeCameraDeviceOrientationInput.prototype, "moveSensibility", void 0);
  11978. return FreeCameraDeviceOrientationInput;
  11979. })();
  11980. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  11981. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  11982. })(BABYLON || (BABYLON = {}));
  11983. var BABYLON;
  11984. (function (BABYLON) {
  11985. var FreeCameraVRDeviceOrientationInput = (function () {
  11986. function FreeCameraVRDeviceOrientationInput() {
  11987. this.alphaCorrection = 1;
  11988. this.betaCorrection = 1;
  11989. this.gammaCorrection = 1;
  11990. this._alpha = 0;
  11991. this._beta = 0;
  11992. this._gamma = 0;
  11993. this._dirty = false;
  11994. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  11995. }
  11996. FreeCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  11997. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  11998. };
  11999. FreeCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  12000. var camera = this.camera;
  12001. this._alpha = +evt.alpha | 0;
  12002. this._beta = +evt.beta | 0;
  12003. this._gamma = +evt.gamma | 0;
  12004. this._dirty = true;
  12005. };
  12006. FreeCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  12007. if (this._dirty) {
  12008. this._dirty = false;
  12009. var rotationX = this._gamma;
  12010. if (rotationX < 0) {
  12011. rotationX = 90 + rotationX;
  12012. }
  12013. else {
  12014. // Incline it in the correct angle.
  12015. rotationX = 270 - rotationX;
  12016. }
  12017. this.camera.rotation.x = this.gammaCorrection * rotationX / 180.0 * Math.PI;
  12018. this.camera.rotation.y = this.alphaCorrection * -this._alpha / 180.0 * Math.PI;
  12019. this.camera.rotation.z = this.betaCorrection * this._beta / 180.0 * Math.PI;
  12020. }
  12021. };
  12022. FreeCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  12023. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  12024. };
  12025. FreeCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  12026. return "FreeCameraVRDeviceOrientationInput";
  12027. };
  12028. FreeCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  12029. return "VRDeviceOrientation";
  12030. };
  12031. return FreeCameraVRDeviceOrientationInput;
  12032. })();
  12033. BABYLON.FreeCameraVRDeviceOrientationInput = FreeCameraVRDeviceOrientationInput;
  12034. BABYLON.CameraInputTypes["FreeCameraVRDeviceOrientationInput"] = FreeCameraVRDeviceOrientationInput;
  12035. })(BABYLON || (BABYLON = {}));
  12036. var BABYLON;
  12037. (function (BABYLON) {
  12038. var FreeCameraGamepadInput = (function () {
  12039. function FreeCameraGamepadInput() {
  12040. this.gamepadAngularSensibility = 200;
  12041. this.gamepadMoveSensibility = 40;
  12042. }
  12043. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12044. var _this = this;
  12045. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12046. };
  12047. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  12048. if (this._gamepads) {
  12049. this._gamepads.dispose();
  12050. }
  12051. this.gamepad = null;
  12052. };
  12053. FreeCameraGamepadInput.prototype.checkInputs = function () {
  12054. if (this.gamepad) {
  12055. var camera = this.camera;
  12056. var LSValues = this.gamepad.leftStick;
  12057. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  12058. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12059. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  12060. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  12061. var RSValues = this.gamepad.rightStick;
  12062. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  12063. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  12064. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  12065. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  12066. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  12067. var speed = camera._computeLocalCameraSpeed() * 50.0;
  12068. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  12069. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  12070. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  12071. }
  12072. };
  12073. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12074. // Only the first gamepad can control the camera
  12075. if (gamepad.index === 0) {
  12076. this.gamepad = gamepad;
  12077. }
  12078. };
  12079. FreeCameraGamepadInput.prototype.getTypeName = function () {
  12080. return "FreeCameraGamepadInput";
  12081. };
  12082. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  12083. return "gamepad";
  12084. };
  12085. __decorate([
  12086. BABYLON.serialize()
  12087. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  12088. __decorate([
  12089. BABYLON.serialize()
  12090. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12091. return FreeCameraGamepadInput;
  12092. })();
  12093. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  12094. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  12095. })(BABYLON || (BABYLON = {}));
  12096. var BABYLON;
  12097. (function (BABYLON) {
  12098. var FreeCameraVirtualJoystickInput = (function () {
  12099. function FreeCameraVirtualJoystickInput() {
  12100. }
  12101. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  12102. return this._leftjoystick;
  12103. };
  12104. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  12105. return this._rightjoystick;
  12106. };
  12107. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  12108. if (this._leftjoystick) {
  12109. var camera = this.camera;
  12110. var speed = camera._computeLocalCameraSpeed() * 50;
  12111. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  12112. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  12113. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  12114. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  12115. if (!this._leftjoystick.pressed) {
  12116. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  12117. }
  12118. if (!this._rightjoystick.pressed) {
  12119. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  12120. }
  12121. }
  12122. };
  12123. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  12124. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  12125. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  12126. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  12127. this._leftjoystick.setJoystickSensibility(0.15);
  12128. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  12129. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  12130. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  12131. this._rightjoystick.reverseUpDown = true;
  12132. this._rightjoystick.setJoystickSensibility(0.05);
  12133. this._rightjoystick.setJoystickColor("yellow");
  12134. };
  12135. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  12136. this._leftjoystick.releaseCanvas();
  12137. this._rightjoystick.releaseCanvas();
  12138. };
  12139. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  12140. return "FreeCameraVirtualJoystickInput";
  12141. };
  12142. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  12143. return "virtualJoystick";
  12144. };
  12145. return FreeCameraVirtualJoystickInput;
  12146. })();
  12147. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  12148. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  12149. })(BABYLON || (BABYLON = {}));
  12150. var BABYLON;
  12151. (function (BABYLON) {
  12152. var ArcRotateCameraKeyboardMoveInput = (function () {
  12153. function ArcRotateCameraKeyboardMoveInput() {
  12154. this._keys = [];
  12155. this.keysUp = [38];
  12156. this.keysDown = [40];
  12157. this.keysLeft = [37];
  12158. this.keysRight = [39];
  12159. }
  12160. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  12161. var _this = this;
  12162. this._onKeyDown = function (evt) {
  12163. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12164. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12165. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12166. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12167. var index = _this._keys.indexOf(evt.keyCode);
  12168. if (index === -1) {
  12169. _this._keys.push(evt.keyCode);
  12170. }
  12171. if (evt.preventDefault) {
  12172. if (!noPreventDefault) {
  12173. evt.preventDefault();
  12174. }
  12175. }
  12176. }
  12177. };
  12178. this._onKeyUp = function (evt) {
  12179. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12180. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12181. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12182. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12183. var index = _this._keys.indexOf(evt.keyCode);
  12184. if (index >= 0) {
  12185. _this._keys.splice(index, 1);
  12186. }
  12187. if (evt.preventDefault) {
  12188. if (!noPreventDefault) {
  12189. evt.preventDefault();
  12190. }
  12191. }
  12192. }
  12193. };
  12194. this._onLostFocus = function () {
  12195. _this._keys = [];
  12196. };
  12197. BABYLON.Tools.RegisterTopRootEvents([
  12198. { name: "keydown", handler: this._onKeyDown },
  12199. { name: "keyup", handler: this._onKeyUp },
  12200. { name: "blur", handler: this._onLostFocus }
  12201. ]);
  12202. };
  12203. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  12204. BABYLON.Tools.UnregisterTopRootEvents([
  12205. { name: "keydown", handler: this._onKeyDown },
  12206. { name: "keyup", handler: this._onKeyUp },
  12207. { name: "blur", handler: this._onLostFocus }
  12208. ]);
  12209. this._keys = [];
  12210. this._onKeyDown = null;
  12211. this._onKeyUp = null;
  12212. this._onLostFocus = null;
  12213. };
  12214. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  12215. if (this._onKeyDown) {
  12216. var camera = this.camera;
  12217. for (var index = 0; index < this._keys.length; index++) {
  12218. var keyCode = this._keys[index];
  12219. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12220. camera.inertialAlphaOffset -= 0.01;
  12221. }
  12222. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12223. camera.inertialBetaOffset -= 0.01;
  12224. }
  12225. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12226. camera.inertialAlphaOffset += 0.01;
  12227. }
  12228. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12229. camera.inertialBetaOffset += 0.01;
  12230. }
  12231. }
  12232. }
  12233. };
  12234. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  12235. return "ArcRotateCameraKeyboardMoveInput";
  12236. };
  12237. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  12238. return "keyboard";
  12239. };
  12240. __decorate([
  12241. BABYLON.serialize()
  12242. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  12243. __decorate([
  12244. BABYLON.serialize()
  12245. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  12246. __decorate([
  12247. BABYLON.serialize()
  12248. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  12249. __decorate([
  12250. BABYLON.serialize()
  12251. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  12252. return ArcRotateCameraKeyboardMoveInput;
  12253. })();
  12254. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  12255. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  12256. })(BABYLON || (BABYLON = {}));
  12257. var BABYLON;
  12258. (function (BABYLON) {
  12259. var ArcRotateCameraMouseWheelInput = (function () {
  12260. function ArcRotateCameraMouseWheelInput() {
  12261. this.wheelPrecision = 3.0;
  12262. }
  12263. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  12264. var _this = this;
  12265. this._wheel = function (p, s) {
  12266. //sanity check - this should be a PointerWheel event.
  12267. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  12268. return;
  12269. var event = p.event;
  12270. var delta = 0;
  12271. if (event.wheelDelta) {
  12272. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  12273. }
  12274. else if (event.detail) {
  12275. delta = -event.detail / _this.wheelPrecision;
  12276. }
  12277. if (delta)
  12278. _this.camera.inertialRadiusOffset += delta;
  12279. if (event.preventDefault) {
  12280. if (!noPreventDefault) {
  12281. event.preventDefault();
  12282. }
  12283. }
  12284. };
  12285. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  12286. };
  12287. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  12288. if (this._observer && element) {
  12289. this.camera.getScene().onPointerObservable.remove(this._observer);
  12290. this._observer = null;
  12291. this._wheel = null;
  12292. }
  12293. };
  12294. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  12295. return "ArcRotateCameraMouseWheelInput";
  12296. };
  12297. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  12298. return "mousewheel";
  12299. };
  12300. __decorate([
  12301. BABYLON.serialize()
  12302. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  12303. return ArcRotateCameraMouseWheelInput;
  12304. })();
  12305. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  12306. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  12307. })(BABYLON || (BABYLON = {}));
  12308. var BABYLON;
  12309. (function (BABYLON) {
  12310. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12311. var ArcRotateCameraPointersInput = (function () {
  12312. function ArcRotateCameraPointersInput() {
  12313. this.angularSensibilityX = 1000.0;
  12314. this.angularSensibilityY = 1000.0;
  12315. this.pinchPrecision = 6.0;
  12316. this.panningSensibility = 50.0;
  12317. this._isRightClick = false;
  12318. this._isCtrlPushed = false;
  12319. this.pinchInwards = true;
  12320. }
  12321. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  12322. var _this = this;
  12323. var engine = this.camera.getEngine();
  12324. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  12325. var pointers = new BABYLON.SmartCollection();
  12326. var previousPinchDistance = 0;
  12327. this._pointerInput = function (p, s) {
  12328. var evt = p.event;
  12329. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12330. try {
  12331. evt.srcElement.setPointerCapture(evt.pointerId);
  12332. }
  12333. catch (e) {
  12334. }
  12335. // Manage panning with right click
  12336. _this._isRightClick = evt.button === 2;
  12337. // manage pointers
  12338. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  12339. cacheSoloPointer = pointers.item(evt.pointerId);
  12340. if (!noPreventDefault) {
  12341. evt.preventDefault();
  12342. }
  12343. }
  12344. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12345. try {
  12346. evt.srcElement.releasePointerCapture(evt.pointerId);
  12347. }
  12348. catch (e) {
  12349. }
  12350. cacheSoloPointer = null;
  12351. previousPinchDistance = 0;
  12352. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  12353. //but emptying completly pointers collection is required to fix a bug on iPhone :
  12354. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  12355. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  12356. pointers.empty();
  12357. if (!noPreventDefault) {
  12358. evt.preventDefault();
  12359. }
  12360. }
  12361. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12362. if (!noPreventDefault) {
  12363. evt.preventDefault();
  12364. }
  12365. switch (pointers.count) {
  12366. case 1:
  12367. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && _this.camera._useCtrlForPanning) || (!_this.camera._useCtrlForPanning && _this._isRightClick))) {
  12368. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  12369. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  12370. }
  12371. else {
  12372. var offsetX = evt.clientX - cacheSoloPointer.x;
  12373. var offsetY = evt.clientY - cacheSoloPointer.y;
  12374. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12375. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12376. }
  12377. cacheSoloPointer.x = evt.clientX;
  12378. cacheSoloPointer.y = evt.clientY;
  12379. break;
  12380. case 2:
  12381. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  12382. pointers.item(evt.pointerId).x = evt.clientX;
  12383. pointers.item(evt.pointerId).y = evt.clientY;
  12384. var direction = _this.pinchInwards ? 1 : -1;
  12385. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  12386. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  12387. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  12388. if (previousPinchDistance === 0) {
  12389. previousPinchDistance = pinchSquaredDistance;
  12390. return;
  12391. }
  12392. if (pinchSquaredDistance !== previousPinchDistance) {
  12393. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  12394. previousPinchDistance = pinchSquaredDistance;
  12395. }
  12396. break;
  12397. default:
  12398. if (pointers.item(evt.pointerId)) {
  12399. pointers.item(evt.pointerId).x = evt.clientX;
  12400. pointers.item(evt.pointerId).y = evt.clientY;
  12401. }
  12402. }
  12403. }
  12404. };
  12405. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12406. this._onContextMenu = function (evt) {
  12407. evt.preventDefault();
  12408. };
  12409. if (!this.camera._useCtrlForPanning) {
  12410. element.addEventListener("contextmenu", this._onContextMenu, false);
  12411. }
  12412. this._onLostFocus = function () {
  12413. //this._keys = [];
  12414. pointers.empty();
  12415. previousPinchDistance = 0;
  12416. cacheSoloPointer = null;
  12417. };
  12418. this._onKeyDown = function (evt) {
  12419. _this._isCtrlPushed = evt.ctrlKey;
  12420. };
  12421. this._onKeyUp = function (evt) {
  12422. _this._isCtrlPushed = evt.ctrlKey;
  12423. };
  12424. this._onMouseMove = function (evt) {
  12425. if (!engine.isPointerLock) {
  12426. return;
  12427. }
  12428. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12429. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12430. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12431. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12432. if (!noPreventDefault) {
  12433. evt.preventDefault();
  12434. }
  12435. };
  12436. this._onGestureStart = function (e) {
  12437. if (window.MSGesture === undefined) {
  12438. return;
  12439. }
  12440. if (!_this._MSGestureHandler) {
  12441. _this._MSGestureHandler = new MSGesture();
  12442. _this._MSGestureHandler.target = element;
  12443. }
  12444. _this._MSGestureHandler.addPointer(e.pointerId);
  12445. };
  12446. this._onGesture = function (e) {
  12447. _this.camera.radius *= e.scale;
  12448. if (e.preventDefault) {
  12449. if (!noPreventDefault) {
  12450. e.stopPropagation();
  12451. e.preventDefault();
  12452. }
  12453. }
  12454. };
  12455. element.addEventListener("mousemove", this._onMouseMove, false);
  12456. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  12457. element.addEventListener("MSGestureChange", this._onGesture, false);
  12458. BABYLON.Tools.RegisterTopRootEvents([
  12459. { name: "keydown", handler: this._onKeyDown },
  12460. { name: "keyup", handler: this._onKeyUp },
  12461. { name: "blur", handler: this._onLostFocus }
  12462. ]);
  12463. };
  12464. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  12465. if (element && this._observer) {
  12466. this.camera.getScene().onPointerObservable.remove(this._observer);
  12467. this._observer = null;
  12468. element.removeEventListener("contextmenu", this._onContextMenu);
  12469. element.removeEventListener("mousemove", this._onMouseMove);
  12470. element.removeEventListener("MSPointerDown", this._onGestureStart);
  12471. element.removeEventListener("MSGestureChange", this._onGesture);
  12472. this._isRightClick = false;
  12473. this._isCtrlPushed = false;
  12474. this.pinchInwards = true;
  12475. this._onKeyDown = null;
  12476. this._onKeyUp = null;
  12477. this._onMouseMove = null;
  12478. this._onGestureStart = null;
  12479. this._onGesture = null;
  12480. this._MSGestureHandler = null;
  12481. this._onLostFocus = null;
  12482. this._onContextMenu = null;
  12483. }
  12484. BABYLON.Tools.UnregisterTopRootEvents([
  12485. { name: "keydown", handler: this._onKeyDown },
  12486. { name: "keyup", handler: this._onKeyUp },
  12487. { name: "blur", handler: this._onLostFocus }
  12488. ]);
  12489. };
  12490. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  12491. return "ArcRotateCameraPointersInput";
  12492. };
  12493. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  12494. return "pointers";
  12495. };
  12496. __decorate([
  12497. BABYLON.serialize()
  12498. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  12499. __decorate([
  12500. BABYLON.serialize()
  12501. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  12502. __decorate([
  12503. BABYLON.serialize()
  12504. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  12505. __decorate([
  12506. BABYLON.serialize()
  12507. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  12508. return ArcRotateCameraPointersInput;
  12509. })();
  12510. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  12511. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  12512. })(BABYLON || (BABYLON = {}));
  12513. var BABYLON;
  12514. (function (BABYLON) {
  12515. var ArcRotateCameraGamepadInput = (function () {
  12516. function ArcRotateCameraGamepadInput() {
  12517. this.gamepadRotationSensibility = 80;
  12518. this.gamepadMoveSensibility = 40;
  12519. }
  12520. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12521. var _this = this;
  12522. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12523. };
  12524. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  12525. if (this._gamepads) {
  12526. this._gamepads.dispose();
  12527. }
  12528. this.gamepad = null;
  12529. };
  12530. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  12531. if (this.gamepad) {
  12532. var camera = this.camera;
  12533. var RSValues = this.gamepad.rightStick;
  12534. if (RSValues.x != 0) {
  12535. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  12536. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  12537. camera.inertialAlphaOffset += normalizedRX;
  12538. }
  12539. }
  12540. if (RSValues.y != 0) {
  12541. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  12542. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  12543. camera.inertialBetaOffset += normalizedRY;
  12544. }
  12545. }
  12546. var LSValues = this.gamepad.leftStick;
  12547. if (LSValues.y != 0) {
  12548. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12549. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  12550. this.camera.inertialRadiusOffset -= normalizedLY;
  12551. }
  12552. }
  12553. }
  12554. };
  12555. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12556. // Only the first gamepad can control the camera
  12557. if (gamepad.index === 0) {
  12558. this.gamepad = gamepad;
  12559. }
  12560. };
  12561. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  12562. return "ArcRotateCameraGamepadInput";
  12563. };
  12564. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  12565. return "gamepad";
  12566. };
  12567. __decorate([
  12568. BABYLON.serialize()
  12569. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  12570. __decorate([
  12571. BABYLON.serialize()
  12572. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12573. return ArcRotateCameraGamepadInput;
  12574. })();
  12575. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  12576. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  12577. })(BABYLON || (BABYLON = {}));
  12578. var BABYLON;
  12579. (function (BABYLON) {
  12580. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  12581. function ArcRotateCameraVRDeviceOrientationInput() {
  12582. this.alphaCorrection = 1;
  12583. this.betaCorrection = 1;
  12584. this.gammaCorrection = 1;
  12585. this._alpha = 0;
  12586. this._beta = 0;
  12587. this._gamma = 0;
  12588. this._dirty = false;
  12589. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  12590. }
  12591. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12592. this.camera.attachControl(element, noPreventDefault);
  12593. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  12594. };
  12595. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  12596. var camera = this.camera;
  12597. this._alpha = +evt.alpha | 0;
  12598. this._beta = +evt.beta | 0;
  12599. this._gamma = +evt.gamma | 0;
  12600. this._dirty = true;
  12601. };
  12602. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  12603. if (this._dirty) {
  12604. this._dirty = false;
  12605. if (this._gamma < 0) {
  12606. this._gamma = 180 + this._gamma;
  12607. }
  12608. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  12609. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  12610. }
  12611. };
  12612. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  12613. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  12614. };
  12615. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  12616. return "ArcRotateCameraVRDeviceOrientationInput";
  12617. };
  12618. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  12619. return "VRDeviceOrientation";
  12620. };
  12621. return ArcRotateCameraVRDeviceOrientationInput;
  12622. })();
  12623. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  12624. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  12625. })(BABYLON || (BABYLON = {}));
  12626. var BABYLON;
  12627. (function (BABYLON) {
  12628. var TargetCamera = (function (_super) {
  12629. __extends(TargetCamera, _super);
  12630. function TargetCamera(name, position, scene) {
  12631. _super.call(this, name, position, scene);
  12632. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  12633. this.cameraRotation = new BABYLON.Vector2(0, 0);
  12634. this.rotation = new BABYLON.Vector3(0, 0, 0);
  12635. this.speed = 2.0;
  12636. this.noRotationConstraint = false;
  12637. this.lockedTarget = null;
  12638. this._currentTarget = BABYLON.Vector3.Zero();
  12639. this._viewMatrix = BABYLON.Matrix.Zero();
  12640. this._camMatrix = BABYLON.Matrix.Zero();
  12641. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  12642. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  12643. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  12644. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  12645. this._lookAtTemp = BABYLON.Matrix.Zero();
  12646. this._tempMatrix = BABYLON.Matrix.Zero();
  12647. }
  12648. TargetCamera.prototype.getFrontPosition = function (distance) {
  12649. var direction = this.getTarget().subtract(this.position);
  12650. direction.normalize();
  12651. direction.scaleInPlace(distance);
  12652. return this.globalPosition.add(direction);
  12653. };
  12654. TargetCamera.prototype._getLockedTargetPosition = function () {
  12655. if (!this.lockedTarget) {
  12656. return null;
  12657. }
  12658. return this.lockedTarget.position || this.lockedTarget;
  12659. };
  12660. // Cache
  12661. TargetCamera.prototype._initCache = function () {
  12662. _super.prototype._initCache.call(this);
  12663. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12664. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12665. };
  12666. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  12667. if (!ignoreParentClass) {
  12668. _super.prototype._updateCache.call(this);
  12669. }
  12670. var lockedTargetPosition = this._getLockedTargetPosition();
  12671. if (!lockedTargetPosition) {
  12672. this._cache.lockedTarget = null;
  12673. }
  12674. else {
  12675. if (!this._cache.lockedTarget) {
  12676. this._cache.lockedTarget = lockedTargetPosition.clone();
  12677. }
  12678. else {
  12679. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  12680. }
  12681. }
  12682. this._cache.rotation.copyFrom(this.rotation);
  12683. };
  12684. // Synchronized
  12685. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  12686. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  12687. return false;
  12688. }
  12689. var lockedTargetPosition = this._getLockedTargetPosition();
  12690. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  12691. && this._cache.rotation.equals(this.rotation);
  12692. };
  12693. // Methods
  12694. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  12695. var engine = this.getEngine();
  12696. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  12697. };
  12698. // Target
  12699. TargetCamera.prototype.setTarget = function (target) {
  12700. this.upVector.normalize();
  12701. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  12702. this._camMatrix.invert();
  12703. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  12704. var vDir = target.subtract(this.position);
  12705. if (vDir.x >= 0.0) {
  12706. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  12707. }
  12708. else {
  12709. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  12710. }
  12711. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  12712. if (isNaN(this.rotation.x)) {
  12713. this.rotation.x = 0;
  12714. }
  12715. if (isNaN(this.rotation.y)) {
  12716. this.rotation.y = 0;
  12717. }
  12718. if (isNaN(this.rotation.z)) {
  12719. this.rotation.z = 0;
  12720. }
  12721. };
  12722. TargetCamera.prototype.getTarget = function () {
  12723. return this._currentTarget;
  12724. };
  12725. TargetCamera.prototype._decideIfNeedsToMove = function () {
  12726. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  12727. };
  12728. TargetCamera.prototype._updatePosition = function () {
  12729. this.position.addInPlace(this.cameraDirection);
  12730. };
  12731. TargetCamera.prototype._checkInputs = function () {
  12732. var needToMove = this._decideIfNeedsToMove();
  12733. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  12734. // Move
  12735. if (needToMove) {
  12736. this._updatePosition();
  12737. }
  12738. // Rotate
  12739. if (needToRotate) {
  12740. this.rotation.x += this.cameraRotation.x;
  12741. this.rotation.y += this.cameraRotation.y;
  12742. if (!this.noRotationConstraint) {
  12743. var limit = (Math.PI / 2) * 0.95;
  12744. if (this.rotation.x > limit)
  12745. this.rotation.x = limit;
  12746. if (this.rotation.x < -limit)
  12747. this.rotation.x = -limit;
  12748. }
  12749. }
  12750. // Inertia
  12751. if (needToMove) {
  12752. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  12753. this.cameraDirection.x = 0;
  12754. }
  12755. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  12756. this.cameraDirection.y = 0;
  12757. }
  12758. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  12759. this.cameraDirection.z = 0;
  12760. }
  12761. this.cameraDirection.scaleInPlace(this.inertia);
  12762. }
  12763. if (needToRotate) {
  12764. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  12765. this.cameraRotation.x = 0;
  12766. }
  12767. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  12768. this.cameraRotation.y = 0;
  12769. }
  12770. this.cameraRotation.scaleInPlace(this.inertia);
  12771. }
  12772. _super.prototype._checkInputs.call(this);
  12773. };
  12774. TargetCamera.prototype._getViewMatrix = function () {
  12775. if (!this.lockedTarget) {
  12776. // Compute
  12777. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  12778. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  12779. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12780. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  12781. this._lookAtTemp.invert();
  12782. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  12783. }
  12784. else {
  12785. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12786. }
  12787. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12788. // Computing target and final matrix
  12789. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12790. }
  12791. else {
  12792. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  12793. }
  12794. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  12795. return this._viewMatrix;
  12796. };
  12797. TargetCamera.prototype._getVRViewMatrix = function () {
  12798. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12799. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12800. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  12801. // Computing target and final matrix
  12802. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12803. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  12804. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  12805. return this._viewMatrix;
  12806. };
  12807. /**
  12808. * @override
  12809. * Override Camera.createRigCamera
  12810. */
  12811. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  12812. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  12813. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  12814. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  12815. rigCamera._cameraRigParams = {};
  12816. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  12817. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  12818. }
  12819. return rigCamera;
  12820. }
  12821. return null;
  12822. };
  12823. /**
  12824. * @override
  12825. * Override Camera._updateRigCameras
  12826. */
  12827. TargetCamera.prototype._updateRigCameras = function () {
  12828. switch (this.cameraRigMode) {
  12829. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12830. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12831. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12832. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12833. case BABYLON.Camera.RIG_MODE_VR:
  12834. var camLeft = this._rigCameras[0];
  12835. var camRight = this._rigCameras[1];
  12836. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  12837. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  12838. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  12839. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  12840. camLeft.position.copyFrom(this.position);
  12841. camRight.position.copyFrom(this.position);
  12842. }
  12843. else {
  12844. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  12845. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  12846. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  12847. camLeft.setTarget(this.getTarget());
  12848. camRight.setTarget(this.getTarget());
  12849. }
  12850. break;
  12851. }
  12852. _super.prototype._updateRigCameras.call(this);
  12853. };
  12854. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  12855. if (!this._rigCamTransformMatrix) {
  12856. this._rigCamTransformMatrix = new BABYLON.Matrix();
  12857. }
  12858. var target = this.getTarget();
  12859. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  12860. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  12861. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  12862. };
  12863. TargetCamera.prototype.getTypeName = function () {
  12864. return "TargetCamera";
  12865. };
  12866. __decorate([
  12867. BABYLON.serializeAsVector3()
  12868. ], TargetCamera.prototype, "rotation", void 0);
  12869. __decorate([
  12870. BABYLON.serialize()
  12871. ], TargetCamera.prototype, "speed", void 0);
  12872. __decorate([
  12873. BABYLON.serializeAsMeshReference("lockedTargetId")
  12874. ], TargetCamera.prototype, "lockedTarget", void 0);
  12875. return TargetCamera;
  12876. })(BABYLON.Camera);
  12877. BABYLON.TargetCamera = TargetCamera;
  12878. })(BABYLON || (BABYLON = {}));
  12879. var BABYLON;
  12880. (function (BABYLON) {
  12881. var FreeCamera = (function (_super) {
  12882. __extends(FreeCamera, _super);
  12883. function FreeCamera(name, position, scene) {
  12884. var _this = this;
  12885. _super.call(this, name, position, scene);
  12886. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12887. this.checkCollisions = false;
  12888. this.applyGravity = false;
  12889. this._collider = new BABYLON.Collider();
  12890. this._needMoveForGravity = false;
  12891. this._oldPosition = BABYLON.Vector3.Zero();
  12892. this._diffPosition = BABYLON.Vector3.Zero();
  12893. this._newPosition = BABYLON.Vector3.Zero();
  12894. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12895. if (collidedMesh === void 0) { collidedMesh = null; }
  12896. //TODO move this to the collision coordinator!
  12897. if (_this.getScene().workerCollisions)
  12898. newPosition.multiplyInPlace(_this._collider.radius);
  12899. var updatePosition = function (newPos) {
  12900. _this._newPosition.copyFrom(newPos);
  12901. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  12902. var oldPosition = _this.position.clone();
  12903. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  12904. _this.position.addInPlace(_this._diffPosition);
  12905. if (_this.onCollide && collidedMesh) {
  12906. _this.onCollide(collidedMesh);
  12907. }
  12908. }
  12909. };
  12910. updatePosition(newPosition);
  12911. };
  12912. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  12913. this.inputs.addKeyboard().addMouse();
  12914. }
  12915. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  12916. //-- begin properties for backward compatibility for inputs
  12917. get: function () {
  12918. var mouse = this.inputs.attached["mouse"];
  12919. if (mouse)
  12920. return mouse.angularSensibility;
  12921. },
  12922. set: function (value) {
  12923. var mouse = this.inputs.attached["mouse"];
  12924. if (mouse)
  12925. mouse.angularSensibility = value;
  12926. },
  12927. enumerable: true,
  12928. configurable: true
  12929. });
  12930. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  12931. get: function () {
  12932. var keyboard = this.inputs.attached["keyboard"];
  12933. if (keyboard)
  12934. return keyboard.keysUp;
  12935. },
  12936. set: function (value) {
  12937. var keyboard = this.inputs.attached["keyboard"];
  12938. if (keyboard)
  12939. keyboard.keysUp = value;
  12940. },
  12941. enumerable: true,
  12942. configurable: true
  12943. });
  12944. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  12945. get: function () {
  12946. var keyboard = this.inputs.attached["keyboard"];
  12947. if (keyboard)
  12948. return keyboard.keysDown;
  12949. },
  12950. set: function (value) {
  12951. var keyboard = this.inputs.attached["keyboard"];
  12952. if (keyboard)
  12953. keyboard.keysDown = value;
  12954. },
  12955. enumerable: true,
  12956. configurable: true
  12957. });
  12958. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  12959. get: function () {
  12960. var keyboard = this.inputs.attached["keyboard"];
  12961. if (keyboard)
  12962. return keyboard.keysLeft;
  12963. },
  12964. set: function (value) {
  12965. var keyboard = this.inputs.attached["keyboard"];
  12966. if (keyboard)
  12967. keyboard.keysLeft = value;
  12968. },
  12969. enumerable: true,
  12970. configurable: true
  12971. });
  12972. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  12973. get: function () {
  12974. var keyboard = this.inputs.attached["keyboard"];
  12975. if (keyboard)
  12976. return keyboard.keysRight;
  12977. },
  12978. set: function (value) {
  12979. var keyboard = this.inputs.attached["keyboard"];
  12980. if (keyboard)
  12981. keyboard.keysRight = value;
  12982. },
  12983. enumerable: true,
  12984. configurable: true
  12985. });
  12986. // Controls
  12987. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  12988. this.inputs.attachElement(element, noPreventDefault);
  12989. };
  12990. FreeCamera.prototype.detachControl = function (element) {
  12991. this.inputs.detachElement(element);
  12992. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  12993. this.cameraRotation = new BABYLON.Vector2(0, 0);
  12994. };
  12995. FreeCamera.prototype._collideWithWorld = function (velocity) {
  12996. var globalPosition;
  12997. if (this.parent) {
  12998. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  12999. }
  13000. else {
  13001. globalPosition = this.position;
  13002. }
  13003. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  13004. this._collider.radius = this.ellipsoid;
  13005. //no need for clone, as long as gravity is not on.
  13006. var actualVelocity = velocity;
  13007. //add gravity to the velocity to prevent the dual-collision checking
  13008. if (this.applyGravity) {
  13009. //this prevents mending with cameraDirection, a global variable of the free camera class.
  13010. actualVelocity = velocity.add(this.getScene().gravity);
  13011. }
  13012. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13013. };
  13014. FreeCamera.prototype._checkInputs = function () {
  13015. if (!this._localDirection) {
  13016. this._localDirection = BABYLON.Vector3.Zero();
  13017. this._transformedDirection = BABYLON.Vector3.Zero();
  13018. }
  13019. this.inputs.checkInputs();
  13020. _super.prototype._checkInputs.call(this);
  13021. };
  13022. FreeCamera.prototype._decideIfNeedsToMove = function () {
  13023. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  13024. };
  13025. FreeCamera.prototype._updatePosition = function () {
  13026. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  13027. this._collideWithWorld(this.cameraDirection);
  13028. }
  13029. else {
  13030. this.position.addInPlace(this.cameraDirection);
  13031. }
  13032. };
  13033. FreeCamera.prototype.dispose = function () {
  13034. this.inputs.clear();
  13035. _super.prototype.dispose.call(this);
  13036. };
  13037. FreeCamera.prototype.getTypeName = function () {
  13038. return "FreeCamera";
  13039. };
  13040. __decorate([
  13041. BABYLON.serializeAsVector3()
  13042. ], FreeCamera.prototype, "ellipsoid", void 0);
  13043. __decorate([
  13044. BABYLON.serialize()
  13045. ], FreeCamera.prototype, "checkCollisions", void 0);
  13046. __decorate([
  13047. BABYLON.serialize()
  13048. ], FreeCamera.prototype, "applyGravity", void 0);
  13049. return FreeCamera;
  13050. })(BABYLON.TargetCamera);
  13051. BABYLON.FreeCamera = FreeCamera;
  13052. })(BABYLON || (BABYLON = {}));
  13053. var BABYLON;
  13054. (function (BABYLON) {
  13055. var FreeCameraInputsManager = (function (_super) {
  13056. __extends(FreeCameraInputsManager, _super);
  13057. function FreeCameraInputsManager(camera) {
  13058. _super.call(this, camera);
  13059. }
  13060. FreeCameraInputsManager.prototype.addKeyboard = function () {
  13061. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  13062. return this;
  13063. };
  13064. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  13065. if (touchEnabled === void 0) { touchEnabled = true; }
  13066. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  13067. return this;
  13068. };
  13069. FreeCameraInputsManager.prototype.addGamepad = function () {
  13070. this.add(new BABYLON.FreeCameraGamepadInput());
  13071. return this;
  13072. };
  13073. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  13074. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  13075. return this;
  13076. };
  13077. FreeCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  13078. this.add(new BABYLON.FreeCameraVRDeviceOrientationInput());
  13079. return this;
  13080. };
  13081. FreeCameraInputsManager.prototype.addTouch = function () {
  13082. this.add(new BABYLON.FreeCameraTouchInput());
  13083. return this;
  13084. };
  13085. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  13086. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  13087. return this;
  13088. };
  13089. return FreeCameraInputsManager;
  13090. })(BABYLON.CameraInputsManager);
  13091. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  13092. })(BABYLON || (BABYLON = {}));
  13093. var BABYLON;
  13094. (function (BABYLON) {
  13095. var FollowCamera = (function (_super) {
  13096. __extends(FollowCamera, _super);
  13097. function FollowCamera(name, position, scene, target) {
  13098. _super.call(this, name, position, scene);
  13099. this.radius = 12;
  13100. this.rotationOffset = 0;
  13101. this.heightOffset = 4;
  13102. this.cameraAcceleration = 0.05;
  13103. this.maxCameraSpeed = 20;
  13104. this.target = target;
  13105. }
  13106. FollowCamera.prototype.getRadians = function (degrees) {
  13107. return degrees * Math.PI / 180;
  13108. };
  13109. FollowCamera.prototype.follow = function (cameraTarget) {
  13110. if (!cameraTarget)
  13111. return;
  13112. var yRotation;
  13113. if (cameraTarget.rotationQuaternion) {
  13114. var rotMatrix = new BABYLON.Matrix();
  13115. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  13116. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  13117. }
  13118. else {
  13119. yRotation = cameraTarget.rotation.y;
  13120. }
  13121. var radians = this.getRadians(this.rotationOffset) + yRotation;
  13122. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  13123. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  13124. var dx = targetX - this.position.x;
  13125. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  13126. var dz = (targetZ) - this.position.z;
  13127. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  13128. var vy = dy * this.cameraAcceleration;
  13129. var vz = dz * this.cameraAcceleration * 2;
  13130. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  13131. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13132. }
  13133. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  13134. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13135. }
  13136. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  13137. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13138. }
  13139. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  13140. this.setTarget(cameraTarget.position);
  13141. };
  13142. FollowCamera.prototype._checkInputs = function () {
  13143. _super.prototype._checkInputs.call(this);
  13144. this.follow(this.target);
  13145. };
  13146. FollowCamera.prototype.getTypeName = function () {
  13147. return "FollowCamera";
  13148. };
  13149. __decorate([
  13150. BABYLON.serialize()
  13151. ], FollowCamera.prototype, "radius", void 0);
  13152. __decorate([
  13153. BABYLON.serialize()
  13154. ], FollowCamera.prototype, "rotationOffset", void 0);
  13155. __decorate([
  13156. BABYLON.serialize()
  13157. ], FollowCamera.prototype, "heightOffset", void 0);
  13158. __decorate([
  13159. BABYLON.serialize()
  13160. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  13161. __decorate([
  13162. BABYLON.serialize()
  13163. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  13164. __decorate([
  13165. BABYLON.serializeAsMeshReference("lockedTargetId")
  13166. ], FollowCamera.prototype, "target", void 0);
  13167. return FollowCamera;
  13168. })(BABYLON.TargetCamera);
  13169. BABYLON.FollowCamera = FollowCamera;
  13170. var ArcFollowCamera = (function (_super) {
  13171. __extends(ArcFollowCamera, _super);
  13172. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  13173. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13174. this.alpha = alpha;
  13175. this.beta = beta;
  13176. this.radius = radius;
  13177. this.target = target;
  13178. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  13179. this.follow();
  13180. }
  13181. ArcFollowCamera.prototype.follow = function () {
  13182. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  13183. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  13184. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  13185. this.position = this.target.position.add(this._cartesianCoordinates);
  13186. this.setTarget(this.target.position);
  13187. };
  13188. ArcFollowCamera.prototype._checkInputs = function () {
  13189. _super.prototype._checkInputs.call(this);
  13190. this.follow();
  13191. };
  13192. ArcFollowCamera.prototype.getTypeName = function () {
  13193. return "ArcFollowCamera";
  13194. };
  13195. return ArcFollowCamera;
  13196. })(BABYLON.TargetCamera);
  13197. BABYLON.ArcFollowCamera = ArcFollowCamera;
  13198. })(BABYLON || (BABYLON = {}));
  13199. var BABYLON;
  13200. (function (BABYLON) {
  13201. // We're mainly based on the logic defined into the FreeCamera code
  13202. var TouchCamera = (function (_super) {
  13203. __extends(TouchCamera, _super);
  13204. //-- end properties for backward compatibility for inputs
  13205. function TouchCamera(name, position, scene) {
  13206. _super.call(this, name, position, scene);
  13207. this.inputs.addTouch();
  13208. this._setupInputs();
  13209. }
  13210. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  13211. //-- Begin properties for backward compatibility for inputs
  13212. get: function () {
  13213. var touch = this.inputs.attached["touch"];
  13214. if (touch)
  13215. return touch.touchAngularSensibility;
  13216. },
  13217. set: function (value) {
  13218. var touch = this.inputs.attached["touch"];
  13219. if (touch)
  13220. touch.touchAngularSensibility = value;
  13221. },
  13222. enumerable: true,
  13223. configurable: true
  13224. });
  13225. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  13226. get: function () {
  13227. var touch = this.inputs.attached["touch"];
  13228. if (touch)
  13229. return touch.touchMoveSensibility;
  13230. },
  13231. set: function (value) {
  13232. var touch = this.inputs.attached["touch"];
  13233. if (touch)
  13234. touch.touchMoveSensibility = value;
  13235. },
  13236. enumerable: true,
  13237. configurable: true
  13238. });
  13239. TouchCamera.prototype.getTypeName = function () {
  13240. return "TouchCamera";
  13241. };
  13242. TouchCamera.prototype._setupInputs = function () {
  13243. var mouse = this.inputs.attached["mouse"];
  13244. if (mouse) {
  13245. mouse.touchEnabled = false;
  13246. }
  13247. };
  13248. return TouchCamera;
  13249. })(BABYLON.FreeCamera);
  13250. BABYLON.TouchCamera = TouchCamera;
  13251. })(BABYLON || (BABYLON = {}));
  13252. var BABYLON;
  13253. (function (BABYLON) {
  13254. var ArcRotateCamera = (function (_super) {
  13255. __extends(ArcRotateCamera, _super);
  13256. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  13257. var _this = this;
  13258. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13259. this.inertialAlphaOffset = 0;
  13260. this.inertialBetaOffset = 0;
  13261. this.inertialRadiusOffset = 0;
  13262. this.lowerAlphaLimit = null;
  13263. this.upperAlphaLimit = null;
  13264. this.lowerBetaLimit = 0.01;
  13265. this.upperBetaLimit = Math.PI;
  13266. this.lowerRadiusLimit = null;
  13267. this.upperRadiusLimit = null;
  13268. this.inertialPanningX = 0;
  13269. this.inertialPanningY = 0;
  13270. //-- end properties for backward compatibility for inputs
  13271. this.zoomOnFactor = 1;
  13272. this.targetScreenOffset = BABYLON.Vector2.Zero();
  13273. this.allowUpsideDown = true;
  13274. this._viewMatrix = new BABYLON.Matrix();
  13275. // Panning
  13276. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  13277. this.checkCollisions = false;
  13278. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  13279. this._collider = new BABYLON.Collider();
  13280. this._previousPosition = BABYLON.Vector3.Zero();
  13281. this._collisionVelocity = BABYLON.Vector3.Zero();
  13282. this._newPosition = BABYLON.Vector3.Zero();
  13283. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13284. if (collidedMesh === void 0) { collidedMesh = null; }
  13285. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  13286. newPosition.multiplyInPlace(_this._collider.radius);
  13287. }
  13288. if (!collidedMesh) {
  13289. _this._previousPosition.copyFrom(_this.position);
  13290. }
  13291. else {
  13292. _this.setPosition(newPosition);
  13293. if (_this.onCollide) {
  13294. _this.onCollide(collidedMesh);
  13295. }
  13296. }
  13297. // Recompute because of constraints
  13298. var cosa = Math.cos(_this.alpha);
  13299. var sina = Math.sin(_this.alpha);
  13300. var cosb = Math.cos(_this.beta);
  13301. var sinb = Math.sin(_this.beta);
  13302. if (sinb === 0) {
  13303. sinb = 0.0001;
  13304. }
  13305. var target = _this._getTargetPosition();
  13306. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  13307. _this.position.copyFrom(_this._newPosition);
  13308. var up = _this.upVector;
  13309. if (_this.allowUpsideDown && _this.beta < 0) {
  13310. up = up.clone();
  13311. up = up.negate();
  13312. }
  13313. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  13314. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  13315. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  13316. _this._collisionTriggered = false;
  13317. };
  13318. if (!target) {
  13319. this.target = BABYLON.Vector3.Zero();
  13320. }
  13321. else {
  13322. this.target = target;
  13323. }
  13324. this.alpha = alpha;
  13325. this.beta = beta;
  13326. this.radius = radius;
  13327. this.getViewMatrix();
  13328. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  13329. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  13330. }
  13331. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  13332. //-- begin properties for backward compatibility for inputs
  13333. get: function () {
  13334. var pointers = this.inputs.attached["pointers"];
  13335. if (pointers)
  13336. return pointers.angularSensibilityX;
  13337. },
  13338. set: function (value) {
  13339. var pointers = this.inputs.attached["pointers"];
  13340. if (pointers) {
  13341. pointers.angularSensibilityX = value;
  13342. }
  13343. },
  13344. enumerable: true,
  13345. configurable: true
  13346. });
  13347. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  13348. get: function () {
  13349. var pointers = this.inputs.attached["pointers"];
  13350. if (pointers)
  13351. return pointers.angularSensibilityY;
  13352. },
  13353. set: function (value) {
  13354. var pointers = this.inputs.attached["pointers"];
  13355. if (pointers) {
  13356. pointers.angularSensibilityY = value;
  13357. }
  13358. },
  13359. enumerable: true,
  13360. configurable: true
  13361. });
  13362. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  13363. get: function () {
  13364. var pointers = this.inputs.attached["pointers"];
  13365. if (pointers)
  13366. return pointers.pinchPrecision;
  13367. },
  13368. set: function (value) {
  13369. var pointers = this.inputs.attached["pointers"];
  13370. if (pointers) {
  13371. pointers.pinchPrecision = value;
  13372. }
  13373. },
  13374. enumerable: true,
  13375. configurable: true
  13376. });
  13377. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  13378. get: function () {
  13379. var pointers = this.inputs.attached["pointers"];
  13380. if (pointers)
  13381. return pointers.panningSensibility;
  13382. },
  13383. set: function (value) {
  13384. var pointers = this.inputs.attached["pointers"];
  13385. if (pointers) {
  13386. pointers.panningSensibility = value;
  13387. }
  13388. },
  13389. enumerable: true,
  13390. configurable: true
  13391. });
  13392. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  13393. get: function () {
  13394. var keyboard = this.inputs.attached["keyboard"];
  13395. if (keyboard)
  13396. return keyboard.keysUp;
  13397. },
  13398. set: function (value) {
  13399. var keyboard = this.inputs.attached["keyboard"];
  13400. if (keyboard)
  13401. keyboard.keysUp = value;
  13402. },
  13403. enumerable: true,
  13404. configurable: true
  13405. });
  13406. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  13407. get: function () {
  13408. var keyboard = this.inputs.attached["keyboard"];
  13409. if (keyboard)
  13410. return keyboard.keysDown;
  13411. },
  13412. set: function (value) {
  13413. var keyboard = this.inputs.attached["keyboard"];
  13414. if (keyboard)
  13415. keyboard.keysDown = value;
  13416. },
  13417. enumerable: true,
  13418. configurable: true
  13419. });
  13420. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  13421. get: function () {
  13422. var keyboard = this.inputs.attached["keyboard"];
  13423. if (keyboard)
  13424. return keyboard.keysLeft;
  13425. },
  13426. set: function (value) {
  13427. var keyboard = this.inputs.attached["keyboard"];
  13428. if (keyboard)
  13429. keyboard.keysLeft = value;
  13430. },
  13431. enumerable: true,
  13432. configurable: true
  13433. });
  13434. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  13435. get: function () {
  13436. var keyboard = this.inputs.attached["keyboard"];
  13437. if (keyboard)
  13438. return keyboard.keysRight;
  13439. },
  13440. set: function (value) {
  13441. var keyboard = this.inputs.attached["keyboard"];
  13442. if (keyboard)
  13443. keyboard.keysRight = value;
  13444. },
  13445. enumerable: true,
  13446. configurable: true
  13447. });
  13448. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  13449. get: function () {
  13450. var mousewheel = this.inputs.attached["mousewheel"];
  13451. if (mousewheel)
  13452. return mousewheel.wheelPrecision;
  13453. },
  13454. set: function (value) {
  13455. var mousewheel = this.inputs.attached["mousewheel"];
  13456. if (mousewheel)
  13457. mousewheel.wheelPrecision = value;
  13458. },
  13459. enumerable: true,
  13460. configurable: true
  13461. });
  13462. // Cache
  13463. ArcRotateCamera.prototype._initCache = function () {
  13464. _super.prototype._initCache.call(this);
  13465. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13466. this._cache.alpha = undefined;
  13467. this._cache.beta = undefined;
  13468. this._cache.radius = undefined;
  13469. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  13470. };
  13471. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  13472. if (!ignoreParentClass) {
  13473. _super.prototype._updateCache.call(this);
  13474. }
  13475. this._cache.target.copyFrom(this._getTargetPosition());
  13476. this._cache.alpha = this.alpha;
  13477. this._cache.beta = this.beta;
  13478. this._cache.radius = this.radius;
  13479. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  13480. };
  13481. ArcRotateCamera.prototype._getTargetPosition = function () {
  13482. if (this.target.getAbsolutePosition) {
  13483. return this.target.getAbsolutePosition();
  13484. }
  13485. return this.target;
  13486. };
  13487. // Synchronized
  13488. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  13489. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  13490. return false;
  13491. return this._cache.target.equals(this.target)
  13492. && this._cache.alpha === this.alpha
  13493. && this._cache.beta === this.beta
  13494. && this._cache.radius === this.radius
  13495. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  13496. };
  13497. // Methods
  13498. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  13499. var _this = this;
  13500. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  13501. this._useCtrlForPanning = useCtrlForPanning;
  13502. this.inputs.attachElement(element, noPreventDefault);
  13503. this._reset = function () {
  13504. _this.inertialAlphaOffset = 0;
  13505. _this.inertialBetaOffset = 0;
  13506. _this.inertialRadiusOffset = 0;
  13507. };
  13508. };
  13509. ArcRotateCamera.prototype.detachControl = function (element) {
  13510. this.inputs.detachElement(element);
  13511. if (this._reset) {
  13512. this._reset();
  13513. }
  13514. };
  13515. ArcRotateCamera.prototype._checkInputs = function () {
  13516. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  13517. if (this._collisionTriggered) {
  13518. return;
  13519. }
  13520. this.inputs.checkInputs();
  13521. // Inertia
  13522. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  13523. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  13524. this.beta += this.inertialBetaOffset;
  13525. this.radius -= this.inertialRadiusOffset;
  13526. this.inertialAlphaOffset *= this.inertia;
  13527. this.inertialBetaOffset *= this.inertia;
  13528. this.inertialRadiusOffset *= this.inertia;
  13529. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  13530. this.inertialAlphaOffset = 0;
  13531. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  13532. this.inertialBetaOffset = 0;
  13533. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  13534. this.inertialRadiusOffset = 0;
  13535. }
  13536. // Panning inertia
  13537. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  13538. if (!this._localDirection) {
  13539. this._localDirection = BABYLON.Vector3.Zero();
  13540. this._transformedDirection = BABYLON.Vector3.Zero();
  13541. }
  13542. this.inertialPanningX *= this.inertia;
  13543. this.inertialPanningY *= this.inertia;
  13544. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  13545. this.inertialPanningX = 0;
  13546. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  13547. this.inertialPanningY = 0;
  13548. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  13549. this._localDirection.multiplyInPlace(this.panningAxis);
  13550. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  13551. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  13552. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  13553. if (!this.panningAxis.y) {
  13554. this._transformedDirection.y = 0;
  13555. }
  13556. this.target.addInPlace(this._transformedDirection);
  13557. }
  13558. // Limits
  13559. this._checkLimits();
  13560. _super.prototype._checkInputs.call(this);
  13561. };
  13562. ArcRotateCamera.prototype._checkLimits = function () {
  13563. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  13564. if (this.allowUpsideDown && this.beta > Math.PI) {
  13565. this.beta = this.beta - (2 * Math.PI);
  13566. }
  13567. }
  13568. else {
  13569. if (this.beta < this.lowerBetaLimit) {
  13570. this.beta = this.lowerBetaLimit;
  13571. }
  13572. }
  13573. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  13574. if (this.allowUpsideDown && this.beta < -Math.PI) {
  13575. this.beta = this.beta + (2 * Math.PI);
  13576. }
  13577. }
  13578. else {
  13579. if (this.beta > this.upperBetaLimit) {
  13580. this.beta = this.upperBetaLimit;
  13581. }
  13582. }
  13583. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  13584. this.alpha = this.lowerAlphaLimit;
  13585. }
  13586. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  13587. this.alpha = this.upperAlphaLimit;
  13588. }
  13589. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  13590. this.radius = this.lowerRadiusLimit;
  13591. }
  13592. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  13593. this.radius = this.upperRadiusLimit;
  13594. }
  13595. };
  13596. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  13597. var radiusv3 = this.position.subtract(this._getTargetPosition());
  13598. this.radius = radiusv3.length();
  13599. // Alpha
  13600. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  13601. if (radiusv3.z < 0) {
  13602. this.alpha = 2 * Math.PI - this.alpha;
  13603. }
  13604. // Beta
  13605. this.beta = Math.acos(radiusv3.y / this.radius);
  13606. this._checkLimits();
  13607. };
  13608. ArcRotateCamera.prototype.setPosition = function (position) {
  13609. if (this.position.equals(position)) {
  13610. return;
  13611. }
  13612. this.position = position;
  13613. this.rebuildAnglesAndRadius();
  13614. };
  13615. ArcRotateCamera.prototype.setTarget = function (target) {
  13616. if (this._getTargetPosition().equals(target)) {
  13617. return;
  13618. }
  13619. this.target = target;
  13620. this.rebuildAnglesAndRadius();
  13621. };
  13622. ArcRotateCamera.prototype._getViewMatrix = function () {
  13623. // Compute
  13624. var cosa = Math.cos(this.alpha);
  13625. var sina = Math.sin(this.alpha);
  13626. var cosb = Math.cos(this.beta);
  13627. var sinb = Math.sin(this.beta);
  13628. if (sinb === 0) {
  13629. sinb = 0.0001;
  13630. }
  13631. var target = this._getTargetPosition();
  13632. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  13633. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  13634. this._collider.radius = this.collisionRadius;
  13635. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  13636. this._collisionTriggered = true;
  13637. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13638. }
  13639. else {
  13640. this.position.copyFrom(this._newPosition);
  13641. var up = this.upVector;
  13642. if (this.allowUpsideDown && this.beta < 0) {
  13643. up = up.clone();
  13644. up = up.negate();
  13645. }
  13646. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  13647. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  13648. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  13649. }
  13650. return this._viewMatrix;
  13651. };
  13652. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  13653. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13654. meshes = meshes || this.getScene().meshes;
  13655. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  13656. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  13657. this.radius = distance * this.zoomOnFactor;
  13658. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  13659. };
  13660. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  13661. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13662. var meshesOrMinMaxVector;
  13663. var distance;
  13664. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  13665. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  13666. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  13667. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  13668. }
  13669. else {
  13670. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  13671. distance = meshesOrMinMaxVectorAndDistance.distance;
  13672. }
  13673. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  13674. if (!doNotUpdateMaxZ) {
  13675. this.maxZ = distance * 2;
  13676. }
  13677. };
  13678. /**
  13679. * @override
  13680. * Override Camera.createRigCamera
  13681. */
  13682. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  13683. switch (this.cameraRigMode) {
  13684. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13685. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13686. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13687. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13688. case BABYLON.Camera.RIG_MODE_VR:
  13689. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  13690. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  13691. rigCam._cameraRigParams = {};
  13692. return rigCam;
  13693. }
  13694. return null;
  13695. };
  13696. /**
  13697. * @override
  13698. * Override Camera._updateRigCameras
  13699. */
  13700. ArcRotateCamera.prototype._updateRigCameras = function () {
  13701. switch (this.cameraRigMode) {
  13702. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13703. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13704. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13705. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13706. case BABYLON.Camera.RIG_MODE_VR:
  13707. var camLeft = this._rigCameras[0];
  13708. var camRight = this._rigCameras[1];
  13709. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  13710. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  13711. camLeft.beta = camRight.beta = this.beta;
  13712. camLeft.radius = camRight.radius = this.radius;
  13713. break;
  13714. }
  13715. _super.prototype._updateRigCameras.call(this);
  13716. };
  13717. ArcRotateCamera.prototype.dispose = function () {
  13718. this.inputs.clear();
  13719. _super.prototype.dispose.call(this);
  13720. };
  13721. ArcRotateCamera.prototype.getTypeName = function () {
  13722. return "ArcRotateCamera";
  13723. };
  13724. __decorate([
  13725. BABYLON.serialize()
  13726. ], ArcRotateCamera.prototype, "alpha", void 0);
  13727. __decorate([
  13728. BABYLON.serialize()
  13729. ], ArcRotateCamera.prototype, "beta", void 0);
  13730. __decorate([
  13731. BABYLON.serialize()
  13732. ], ArcRotateCamera.prototype, "radius", void 0);
  13733. __decorate([
  13734. BABYLON.serializeAsVector3()
  13735. ], ArcRotateCamera.prototype, "target", void 0);
  13736. __decorate([
  13737. BABYLON.serialize()
  13738. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  13739. __decorate([
  13740. BABYLON.serialize()
  13741. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  13742. __decorate([
  13743. BABYLON.serialize()
  13744. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  13745. __decorate([
  13746. BABYLON.serialize()
  13747. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  13748. __decorate([
  13749. BABYLON.serialize()
  13750. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  13751. __decorate([
  13752. BABYLON.serialize()
  13753. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  13754. __decorate([
  13755. BABYLON.serialize()
  13756. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  13757. __decorate([
  13758. BABYLON.serialize()
  13759. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  13760. __decorate([
  13761. BABYLON.serialize()
  13762. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  13763. __decorate([
  13764. BABYLON.serialize()
  13765. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  13766. __decorate([
  13767. BABYLON.serialize()
  13768. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  13769. __decorate([
  13770. BABYLON.serialize()
  13771. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  13772. __decorate([
  13773. BABYLON.serialize()
  13774. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  13775. return ArcRotateCamera;
  13776. })(BABYLON.TargetCamera);
  13777. BABYLON.ArcRotateCamera = ArcRotateCamera;
  13778. })(BABYLON || (BABYLON = {}));
  13779. var BABYLON;
  13780. (function (BABYLON) {
  13781. var ArcRotateCameraInputsManager = (function (_super) {
  13782. __extends(ArcRotateCameraInputsManager, _super);
  13783. function ArcRotateCameraInputsManager(camera) {
  13784. _super.call(this, camera);
  13785. }
  13786. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  13787. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  13788. return this;
  13789. };
  13790. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  13791. this.add(new BABYLON.ArcRotateCameraPointersInput());
  13792. return this;
  13793. };
  13794. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  13795. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  13796. return this;
  13797. };
  13798. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  13799. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  13800. return this;
  13801. };
  13802. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  13803. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  13804. return this;
  13805. };
  13806. return ArcRotateCameraInputsManager;
  13807. })(BABYLON.CameraInputsManager);
  13808. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  13809. })(BABYLON || (BABYLON = {}));
  13810. var BABYLON;
  13811. (function (BABYLON) {
  13812. var RenderingManager = (function () {
  13813. function RenderingManager(scene) {
  13814. this._renderingGroups = new Array();
  13815. this._scene = scene;
  13816. }
  13817. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  13818. if (this._scene._activeParticleSystems.length === 0) {
  13819. return;
  13820. }
  13821. // Particles
  13822. var activeCamera = this._scene.activeCamera;
  13823. var beforeParticlesDate = BABYLON.Tools.Now;
  13824. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  13825. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  13826. if (particleSystem.renderingGroupId !== index) {
  13827. continue;
  13828. }
  13829. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  13830. continue;
  13831. }
  13832. this._clearDepthBuffer();
  13833. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  13834. this._scene._activeParticles += particleSystem.render();
  13835. }
  13836. }
  13837. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13838. };
  13839. RenderingManager.prototype._renderSprites = function (index) {
  13840. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  13841. return;
  13842. }
  13843. // Sprites
  13844. var activeCamera = this._scene.activeCamera;
  13845. var beforeSpritessDate = BABYLON.Tools.Now;
  13846. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  13847. var spriteManager = this._scene.spriteManagers[id];
  13848. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  13849. this._clearDepthBuffer();
  13850. spriteManager.render();
  13851. }
  13852. }
  13853. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  13854. };
  13855. RenderingManager.prototype._clearDepthBuffer = function () {
  13856. if (this._depthBufferAlreadyCleaned) {
  13857. return;
  13858. }
  13859. this._scene.getEngine().clear(0, false, true);
  13860. this._depthBufferAlreadyCleaned = true;
  13861. };
  13862. RenderingManager.prototype._renderSpritesAndParticles = function () {
  13863. if (this._currentRenderSprites) {
  13864. this._renderSprites(this._currentIndex);
  13865. }
  13866. if (this._currentRenderParticles) {
  13867. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  13868. }
  13869. };
  13870. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  13871. this._currentActiveMeshes = activeMeshes;
  13872. this._currentRenderParticles = renderParticles;
  13873. this._currentRenderSprites = renderSprites;
  13874. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13875. this._depthBufferAlreadyCleaned = index == 0;
  13876. var renderingGroup = this._renderingGroups[index];
  13877. var needToStepBack = false;
  13878. this._currentIndex = index;
  13879. if (renderingGroup) {
  13880. this._clearDepthBuffer();
  13881. if (!renderingGroup.onBeforeTransparentRendering) {
  13882. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  13883. }
  13884. if (!renderingGroup.render(customRenderFunction)) {
  13885. this._renderingGroups.splice(index, 1);
  13886. needToStepBack = true;
  13887. this._renderSpritesAndParticles();
  13888. }
  13889. }
  13890. else {
  13891. this._renderSpritesAndParticles();
  13892. }
  13893. if (needToStepBack) {
  13894. index--;
  13895. }
  13896. }
  13897. };
  13898. RenderingManager.prototype.reset = function () {
  13899. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  13900. if (renderingGroup) {
  13901. renderingGroup.prepare();
  13902. }
  13903. });
  13904. };
  13905. RenderingManager.prototype.dispatch = function (subMesh) {
  13906. var mesh = subMesh.getMesh();
  13907. var renderingGroupId = mesh.renderingGroupId || 0;
  13908. if (!this._renderingGroups[renderingGroupId]) {
  13909. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  13910. }
  13911. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  13912. };
  13913. RenderingManager.MAX_RENDERINGGROUPS = 4;
  13914. return RenderingManager;
  13915. })();
  13916. BABYLON.RenderingManager = RenderingManager;
  13917. })(BABYLON || (BABYLON = {}));
  13918. var BABYLON;
  13919. (function (BABYLON) {
  13920. var RenderingGroup = (function () {
  13921. function RenderingGroup(index, scene) {
  13922. this.index = index;
  13923. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  13924. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  13925. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  13926. this._scene = scene;
  13927. }
  13928. RenderingGroup.prototype.render = function (customRenderFunction) {
  13929. if (customRenderFunction) {
  13930. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  13931. return true;
  13932. }
  13933. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  13934. if (this.onBeforeTransparentRendering) {
  13935. this.onBeforeTransparentRendering();
  13936. }
  13937. return false;
  13938. }
  13939. var engine = this._scene.getEngine();
  13940. // Opaque
  13941. var subIndex;
  13942. var submesh;
  13943. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  13944. submesh = this._opaqueSubMeshes.data[subIndex];
  13945. submesh.render(false);
  13946. }
  13947. // Alpha test
  13948. engine.setAlphaTesting(true);
  13949. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  13950. submesh = this._alphaTestSubMeshes.data[subIndex];
  13951. submesh.render(false);
  13952. }
  13953. engine.setAlphaTesting(false);
  13954. if (this.onBeforeTransparentRendering) {
  13955. this.onBeforeTransparentRendering();
  13956. }
  13957. // Transparent
  13958. if (this._transparentSubMeshes.length) {
  13959. // Sorting
  13960. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  13961. submesh = this._transparentSubMeshes.data[subIndex];
  13962. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  13963. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  13964. }
  13965. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  13966. sortedArray.sort(function (a, b) {
  13967. // Alpha index first
  13968. if (a._alphaIndex > b._alphaIndex) {
  13969. return 1;
  13970. }
  13971. if (a._alphaIndex < b._alphaIndex) {
  13972. return -1;
  13973. }
  13974. // Then distance to camera
  13975. if (a._distanceToCamera < b._distanceToCamera) {
  13976. return 1;
  13977. }
  13978. if (a._distanceToCamera > b._distanceToCamera) {
  13979. return -1;
  13980. }
  13981. return 0;
  13982. });
  13983. // Rendering
  13984. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  13985. submesh = sortedArray[subIndex];
  13986. submesh.render(true);
  13987. }
  13988. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13989. }
  13990. return true;
  13991. };
  13992. RenderingGroup.prototype.prepare = function () {
  13993. this._opaqueSubMeshes.reset();
  13994. this._transparentSubMeshes.reset();
  13995. this._alphaTestSubMeshes.reset();
  13996. };
  13997. RenderingGroup.prototype.dispatch = function (subMesh) {
  13998. var material = subMesh.getMaterial();
  13999. var mesh = subMesh.getMesh();
  14000. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  14001. this._transparentSubMeshes.push(subMesh);
  14002. }
  14003. else if (material.needAlphaTesting()) {
  14004. this._alphaTestSubMeshes.push(subMesh);
  14005. }
  14006. else {
  14007. this._opaqueSubMeshes.push(subMesh); // Opaque
  14008. }
  14009. };
  14010. return RenderingGroup;
  14011. })();
  14012. BABYLON.RenderingGroup = RenderingGroup;
  14013. })(BABYLON || (BABYLON = {}));
  14014. var BABYLON;
  14015. (function (BABYLON) {
  14016. var PointerEventTypes = (function () {
  14017. function PointerEventTypes() {
  14018. }
  14019. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  14020. get: function () {
  14021. return PointerEventTypes._POINTERDOWN;
  14022. },
  14023. enumerable: true,
  14024. configurable: true
  14025. });
  14026. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  14027. get: function () {
  14028. return PointerEventTypes._POINTERUP;
  14029. },
  14030. enumerable: true,
  14031. configurable: true
  14032. });
  14033. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  14034. get: function () {
  14035. return PointerEventTypes._POINTERMOVE;
  14036. },
  14037. enumerable: true,
  14038. configurable: true
  14039. });
  14040. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  14041. get: function () {
  14042. return PointerEventTypes._POINTERWHEEL;
  14043. },
  14044. enumerable: true,
  14045. configurable: true
  14046. });
  14047. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  14048. get: function () {
  14049. return PointerEventTypes._POINTERPICK;
  14050. },
  14051. enumerable: true,
  14052. configurable: true
  14053. });
  14054. PointerEventTypes._POINTERDOWN = 0x01;
  14055. PointerEventTypes._POINTERUP = 0x02;
  14056. PointerEventTypes._POINTERMOVE = 0x04;
  14057. PointerEventTypes._POINTERWHEEL = 0x08;
  14058. PointerEventTypes._POINTERPICK = 0x10;
  14059. return PointerEventTypes;
  14060. })();
  14061. BABYLON.PointerEventTypes = PointerEventTypes;
  14062. /**
  14063. * This type contains all the data related to a pointer event in Babylon.js.
  14064. * 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.
  14065. */
  14066. var PointerInfo = (function () {
  14067. function PointerInfo(type, event, pickInfo) {
  14068. this.type = type;
  14069. this.event = event;
  14070. this.pickInfo = pickInfo;
  14071. }
  14072. return PointerInfo;
  14073. })();
  14074. BABYLON.PointerInfo = PointerInfo;
  14075. /**
  14076. * Represents a scene to be rendered by the engine.
  14077. * @see http://doc.babylonjs.com/page.php?p=21911
  14078. */
  14079. var Scene = (function () {
  14080. /**
  14081. * @constructor
  14082. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  14083. */
  14084. function Scene(engine) {
  14085. // Members
  14086. this.autoClear = true;
  14087. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14088. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14089. this.forceWireframe = false;
  14090. this.forcePointsCloud = false;
  14091. this.forceShowBoundingBoxes = false;
  14092. this.animationsEnabled = true;
  14093. this.constantlyUpdateMeshUnderPointer = false;
  14094. // Events
  14095. /**
  14096. * An event triggered when the scene is disposed.
  14097. * @type {BABYLON.Observable}
  14098. */
  14099. this.onDisposeObservable = new BABYLON.Observable();
  14100. /**
  14101. * An event triggered before rendering the scene
  14102. * @type {BABYLON.Observable}
  14103. */
  14104. this.onBeforeRenderObservable = new BABYLON.Observable();
  14105. /**
  14106. * An event triggered after rendering the scene
  14107. * @type {BABYLON.Observable}
  14108. */
  14109. this.onAfterRenderObservable = new BABYLON.Observable();
  14110. /**
  14111. * An event triggered when the scene is ready
  14112. * @type {BABYLON.Observable}
  14113. */
  14114. this.onReadyObservable = new BABYLON.Observable();
  14115. /**
  14116. * An event triggered before rendering a camera
  14117. * @type {BABYLON.Observable}
  14118. */
  14119. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  14120. /**
  14121. * An event triggered after rendering a camera
  14122. * @type {BABYLON.Observable}
  14123. */
  14124. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  14125. /**
  14126. * An event triggered when a camera is created
  14127. * @type {BABYLON.Observable}
  14128. */
  14129. this.onNewCameraAddedObservable = new BABYLON.Observable();
  14130. /**
  14131. * An event triggered when a camera is removed
  14132. * @type {BABYLON.Observable}
  14133. */
  14134. this.onCameraRemovedObservable = new BABYLON.Observable();
  14135. /**
  14136. * An event triggered when a light is created
  14137. * @type {BABYLON.Observable}
  14138. */
  14139. this.onNewLightAddedObservable = new BABYLON.Observable();
  14140. /**
  14141. * An event triggered when a light is removed
  14142. * @type {BABYLON.Observable}
  14143. */
  14144. this.onLightRemovedObservable = new BABYLON.Observable();
  14145. /**
  14146. * An event triggered when a geometry is created
  14147. * @type {BABYLON.Observable}
  14148. */
  14149. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  14150. /**
  14151. * An event triggered when a geometry is removed
  14152. * @type {BABYLON.Observable}
  14153. */
  14154. this.onGeometryRemovedObservable = new BABYLON.Observable();
  14155. /**
  14156. * An event triggered when a mesh is created
  14157. * @type {BABYLON.Observable}
  14158. */
  14159. this.onNewMeshAddedObservable = new BABYLON.Observable();
  14160. /**
  14161. * An event triggered when a mesh is removed
  14162. * @type {BABYLON.Observable}
  14163. */
  14164. this.onMeshRemovedObservable = new BABYLON.Observable();
  14165. // Animations
  14166. this.animations = [];
  14167. /**
  14168. * Observable event triggered each time an input event is received from the rendering canvas
  14169. */
  14170. this.onPointerObservable = new BABYLON.Observable();
  14171. 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
  14172. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  14173. this._startingPointerTime = 0;
  14174. // Fog
  14175. /**
  14176. * is fog enabled on this scene.
  14177. * @type {boolean}
  14178. */
  14179. this.fogEnabled = true;
  14180. this.fogMode = Scene.FOGMODE_NONE;
  14181. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14182. this.fogDensity = 0.1;
  14183. this.fogStart = 0;
  14184. this.fogEnd = 1000.0;
  14185. // Lights
  14186. /**
  14187. * is shadow enabled on this scene.
  14188. * @type {boolean}
  14189. */
  14190. this.shadowsEnabled = true;
  14191. /**
  14192. * is light enabled on this scene.
  14193. * @type {boolean}
  14194. */
  14195. this.lightsEnabled = true;
  14196. /**
  14197. * All of the lights added to this scene.
  14198. * @see BABYLON.Light
  14199. * @type {BABYLON.Light[]}
  14200. */
  14201. this.lights = new Array();
  14202. // Cameras
  14203. /**
  14204. * All of the cameras added to this scene.
  14205. * @see BABYLON.Camera
  14206. * @type {BABYLON.Camera[]}
  14207. */
  14208. this.cameras = new Array();
  14209. this.activeCameras = new Array();
  14210. // Meshes
  14211. /**
  14212. * All of the (abstract) meshes added to this scene.
  14213. * @see BABYLON.AbstractMesh
  14214. * @type {BABYLON.AbstractMesh[]}
  14215. */
  14216. this.meshes = new Array();
  14217. // Geometries
  14218. this._geometries = new Array();
  14219. this.materials = new Array();
  14220. this.multiMaterials = new Array();
  14221. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  14222. // Textures
  14223. this.texturesEnabled = true;
  14224. this.textures = new Array();
  14225. // Particles
  14226. this.particlesEnabled = true;
  14227. this.particleSystems = new Array();
  14228. // Sprites
  14229. this.spritesEnabled = true;
  14230. this.spriteManagers = new Array();
  14231. // Layers
  14232. this.layers = new Array();
  14233. // Skeletons
  14234. this.skeletonsEnabled = true;
  14235. this.skeletons = new Array();
  14236. // Lens flares
  14237. this.lensFlaresEnabled = true;
  14238. this.lensFlareSystems = new Array();
  14239. // Collisions
  14240. this.collisionsEnabled = true;
  14241. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  14242. // Postprocesses
  14243. this.postProcessesEnabled = true;
  14244. // Customs render targets
  14245. this.renderTargetsEnabled = true;
  14246. this.dumpNextRenderTargets = false;
  14247. this.customRenderTargets = new Array();
  14248. // Imported meshes
  14249. this.importedMeshesFiles = new Array();
  14250. // Probes
  14251. this.probesEnabled = true;
  14252. this.reflectionProbes = new Array();
  14253. this._actionManagers = new Array();
  14254. this._meshesForIntersections = new BABYLON.SmartArray(256);
  14255. // Procedural textures
  14256. this.proceduralTexturesEnabled = true;
  14257. this._proceduralTextures = new Array();
  14258. this.soundTracks = new Array();
  14259. this._audioEnabled = true;
  14260. this._headphone = false;
  14261. this._totalVertices = 0;
  14262. this._activeIndices = 0;
  14263. this._activeParticles = 0;
  14264. this._lastFrameDuration = 0;
  14265. this._evaluateActiveMeshesDuration = 0;
  14266. this._renderTargetsDuration = 0;
  14267. this._particlesDuration = 0;
  14268. this._renderDuration = 0;
  14269. this._spritesDuration = 0;
  14270. this._animationRatio = 0;
  14271. this._renderId = 0;
  14272. this._executeWhenReadyTimeoutId = -1;
  14273. this._intermediateRendering = false;
  14274. this._toBeDisposed = new BABYLON.SmartArray(256);
  14275. this._pendingData = []; //ANY
  14276. this._activeMeshes = new BABYLON.SmartArray(256);
  14277. this._processedMaterials = new BABYLON.SmartArray(256);
  14278. this._renderTargets = new BABYLON.SmartArray(256);
  14279. this._activeParticleSystems = new BABYLON.SmartArray(256);
  14280. this._activeSkeletons = new BABYLON.SmartArray(32);
  14281. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  14282. this._activeBones = 0;
  14283. this._activeAnimatables = new Array();
  14284. this._transformMatrix = BABYLON.Matrix.Zero();
  14285. this._edgesRenderers = new BABYLON.SmartArray(16);
  14286. this._uniqueIdCounter = 0;
  14287. this._engine = engine;
  14288. engine.scenes.push(this);
  14289. this._renderingManager = new BABYLON.RenderingManager(this);
  14290. this.postProcessManager = new BABYLON.PostProcessManager(this);
  14291. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  14292. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  14293. if (BABYLON.OutlineRenderer) {
  14294. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  14295. }
  14296. this.attachControl();
  14297. this._debugLayer = new BABYLON.DebugLayer(this);
  14298. if (BABYLON.SoundTrack) {
  14299. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  14300. }
  14301. //simplification queue
  14302. if (BABYLON.SimplificationQueue) {
  14303. this.simplificationQueue = new BABYLON.SimplificationQueue();
  14304. }
  14305. //collision coordinator initialization. For now legacy per default.
  14306. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  14307. }
  14308. Object.defineProperty(Scene, "FOGMODE_NONE", {
  14309. get: function () {
  14310. return Scene._FOGMODE_NONE;
  14311. },
  14312. enumerable: true,
  14313. configurable: true
  14314. });
  14315. Object.defineProperty(Scene, "FOGMODE_EXP", {
  14316. get: function () {
  14317. return Scene._FOGMODE_EXP;
  14318. },
  14319. enumerable: true,
  14320. configurable: true
  14321. });
  14322. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  14323. get: function () {
  14324. return Scene._FOGMODE_EXP2;
  14325. },
  14326. enumerable: true,
  14327. configurable: true
  14328. });
  14329. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  14330. get: function () {
  14331. return Scene._FOGMODE_LINEAR;
  14332. },
  14333. enumerable: true,
  14334. configurable: true
  14335. });
  14336. Object.defineProperty(Scene.prototype, "onDispose", {
  14337. set: function (callback) {
  14338. if (this._onDisposeObserver) {
  14339. this.onDisposeObservable.remove(this._onDisposeObserver);
  14340. }
  14341. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14342. },
  14343. enumerable: true,
  14344. configurable: true
  14345. });
  14346. Object.defineProperty(Scene.prototype, "beforeRender", {
  14347. set: function (callback) {
  14348. if (this._onBeforeRenderObserver) {
  14349. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  14350. }
  14351. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  14352. },
  14353. enumerable: true,
  14354. configurable: true
  14355. });
  14356. Object.defineProperty(Scene.prototype, "afterRender", {
  14357. set: function (callback) {
  14358. if (this._onAfterRenderObserver) {
  14359. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  14360. }
  14361. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  14362. },
  14363. enumerable: true,
  14364. configurable: true
  14365. });
  14366. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  14367. set: function (callback) {
  14368. if (this._onBeforeCameraRenderObserver) {
  14369. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  14370. }
  14371. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  14372. },
  14373. enumerable: true,
  14374. configurable: true
  14375. });
  14376. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  14377. set: function (callback) {
  14378. if (this._onAfterCameraRenderObserver) {
  14379. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  14380. }
  14381. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  14382. },
  14383. enumerable: true,
  14384. configurable: true
  14385. });
  14386. Object.defineProperty(Scene.prototype, "debugLayer", {
  14387. // Properties
  14388. get: function () {
  14389. return this._debugLayer;
  14390. },
  14391. enumerable: true,
  14392. configurable: true
  14393. });
  14394. Object.defineProperty(Scene.prototype, "workerCollisions", {
  14395. get: function () {
  14396. return this._workerCollisions;
  14397. },
  14398. set: function (enabled) {
  14399. enabled = (enabled && !!Worker);
  14400. this._workerCollisions = enabled;
  14401. if (this.collisionCoordinator) {
  14402. this.collisionCoordinator.destroy();
  14403. }
  14404. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  14405. this.collisionCoordinator.init(this);
  14406. },
  14407. enumerable: true,
  14408. configurable: true
  14409. });
  14410. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  14411. get: function () {
  14412. return this._selectionOctree;
  14413. },
  14414. enumerable: true,
  14415. configurable: true
  14416. });
  14417. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  14418. /**
  14419. * The mesh that is currently under the pointer.
  14420. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  14421. */
  14422. get: function () {
  14423. return this._pointerOverMesh;
  14424. },
  14425. enumerable: true,
  14426. configurable: true
  14427. });
  14428. Object.defineProperty(Scene.prototype, "pointerX", {
  14429. /**
  14430. * Current on-screen X position of the pointer
  14431. * @return {number} X position of the pointer
  14432. */
  14433. get: function () {
  14434. return this._pointerX;
  14435. },
  14436. enumerable: true,
  14437. configurable: true
  14438. });
  14439. Object.defineProperty(Scene.prototype, "pointerY", {
  14440. /**
  14441. * Current on-screen Y position of the pointer
  14442. * @return {number} Y position of the pointer
  14443. */
  14444. get: function () {
  14445. return this._pointerY;
  14446. },
  14447. enumerable: true,
  14448. configurable: true
  14449. });
  14450. Scene.prototype.getCachedMaterial = function () {
  14451. return this._cachedMaterial;
  14452. };
  14453. Scene.prototype.getBoundingBoxRenderer = function () {
  14454. return this._boundingBoxRenderer;
  14455. };
  14456. Scene.prototype.getOutlineRenderer = function () {
  14457. return this._outlineRenderer;
  14458. };
  14459. Scene.prototype.getEngine = function () {
  14460. return this._engine;
  14461. };
  14462. Scene.prototype.getTotalVertices = function () {
  14463. return this._totalVertices;
  14464. };
  14465. Scene.prototype.getActiveIndices = function () {
  14466. return this._activeIndices;
  14467. };
  14468. Scene.prototype.getActiveParticles = function () {
  14469. return this._activeParticles;
  14470. };
  14471. Scene.prototype.getActiveBones = function () {
  14472. return this._activeBones;
  14473. };
  14474. // Stats
  14475. Scene.prototype.getLastFrameDuration = function () {
  14476. return this._lastFrameDuration;
  14477. };
  14478. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  14479. return this._evaluateActiveMeshesDuration;
  14480. };
  14481. Scene.prototype.getActiveMeshes = function () {
  14482. return this._activeMeshes;
  14483. };
  14484. Scene.prototype.getRenderTargetsDuration = function () {
  14485. return this._renderTargetsDuration;
  14486. };
  14487. Scene.prototype.getRenderDuration = function () {
  14488. return this._renderDuration;
  14489. };
  14490. Scene.prototype.getParticlesDuration = function () {
  14491. return this._particlesDuration;
  14492. };
  14493. Scene.prototype.getSpritesDuration = function () {
  14494. return this._spritesDuration;
  14495. };
  14496. Scene.prototype.getAnimationRatio = function () {
  14497. return this._animationRatio;
  14498. };
  14499. Scene.prototype.getRenderId = function () {
  14500. return this._renderId;
  14501. };
  14502. Scene.prototype.incrementRenderId = function () {
  14503. this._renderId++;
  14504. };
  14505. Scene.prototype._updatePointerPosition = function (evt) {
  14506. var canvasRect = this._engine.getRenderingCanvasClientRect();
  14507. this._pointerX = evt.clientX - canvasRect.left;
  14508. this._pointerY = evt.clientY - canvasRect.top;
  14509. this._unTranslatedPointerX = this._pointerX;
  14510. this._unTranslatedPointerY = this._pointerY;
  14511. if (this.cameraToUseForPointers) {
  14512. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  14513. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  14514. }
  14515. };
  14516. // Pointers handling
  14517. /**
  14518. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  14519. * @param attachUp defines if you want to attach events to pointerup
  14520. * @param attachDown defines if you want to attach events to pointerdown
  14521. * @param attachMove defines if you want to attach events to pointermove
  14522. */
  14523. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  14524. var _this = this;
  14525. if (attachUp === void 0) { attachUp = true; }
  14526. if (attachDown === void 0) { attachDown = true; }
  14527. if (attachMove === void 0) { attachMove = true; }
  14528. var spritePredicate = function (sprite) {
  14529. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  14530. };
  14531. this._onPointerMove = function (evt) {
  14532. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14533. return;
  14534. }
  14535. var canvas = _this._engine.getRenderingCanvas();
  14536. _this._updatePointerPosition(evt);
  14537. if (!_this.pointerMovePredicate) {
  14538. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  14539. }
  14540. // Meshes
  14541. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  14542. if (pickResult.hit && pickResult.pickedMesh) {
  14543. _this.setPointerOverSprite(null);
  14544. _this.setPointerOverMesh(pickResult.pickedMesh);
  14545. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  14546. canvas.style.cursor = "pointer";
  14547. }
  14548. else {
  14549. canvas.style.cursor = "";
  14550. }
  14551. }
  14552. else {
  14553. _this.setPointerOverMesh(null);
  14554. // Sprites
  14555. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14556. if (pickResult.hit && pickResult.pickedSprite) {
  14557. canvas.style.cursor = "pointer";
  14558. _this.setPointerOverSprite(pickResult.pickedSprite);
  14559. }
  14560. else {
  14561. _this.setPointerOverSprite(null);
  14562. // Restore pointer
  14563. canvas.style.cursor = "";
  14564. }
  14565. }
  14566. if (_this.onPointerMove) {
  14567. _this.onPointerMove(evt, pickResult);
  14568. }
  14569. if (_this.onPointerObservable.hasObservers()) {
  14570. console.log(evt.type);
  14571. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  14572. var pi = new PointerInfo(type, evt, pickResult);
  14573. _this.onPointerObservable.notifyObservers(pi, type);
  14574. }
  14575. };
  14576. this._onPointerDown = function (evt) {
  14577. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14578. return;
  14579. }
  14580. _this._updatePointerPosition(evt);
  14581. _this._startingPointerPosition.x = _this._pointerX;
  14582. _this._startingPointerPosition.y = _this._pointerY;
  14583. _this._startingPointerTime = new Date().getTime();
  14584. if (!_this.pointerDownPredicate) {
  14585. _this.pointerDownPredicate = function (mesh) {
  14586. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  14587. };
  14588. }
  14589. // Meshes
  14590. _this._pickedDownMesh = null;
  14591. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  14592. if (pickResult.hit && pickResult.pickedMesh) {
  14593. if (pickResult.pickedMesh.actionManager) {
  14594. _this._pickedDownMesh = pickResult.pickedMesh;
  14595. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  14596. switch (evt.button) {
  14597. case 0:
  14598. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14599. break;
  14600. case 1:
  14601. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14602. break;
  14603. case 2:
  14604. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14605. break;
  14606. }
  14607. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14608. }
  14609. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  14610. var that = _this;
  14611. window.setTimeout(function () {
  14612. 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);
  14613. if (pickResult.hit && pickResult.pickedMesh) {
  14614. if (pickResult.pickedMesh.actionManager) {
  14615. 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)) {
  14616. that._startingPointerTime = 0;
  14617. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14618. }
  14619. }
  14620. }
  14621. }, BABYLON.ActionManager.LongPressDelay);
  14622. }
  14623. }
  14624. }
  14625. if (_this.onPointerDown) {
  14626. _this.onPointerDown(evt, pickResult);
  14627. }
  14628. if (_this.onPointerObservable.hasObservers()) {
  14629. var type = PointerEventTypes.POINTERDOWN;
  14630. var pi = new PointerInfo(type, evt, pickResult);
  14631. _this.onPointerObservable.notifyObservers(pi, type);
  14632. }
  14633. // Sprites
  14634. _this._pickedDownSprite = null;
  14635. if (_this.spriteManagers.length > 0) {
  14636. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14637. if (pickResult.hit && pickResult.pickedSprite) {
  14638. if (pickResult.pickedSprite.actionManager) {
  14639. _this._pickedDownSprite = pickResult.pickedSprite;
  14640. switch (evt.button) {
  14641. case 0:
  14642. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14643. break;
  14644. case 1:
  14645. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14646. break;
  14647. case 2:
  14648. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14649. break;
  14650. }
  14651. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14652. }
  14653. }
  14654. }
  14655. };
  14656. this._onPointerUp = function (evt) {
  14657. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14658. return;
  14659. }
  14660. _this._updatePointerPosition(evt);
  14661. if (!_this.pointerUpPredicate) {
  14662. _this.pointerUpPredicate = function (mesh) {
  14663. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  14664. };
  14665. }
  14666. // Meshes
  14667. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  14668. if (pickResult.hit && pickResult.pickedMesh) {
  14669. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  14670. if (_this.onPointerPick) {
  14671. _this.onPointerPick(evt, pickResult);
  14672. }
  14673. if (_this.onPointerObservable.hasObservers()) {
  14674. var type = PointerEventTypes.POINTERPICK;
  14675. var pi = new PointerInfo(type, evt, pickResult);
  14676. _this.onPointerObservable.notifyObservers(pi, type);
  14677. }
  14678. }
  14679. if (pickResult.pickedMesh.actionManager) {
  14680. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14681. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  14682. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14683. }
  14684. }
  14685. }
  14686. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  14687. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  14688. }
  14689. if (_this.onPointerUp) {
  14690. _this.onPointerUp(evt, pickResult);
  14691. }
  14692. if (_this.onPointerObservable.hasObservers()) {
  14693. var type = PointerEventTypes.POINTERUP;
  14694. var pi = new PointerInfo(type, evt, pickResult);
  14695. _this.onPointerObservable.notifyObservers(pi, type);
  14696. }
  14697. _this._startingPointerTime = 0;
  14698. // Sprites
  14699. if (_this.spriteManagers.length > 0) {
  14700. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14701. if (pickResult.hit && pickResult.pickedSprite) {
  14702. if (pickResult.pickedSprite.actionManager) {
  14703. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14704. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  14705. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14706. }
  14707. }
  14708. }
  14709. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  14710. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  14711. }
  14712. }
  14713. };
  14714. this._onKeyDown = function (evt) {
  14715. if (_this.actionManager) {
  14716. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14717. }
  14718. };
  14719. this._onKeyUp = function (evt) {
  14720. if (_this.actionManager) {
  14721. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14722. }
  14723. };
  14724. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14725. if (attachMove) {
  14726. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  14727. // Wheel
  14728. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  14729. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  14730. }
  14731. if (attachDown) {
  14732. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  14733. }
  14734. if (attachUp) {
  14735. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  14736. }
  14737. BABYLON.Tools.RegisterTopRootEvents([
  14738. { name: "keydown", handler: this._onKeyDown },
  14739. { name: "keyup", handler: this._onKeyUp }
  14740. ]);
  14741. };
  14742. Scene.prototype.detachControl = function () {
  14743. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14744. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  14745. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  14746. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  14747. // Wheel
  14748. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  14749. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  14750. BABYLON.Tools.UnregisterTopRootEvents([
  14751. { name: "keydown", handler: this._onKeyDown },
  14752. { name: "keyup", handler: this._onKeyUp }
  14753. ]);
  14754. };
  14755. // Ready
  14756. Scene.prototype.isReady = function () {
  14757. if (this._pendingData.length > 0) {
  14758. return false;
  14759. }
  14760. var index;
  14761. for (index = 0; index < this._geometries.length; index++) {
  14762. var geometry = this._geometries[index];
  14763. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14764. return false;
  14765. }
  14766. }
  14767. for (index = 0; index < this.meshes.length; index++) {
  14768. var mesh = this.meshes[index];
  14769. if (!mesh.isReady()) {
  14770. return false;
  14771. }
  14772. var mat = mesh.material;
  14773. if (mat) {
  14774. if (!mat.isReady(mesh)) {
  14775. return false;
  14776. }
  14777. }
  14778. }
  14779. return true;
  14780. };
  14781. Scene.prototype.resetCachedMaterial = function () {
  14782. this._cachedMaterial = null;
  14783. };
  14784. Scene.prototype.registerBeforeRender = function (func) {
  14785. this.onBeforeRenderObservable.add(func);
  14786. };
  14787. Scene.prototype.unregisterBeforeRender = function (func) {
  14788. this.onBeforeRenderObservable.removeCallback(func);
  14789. };
  14790. Scene.prototype.registerAfterRender = function (func) {
  14791. this.onAfterRenderObservable.add(func);
  14792. };
  14793. Scene.prototype.unregisterAfterRender = function (func) {
  14794. this.onAfterRenderObservable.removeCallback(func);
  14795. };
  14796. Scene.prototype._addPendingData = function (data) {
  14797. this._pendingData.push(data);
  14798. };
  14799. Scene.prototype._removePendingData = function (data) {
  14800. var index = this._pendingData.indexOf(data);
  14801. if (index !== -1) {
  14802. this._pendingData.splice(index, 1);
  14803. }
  14804. };
  14805. Scene.prototype.getWaitingItemsCount = function () {
  14806. return this._pendingData.length;
  14807. };
  14808. /**
  14809. * Registers a function to be executed when the scene is ready.
  14810. * @param {Function} func - the function to be executed.
  14811. */
  14812. Scene.prototype.executeWhenReady = function (func) {
  14813. var _this = this;
  14814. this.onReadyObservable.add(func);
  14815. if (this._executeWhenReadyTimeoutId !== -1) {
  14816. return;
  14817. }
  14818. this._executeWhenReadyTimeoutId = setTimeout(function () {
  14819. _this._checkIsReady();
  14820. }, 150);
  14821. };
  14822. Scene.prototype._checkIsReady = function () {
  14823. var _this = this;
  14824. if (this.isReady()) {
  14825. this.onReadyObservable.notifyObservers(this);
  14826. this.onReadyObservable.clear();
  14827. this._executeWhenReadyTimeoutId = -1;
  14828. return;
  14829. }
  14830. this._executeWhenReadyTimeoutId = setTimeout(function () {
  14831. _this._checkIsReady();
  14832. }, 150);
  14833. };
  14834. // Animations
  14835. /**
  14836. * Will start the animation sequence of a given target
  14837. * @param target - the target
  14838. * @param {number} from - from which frame should animation start
  14839. * @param {number} to - till which frame should animation run.
  14840. * @param {boolean} [loop] - should the animation loop
  14841. * @param {number} [speedRatio] - the speed in which to run the animation
  14842. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  14843. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  14844. * @return {BABYLON.Animatable} the animatable object created for this animation
  14845. * @see BABYLON.Animatable
  14846. * @see http://doc.babylonjs.com/page.php?p=22081
  14847. */
  14848. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  14849. if (speedRatio === void 0) { speedRatio = 1.0; }
  14850. this.stopAnimation(target);
  14851. if (!animatable) {
  14852. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  14853. }
  14854. // Local animations
  14855. if (target.animations) {
  14856. animatable.appendAnimations(target, target.animations);
  14857. }
  14858. // Children animations
  14859. if (target.getAnimatables) {
  14860. var animatables = target.getAnimatables();
  14861. for (var index = 0; index < animatables.length; index++) {
  14862. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  14863. }
  14864. }
  14865. animatable.reset();
  14866. return animatable;
  14867. };
  14868. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  14869. if (speedRatio === undefined) {
  14870. speedRatio = 1.0;
  14871. }
  14872. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  14873. return animatable;
  14874. };
  14875. Scene.prototype.getAnimatableByTarget = function (target) {
  14876. for (var index = 0; index < this._activeAnimatables.length; index++) {
  14877. if (this._activeAnimatables[index].target === target) {
  14878. return this._activeAnimatables[index];
  14879. }
  14880. }
  14881. return null;
  14882. };
  14883. Object.defineProperty(Scene.prototype, "Animatables", {
  14884. get: function () {
  14885. return this._activeAnimatables;
  14886. },
  14887. enumerable: true,
  14888. configurable: true
  14889. });
  14890. /**
  14891. * Will stop the animation of the given target
  14892. * @param target - the target
  14893. * @see beginAnimation
  14894. */
  14895. Scene.prototype.stopAnimation = function (target) {
  14896. var animatable = this.getAnimatableByTarget(target);
  14897. if (animatable) {
  14898. animatable.stop();
  14899. }
  14900. };
  14901. Scene.prototype._animate = function () {
  14902. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  14903. return;
  14904. }
  14905. if (!this._animationStartDate) {
  14906. if (this._pendingData.length > 0) {
  14907. return;
  14908. }
  14909. this._animationStartDate = BABYLON.Tools.Now;
  14910. }
  14911. // Getting time
  14912. var now = BABYLON.Tools.Now;
  14913. var delay = now - this._animationStartDate;
  14914. for (var index = 0; index < this._activeAnimatables.length; index++) {
  14915. this._activeAnimatables[index]._animate(delay);
  14916. }
  14917. };
  14918. // Matrix
  14919. Scene.prototype.getViewMatrix = function () {
  14920. return this._viewMatrix;
  14921. };
  14922. Scene.prototype.getProjectionMatrix = function () {
  14923. return this._projectionMatrix;
  14924. };
  14925. Scene.prototype.getTransformMatrix = function () {
  14926. return this._transformMatrix;
  14927. };
  14928. Scene.prototype.setTransformMatrix = function (view, projection) {
  14929. this._viewMatrix = view;
  14930. this._projectionMatrix = projection;
  14931. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14932. };
  14933. // Methods
  14934. Scene.prototype.addMesh = function (newMesh) {
  14935. newMesh.uniqueId = this._uniqueIdCounter++;
  14936. var position = this.meshes.push(newMesh);
  14937. //notify the collision coordinator
  14938. this.collisionCoordinator.onMeshAdded(newMesh);
  14939. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  14940. };
  14941. Scene.prototype.removeMesh = function (toRemove) {
  14942. var index = this.meshes.indexOf(toRemove);
  14943. if (index !== -1) {
  14944. // Remove from the scene if mesh found
  14945. this.meshes.splice(index, 1);
  14946. }
  14947. //notify the collision coordinator
  14948. this.collisionCoordinator.onMeshRemoved(toRemove);
  14949. this.onMeshRemovedObservable.notifyObservers(toRemove);
  14950. return index;
  14951. };
  14952. Scene.prototype.removeSkeleton = function (toRemove) {
  14953. var index = this.skeletons.indexOf(toRemove);
  14954. if (index !== -1) {
  14955. // Remove from the scene if mesh found
  14956. this.skeletons.splice(index, 1);
  14957. }
  14958. return index;
  14959. };
  14960. Scene.prototype.removeLight = function (toRemove) {
  14961. var index = this.lights.indexOf(toRemove);
  14962. if (index !== -1) {
  14963. // Remove from the scene if mesh found
  14964. this.lights.splice(index, 1);
  14965. }
  14966. this.onLightRemovedObservable.notifyObservers(toRemove);
  14967. return index;
  14968. };
  14969. Scene.prototype.removeCamera = function (toRemove) {
  14970. var index = this.cameras.indexOf(toRemove);
  14971. if (index !== -1) {
  14972. // Remove from the scene if mesh found
  14973. this.cameras.splice(index, 1);
  14974. }
  14975. // Remove from activeCameras
  14976. var index2 = this.activeCameras.indexOf(toRemove);
  14977. if (index2 !== -1) {
  14978. // Remove from the scene if mesh found
  14979. this.activeCameras.splice(index2, 1);
  14980. }
  14981. // Reset the activeCamera
  14982. if (this.activeCamera === toRemove) {
  14983. if (this.cameras.length > 0) {
  14984. this.activeCamera = this.cameras[0];
  14985. }
  14986. else {
  14987. this.activeCamera = null;
  14988. }
  14989. }
  14990. this.onCameraRemovedObservable.notifyObservers(toRemove);
  14991. return index;
  14992. };
  14993. Scene.prototype.addLight = function (newLight) {
  14994. newLight.uniqueId = this._uniqueIdCounter++;
  14995. var position = this.lights.push(newLight);
  14996. this.onNewLightAddedObservable.notifyObservers(newLight);
  14997. };
  14998. Scene.prototype.addCamera = function (newCamera) {
  14999. newCamera.uniqueId = this._uniqueIdCounter++;
  15000. var position = this.cameras.push(newCamera);
  15001. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  15002. };
  15003. /**
  15004. * Switch active camera
  15005. * @param {Camera} newCamera - new active camera
  15006. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  15007. */
  15008. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  15009. if (attachControl === void 0) { attachControl = true; }
  15010. var canvas = this._engine.getRenderingCanvas();
  15011. this.activeCamera.detachControl(canvas);
  15012. this.activeCamera = newCamera;
  15013. if (attachControl) {
  15014. newCamera.attachControl(canvas);
  15015. }
  15016. };
  15017. /**
  15018. * sets the active camera of the scene using its ID
  15019. * @param {string} id - the camera's ID
  15020. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15021. * @see activeCamera
  15022. */
  15023. Scene.prototype.setActiveCameraByID = function (id) {
  15024. var camera = this.getCameraByID(id);
  15025. if (camera) {
  15026. this.activeCamera = camera;
  15027. return camera;
  15028. }
  15029. return null;
  15030. };
  15031. /**
  15032. * sets the active camera of the scene using its name
  15033. * @param {string} name - the camera's name
  15034. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15035. * @see activeCamera
  15036. */
  15037. Scene.prototype.setActiveCameraByName = function (name) {
  15038. var camera = this.getCameraByName(name);
  15039. if (camera) {
  15040. this.activeCamera = camera;
  15041. return camera;
  15042. }
  15043. return null;
  15044. };
  15045. /**
  15046. * get a material using its id
  15047. * @param {string} the material's ID
  15048. * @return {BABYLON.Material|null} the material or null if none found.
  15049. */
  15050. Scene.prototype.getMaterialByID = function (id) {
  15051. for (var index = 0; index < this.materials.length; index++) {
  15052. if (this.materials[index].id === id) {
  15053. return this.materials[index];
  15054. }
  15055. }
  15056. return null;
  15057. };
  15058. /**
  15059. * get a material using its name
  15060. * @param {string} the material's name
  15061. * @return {BABYLON.Material|null} the material or null if none found.
  15062. */
  15063. Scene.prototype.getMaterialByName = function (name) {
  15064. for (var index = 0; index < this.materials.length; index++) {
  15065. if (this.materials[index].name === name) {
  15066. return this.materials[index];
  15067. }
  15068. }
  15069. return null;
  15070. };
  15071. Scene.prototype.getLensFlareSystemByName = function (name) {
  15072. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15073. if (this.lensFlareSystems[index].name === name) {
  15074. return this.lensFlareSystems[index];
  15075. }
  15076. }
  15077. return null;
  15078. };
  15079. Scene.prototype.getLensFlareSystemByID = function (id) {
  15080. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15081. if (this.lensFlareSystems[index].id === id) {
  15082. return this.lensFlareSystems[index];
  15083. }
  15084. }
  15085. return null;
  15086. };
  15087. Scene.prototype.getCameraByID = function (id) {
  15088. for (var index = 0; index < this.cameras.length; index++) {
  15089. if (this.cameras[index].id === id) {
  15090. return this.cameras[index];
  15091. }
  15092. }
  15093. return null;
  15094. };
  15095. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  15096. for (var index = 0; index < this.cameras.length; index++) {
  15097. if (this.cameras[index].uniqueId === uniqueId) {
  15098. return this.cameras[index];
  15099. }
  15100. }
  15101. return null;
  15102. };
  15103. /**
  15104. * get a camera using its name
  15105. * @param {string} the camera's name
  15106. * @return {BABYLON.Camera|null} the camera or null if none found.
  15107. */
  15108. Scene.prototype.getCameraByName = function (name) {
  15109. for (var index = 0; index < this.cameras.length; index++) {
  15110. if (this.cameras[index].name === name) {
  15111. return this.cameras[index];
  15112. }
  15113. }
  15114. return null;
  15115. };
  15116. /**
  15117. * get a bone using its id
  15118. * @param {string} the bone's id
  15119. * @return {BABYLON.Bone|null} the bone or null if not found
  15120. */
  15121. Scene.prototype.getBoneByID = function (id) {
  15122. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15123. var skeleton = this.skeletons[skeletonIndex];
  15124. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15125. if (skeleton.bones[boneIndex].id === id) {
  15126. return skeleton.bones[boneIndex];
  15127. }
  15128. }
  15129. }
  15130. return null;
  15131. };
  15132. /**
  15133. * get a bone using its id
  15134. * @param {string} the bone's name
  15135. * @return {BABYLON.Bone|null} the bone or null if not found
  15136. */
  15137. Scene.prototype.getBoneByName = function (name) {
  15138. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15139. var skeleton = this.skeletons[skeletonIndex];
  15140. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15141. if (skeleton.bones[boneIndex].name === name) {
  15142. return skeleton.bones[boneIndex];
  15143. }
  15144. }
  15145. }
  15146. return null;
  15147. };
  15148. /**
  15149. * get a light node using its name
  15150. * @param {string} the light's name
  15151. * @return {BABYLON.Light|null} the light or null if none found.
  15152. */
  15153. Scene.prototype.getLightByName = function (name) {
  15154. for (var index = 0; index < this.lights.length; index++) {
  15155. if (this.lights[index].name === name) {
  15156. return this.lights[index];
  15157. }
  15158. }
  15159. return null;
  15160. };
  15161. /**
  15162. * get a light node using its ID
  15163. * @param {string} the light's id
  15164. * @return {BABYLON.Light|null} the light or null if none found.
  15165. */
  15166. Scene.prototype.getLightByID = function (id) {
  15167. for (var index = 0; index < this.lights.length; index++) {
  15168. if (this.lights[index].id === id) {
  15169. return this.lights[index];
  15170. }
  15171. }
  15172. return null;
  15173. };
  15174. /**
  15175. * get a light node using its scene-generated unique ID
  15176. * @param {number} the light's unique id
  15177. * @return {BABYLON.Light|null} the light or null if none found.
  15178. */
  15179. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  15180. for (var index = 0; index < this.lights.length; index++) {
  15181. if (this.lights[index].uniqueId === uniqueId) {
  15182. return this.lights[index];
  15183. }
  15184. }
  15185. return null;
  15186. };
  15187. /**
  15188. * get a particle system by id
  15189. * @param id {number} the particle system id
  15190. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  15191. */
  15192. Scene.prototype.getParticleSystemByID = function (id) {
  15193. for (var index = 0; index < this.particleSystems.length; index++) {
  15194. if (this.particleSystems[index].id === id) {
  15195. return this.particleSystems[index];
  15196. }
  15197. }
  15198. return null;
  15199. };
  15200. /**
  15201. * get a geometry using its ID
  15202. * @param {string} the geometry's id
  15203. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  15204. */
  15205. Scene.prototype.getGeometryByID = function (id) {
  15206. for (var index = 0; index < this._geometries.length; index++) {
  15207. if (this._geometries[index].id === id) {
  15208. return this._geometries[index];
  15209. }
  15210. }
  15211. return null;
  15212. };
  15213. /**
  15214. * add a new geometry to this scene.
  15215. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  15216. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  15217. * @return {boolean} was the geometry added or not
  15218. */
  15219. Scene.prototype.pushGeometry = function (geometry, force) {
  15220. if (!force && this.getGeometryByID(geometry.id)) {
  15221. return false;
  15222. }
  15223. this._geometries.push(geometry);
  15224. //notify the collision coordinator
  15225. this.collisionCoordinator.onGeometryAdded(geometry);
  15226. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  15227. return true;
  15228. };
  15229. /**
  15230. * Removes an existing geometry
  15231. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  15232. * @return {boolean} was the geometry removed or not
  15233. */
  15234. Scene.prototype.removeGeometry = function (geometry) {
  15235. var index = this._geometries.indexOf(geometry);
  15236. if (index > -1) {
  15237. this._geometries.splice(index, 1);
  15238. //notify the collision coordinator
  15239. this.collisionCoordinator.onGeometryDeleted(geometry);
  15240. this.onGeometryRemovedObservable.notifyObservers(geometry);
  15241. return true;
  15242. }
  15243. return false;
  15244. };
  15245. Scene.prototype.getGeometries = function () {
  15246. return this._geometries;
  15247. };
  15248. /**
  15249. * Get the first added mesh found of a given ID
  15250. * @param {string} id - the id to search for
  15251. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15252. */
  15253. Scene.prototype.getMeshByID = function (id) {
  15254. for (var index = 0; index < this.meshes.length; index++) {
  15255. if (this.meshes[index].id === id) {
  15256. return this.meshes[index];
  15257. }
  15258. }
  15259. return null;
  15260. };
  15261. /**
  15262. * Get a mesh with its auto-generated unique id
  15263. * @param {number} uniqueId - the unique id to search for
  15264. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15265. */
  15266. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  15267. for (var index = 0; index < this.meshes.length; index++) {
  15268. if (this.meshes[index].uniqueId === uniqueId) {
  15269. return this.meshes[index];
  15270. }
  15271. }
  15272. return null;
  15273. };
  15274. /**
  15275. * Get a the last added mesh found of a given ID
  15276. * @param {string} id - the id to search for
  15277. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15278. */
  15279. Scene.prototype.getLastMeshByID = function (id) {
  15280. for (var index = this.meshes.length - 1; index >= 0; index--) {
  15281. if (this.meshes[index].id === id) {
  15282. return this.meshes[index];
  15283. }
  15284. }
  15285. return null;
  15286. };
  15287. /**
  15288. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  15289. * @param {string} id - the id to search for
  15290. * @return {BABYLON.Node|null} the node found or null if not found at all.
  15291. */
  15292. Scene.prototype.getLastEntryByID = function (id) {
  15293. var index;
  15294. for (index = this.meshes.length - 1; index >= 0; index--) {
  15295. if (this.meshes[index].id === id) {
  15296. return this.meshes[index];
  15297. }
  15298. }
  15299. for (index = this.cameras.length - 1; index >= 0; index--) {
  15300. if (this.cameras[index].id === id) {
  15301. return this.cameras[index];
  15302. }
  15303. }
  15304. for (index = this.lights.length - 1; index >= 0; index--) {
  15305. if (this.lights[index].id === id) {
  15306. return this.lights[index];
  15307. }
  15308. }
  15309. return null;
  15310. };
  15311. Scene.prototype.getNodeByID = function (id) {
  15312. var mesh = this.getMeshByID(id);
  15313. if (mesh) {
  15314. return mesh;
  15315. }
  15316. var light = this.getLightByID(id);
  15317. if (light) {
  15318. return light;
  15319. }
  15320. var camera = this.getCameraByID(id);
  15321. if (camera) {
  15322. return camera;
  15323. }
  15324. var bone = this.getBoneByID(id);
  15325. return bone;
  15326. };
  15327. Scene.prototype.getNodeByName = function (name) {
  15328. var mesh = this.getMeshByName(name);
  15329. if (mesh) {
  15330. return mesh;
  15331. }
  15332. var light = this.getLightByName(name);
  15333. if (light) {
  15334. return light;
  15335. }
  15336. var camera = this.getCameraByName(name);
  15337. if (camera) {
  15338. return camera;
  15339. }
  15340. var bone = this.getBoneByName(name);
  15341. return bone;
  15342. };
  15343. Scene.prototype.getMeshByName = function (name) {
  15344. for (var index = 0; index < this.meshes.length; index++) {
  15345. if (this.meshes[index].name === name) {
  15346. return this.meshes[index];
  15347. }
  15348. }
  15349. return null;
  15350. };
  15351. Scene.prototype.getSoundByName = function (name) {
  15352. var index;
  15353. if (BABYLON.AudioEngine) {
  15354. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  15355. if (this.mainSoundTrack.soundCollection[index].name === name) {
  15356. return this.mainSoundTrack.soundCollection[index];
  15357. }
  15358. }
  15359. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  15360. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  15361. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  15362. return this.soundTracks[sdIndex].soundCollection[index];
  15363. }
  15364. }
  15365. }
  15366. }
  15367. return null;
  15368. };
  15369. Scene.prototype.getLastSkeletonByID = function (id) {
  15370. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  15371. if (this.skeletons[index].id === id) {
  15372. return this.skeletons[index];
  15373. }
  15374. }
  15375. return null;
  15376. };
  15377. Scene.prototype.getSkeletonById = function (id) {
  15378. for (var index = 0; index < this.skeletons.length; index++) {
  15379. if (this.skeletons[index].id === id) {
  15380. return this.skeletons[index];
  15381. }
  15382. }
  15383. return null;
  15384. };
  15385. Scene.prototype.getSkeletonByName = function (name) {
  15386. for (var index = 0; index < this.skeletons.length; index++) {
  15387. if (this.skeletons[index].name === name) {
  15388. return this.skeletons[index];
  15389. }
  15390. }
  15391. return null;
  15392. };
  15393. Scene.prototype.isActiveMesh = function (mesh) {
  15394. return (this._activeMeshes.indexOf(mesh) !== -1);
  15395. };
  15396. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  15397. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  15398. var material = subMesh.getMaterial();
  15399. if (mesh.showSubMeshesBoundingBox) {
  15400. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  15401. }
  15402. if (material) {
  15403. // Render targets
  15404. if (material.getRenderTargetTextures) {
  15405. if (this._processedMaterials.indexOf(material) === -1) {
  15406. this._processedMaterials.push(material);
  15407. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  15408. }
  15409. }
  15410. // Dispatch
  15411. this._activeIndices += subMesh.indexCount;
  15412. this._renderingManager.dispatch(subMesh);
  15413. }
  15414. }
  15415. };
  15416. Scene.prototype._isInIntermediateRendering = function () {
  15417. return this._intermediateRendering;
  15418. };
  15419. Scene.prototype._evaluateActiveMeshes = function () {
  15420. this.activeCamera._activeMeshes.reset();
  15421. this._activeMeshes.reset();
  15422. this._renderingManager.reset();
  15423. this._processedMaterials.reset();
  15424. this._activeParticleSystems.reset();
  15425. this._activeSkeletons.reset();
  15426. this._softwareSkinnedMeshes.reset();
  15427. this._boundingBoxRenderer.reset();
  15428. this._edgesRenderers.reset();
  15429. if (!this._frustumPlanes) {
  15430. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15431. }
  15432. else {
  15433. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15434. }
  15435. // Meshes
  15436. var meshes;
  15437. var len;
  15438. if (this._selectionOctree) {
  15439. var selection = this._selectionOctree.select(this._frustumPlanes);
  15440. meshes = selection.data;
  15441. len = selection.length;
  15442. }
  15443. else {
  15444. len = this.meshes.length;
  15445. meshes = this.meshes;
  15446. }
  15447. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  15448. var mesh = meshes[meshIndex];
  15449. if (mesh.isBlocked) {
  15450. continue;
  15451. }
  15452. this._totalVertices += mesh.getTotalVertices();
  15453. if (!mesh.isReady() || !mesh.isEnabled()) {
  15454. continue;
  15455. }
  15456. mesh.computeWorldMatrix();
  15457. // Intersections
  15458. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  15459. this._meshesForIntersections.pushNoDuplicate(mesh);
  15460. }
  15461. // Switch to current LOD
  15462. var meshLOD = mesh.getLOD(this.activeCamera);
  15463. if (!meshLOD) {
  15464. continue;
  15465. }
  15466. mesh._preActivate();
  15467. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  15468. this._activeMeshes.push(mesh);
  15469. this.activeCamera._activeMeshes.push(mesh);
  15470. mesh._activate(this._renderId);
  15471. this._activeMesh(meshLOD);
  15472. }
  15473. }
  15474. // Particle systems
  15475. var beforeParticlesDate = BABYLON.Tools.Now;
  15476. if (this.particlesEnabled) {
  15477. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  15478. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  15479. var particleSystem = this.particleSystems[particleIndex];
  15480. if (!particleSystem.isStarted()) {
  15481. continue;
  15482. }
  15483. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  15484. this._activeParticleSystems.push(particleSystem);
  15485. particleSystem.animate();
  15486. }
  15487. }
  15488. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  15489. }
  15490. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  15491. };
  15492. Scene.prototype._activeMesh = function (mesh) {
  15493. if (mesh.skeleton && this.skeletonsEnabled) {
  15494. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  15495. if (!mesh.computeBonesUsingShaders) {
  15496. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  15497. }
  15498. }
  15499. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  15500. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  15501. }
  15502. if (mesh._edgesRenderer) {
  15503. this._edgesRenderers.push(mesh._edgesRenderer);
  15504. }
  15505. if (mesh && mesh.subMeshes) {
  15506. // Submeshes Octrees
  15507. var len;
  15508. var subMeshes;
  15509. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  15510. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  15511. len = intersections.length;
  15512. subMeshes = intersections.data;
  15513. }
  15514. else {
  15515. subMeshes = mesh.subMeshes;
  15516. len = subMeshes.length;
  15517. }
  15518. for (var subIndex = 0; subIndex < len; subIndex++) {
  15519. var subMesh = subMeshes[subIndex];
  15520. this._evaluateSubMesh(subMesh, mesh);
  15521. }
  15522. }
  15523. };
  15524. Scene.prototype.updateTransformMatrix = function (force) {
  15525. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  15526. };
  15527. Scene.prototype._renderForCamera = function (camera) {
  15528. var engine = this._engine;
  15529. this.activeCamera = camera;
  15530. if (!this.activeCamera)
  15531. throw new Error("Active camera not set");
  15532. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  15533. // Viewport
  15534. engine.setViewport(this.activeCamera.viewport);
  15535. // Camera
  15536. this.resetCachedMaterial();
  15537. this._renderId++;
  15538. this.updateTransformMatrix();
  15539. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  15540. // Meshes
  15541. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  15542. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  15543. this._evaluateActiveMeshes();
  15544. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  15545. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  15546. // Skeletons
  15547. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  15548. var skeleton = this._activeSkeletons.data[skeletonIndex];
  15549. skeleton.prepare();
  15550. }
  15551. // Software skinning
  15552. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  15553. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  15554. mesh.applySkeleton(mesh.skeleton);
  15555. }
  15556. // Render targets
  15557. var beforeRenderTargetDate = BABYLON.Tools.Now;
  15558. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  15559. this._intermediateRendering = true;
  15560. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  15561. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  15562. var renderTarget = this._renderTargets.data[renderIndex];
  15563. if (renderTarget._shouldRender()) {
  15564. this._renderId++;
  15565. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  15566. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  15567. }
  15568. }
  15569. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  15570. this._intermediateRendering = false;
  15571. this._renderId++;
  15572. engine.restoreDefaultFramebuffer(); // Restore back buffer
  15573. }
  15574. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  15575. // Prepare Frame
  15576. this.postProcessManager._prepareFrame();
  15577. var beforeRenderDate = BABYLON.Tools.Now;
  15578. // Backgrounds
  15579. var layerIndex;
  15580. var layer;
  15581. if (this.layers.length) {
  15582. engine.setDepthBuffer(false);
  15583. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  15584. layer = this.layers[layerIndex];
  15585. if (layer.isBackground) {
  15586. layer.render();
  15587. }
  15588. }
  15589. engine.setDepthBuffer(true);
  15590. }
  15591. // Render
  15592. BABYLON.Tools.StartPerformanceCounter("Main render");
  15593. this._renderingManager.render(null, null, true, true);
  15594. BABYLON.Tools.EndPerformanceCounter("Main render");
  15595. // Bounding boxes
  15596. this._boundingBoxRenderer.render();
  15597. // Edges
  15598. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15599. this._edgesRenderers.data[edgesRendererIndex].render();
  15600. }
  15601. // Lens flares
  15602. if (this.lensFlaresEnabled) {
  15603. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  15604. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  15605. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  15606. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  15607. lensFlareSystem.render();
  15608. }
  15609. }
  15610. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  15611. }
  15612. // Foregrounds
  15613. if (this.layers.length) {
  15614. engine.setDepthBuffer(false);
  15615. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  15616. layer = this.layers[layerIndex];
  15617. if (!layer.isBackground) {
  15618. layer.render();
  15619. }
  15620. }
  15621. engine.setDepthBuffer(true);
  15622. }
  15623. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  15624. // Finalize frame
  15625. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  15626. // Update camera
  15627. this.activeCamera._updateFromScene();
  15628. // Reset some special arrays
  15629. this._renderTargets.reset();
  15630. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  15631. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  15632. };
  15633. Scene.prototype._processSubCameras = function (camera) {
  15634. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  15635. this._renderForCamera(camera);
  15636. return;
  15637. }
  15638. // rig cameras
  15639. for (var index = 0; index < camera._rigCameras.length; index++) {
  15640. this._renderForCamera(camera._rigCameras[index]);
  15641. }
  15642. this.activeCamera = camera;
  15643. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  15644. // Update camera
  15645. this.activeCamera._updateFromScene();
  15646. };
  15647. Scene.prototype._checkIntersections = function () {
  15648. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  15649. var sourceMesh = this._meshesForIntersections.data[index];
  15650. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  15651. var action = sourceMesh.actionManager.actions[actionIndex];
  15652. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15653. var parameters = action.getTriggerParameter();
  15654. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  15655. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  15656. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  15657. if (areIntersecting && currentIntersectionInProgress === -1) {
  15658. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  15659. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  15660. sourceMesh._intersectionsInProgress.push(otherMesh);
  15661. }
  15662. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15663. sourceMesh._intersectionsInProgress.push(otherMesh);
  15664. }
  15665. }
  15666. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  15667. //They intersected, and now they don't.
  15668. //is this trigger an exit trigger? execute an event.
  15669. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15670. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  15671. }
  15672. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  15673. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15674. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  15675. }
  15676. }
  15677. }
  15678. }
  15679. }
  15680. };
  15681. Scene.prototype.render = function () {
  15682. var startDate = BABYLON.Tools.Now;
  15683. this._particlesDuration = 0;
  15684. this._spritesDuration = 0;
  15685. this._activeParticles = 0;
  15686. this._renderDuration = 0;
  15687. this._renderTargetsDuration = 0;
  15688. this._evaluateActiveMeshesDuration = 0;
  15689. this._totalVertices = 0;
  15690. this._activeIndices = 0;
  15691. this._activeBones = 0;
  15692. this.getEngine().resetDrawCalls();
  15693. this._meshesForIntersections.reset();
  15694. this.resetCachedMaterial();
  15695. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  15696. // Actions
  15697. if (this.actionManager) {
  15698. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  15699. }
  15700. //Simplification Queue
  15701. if (this.simplificationQueue && !this.simplificationQueue.running) {
  15702. this.simplificationQueue.executeNext();
  15703. }
  15704. // Animations
  15705. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  15706. this._animationRatio = deltaTime * (60.0 / 1000.0);
  15707. this._animate();
  15708. // Physics
  15709. if (this._physicsEngine) {
  15710. BABYLON.Tools.StartPerformanceCounter("Physics");
  15711. this._physicsEngine._step(deltaTime / 1000.0);
  15712. BABYLON.Tools.EndPerformanceCounter("Physics");
  15713. }
  15714. // Before render
  15715. this.onBeforeRenderObservable.notifyObservers(this);
  15716. // Customs render targets
  15717. var beforeRenderTargetDate = BABYLON.Tools.Now;
  15718. var engine = this.getEngine();
  15719. var currentActiveCamera = this.activeCamera;
  15720. if (this.renderTargetsEnabled) {
  15721. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15722. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  15723. var renderTarget = this.customRenderTargets[customIndex];
  15724. if (renderTarget._shouldRender()) {
  15725. this._renderId++;
  15726. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  15727. if (!this.activeCamera)
  15728. throw new Error("Active camera not set");
  15729. // Viewport
  15730. engine.setViewport(this.activeCamera.viewport);
  15731. // Camera
  15732. this.updateTransformMatrix();
  15733. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  15734. }
  15735. }
  15736. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15737. this._renderId++;
  15738. }
  15739. if (this.customRenderTargets.length > 0) {
  15740. engine.restoreDefaultFramebuffer();
  15741. }
  15742. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  15743. this.activeCamera = currentActiveCamera;
  15744. // Procedural textures
  15745. if (this.proceduralTexturesEnabled) {
  15746. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  15747. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  15748. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  15749. if (proceduralTexture._shouldRender()) {
  15750. proceduralTexture.render();
  15751. }
  15752. }
  15753. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  15754. }
  15755. // Clear
  15756. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  15757. // Shadows
  15758. if (this.shadowsEnabled) {
  15759. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  15760. var light = this.lights[lightIndex];
  15761. var shadowGenerator = light.getShadowGenerator();
  15762. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  15763. this._renderTargets.push(shadowGenerator.getShadowMap());
  15764. }
  15765. }
  15766. }
  15767. // Depth renderer
  15768. if (this._depthRenderer) {
  15769. this._renderTargets.push(this._depthRenderer.getDepthMap());
  15770. }
  15771. // RenderPipeline
  15772. this.postProcessRenderPipelineManager.update();
  15773. // Multi-cameras?
  15774. if (this.activeCameras.length > 0) {
  15775. var currentRenderId = this._renderId;
  15776. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  15777. this._renderId = currentRenderId;
  15778. if (cameraIndex > 0) {
  15779. this._engine.clear(0, false, true);
  15780. }
  15781. this._processSubCameras(this.activeCameras[cameraIndex]);
  15782. }
  15783. }
  15784. else {
  15785. if (!this.activeCamera) {
  15786. throw new Error("No camera defined");
  15787. }
  15788. this._processSubCameras(this.activeCamera);
  15789. }
  15790. // Intersection checks
  15791. this._checkIntersections();
  15792. // Update the audio listener attached to the camera
  15793. if (BABYLON.AudioEngine) {
  15794. this._updateAudioParameters();
  15795. }
  15796. // After render
  15797. if (this.afterRender) {
  15798. this.afterRender();
  15799. }
  15800. this.onAfterRenderObservable.notifyObservers(this);
  15801. // Cleaning
  15802. for (var index = 0; index < this._toBeDisposed.length; index++) {
  15803. this._toBeDisposed.data[index].dispose();
  15804. this._toBeDisposed[index] = null;
  15805. }
  15806. this._toBeDisposed.reset();
  15807. if (this.dumpNextRenderTargets) {
  15808. this.dumpNextRenderTargets = false;
  15809. }
  15810. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  15811. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  15812. };
  15813. Scene.prototype._updateAudioParameters = function () {
  15814. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  15815. return;
  15816. }
  15817. var listeningCamera;
  15818. var audioEngine = BABYLON.Engine.audioEngine;
  15819. if (this.activeCameras.length > 0) {
  15820. listeningCamera = this.activeCameras[0];
  15821. }
  15822. else {
  15823. listeningCamera = this.activeCamera;
  15824. }
  15825. if (listeningCamera && audioEngine.canUseWebAudio) {
  15826. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  15827. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  15828. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  15829. cameraDirection.normalize();
  15830. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  15831. var i;
  15832. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15833. var sound = this.mainSoundTrack.soundCollection[i];
  15834. if (sound.useCustomAttenuation) {
  15835. sound.updateDistanceFromListener();
  15836. }
  15837. }
  15838. for (i = 0; i < this.soundTracks.length; i++) {
  15839. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15840. sound = this.soundTracks[i].soundCollection[j];
  15841. if (sound.useCustomAttenuation) {
  15842. sound.updateDistanceFromListener();
  15843. }
  15844. }
  15845. }
  15846. }
  15847. };
  15848. Object.defineProperty(Scene.prototype, "audioEnabled", {
  15849. // Audio
  15850. get: function () {
  15851. return this._audioEnabled;
  15852. },
  15853. set: function (value) {
  15854. this._audioEnabled = value;
  15855. if (BABYLON.AudioEngine) {
  15856. if (this._audioEnabled) {
  15857. this._enableAudio();
  15858. }
  15859. else {
  15860. this._disableAudio();
  15861. }
  15862. }
  15863. },
  15864. enumerable: true,
  15865. configurable: true
  15866. });
  15867. Scene.prototype._disableAudio = function () {
  15868. var i;
  15869. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15870. this.mainSoundTrack.soundCollection[i].pause();
  15871. }
  15872. for (i = 0; i < this.soundTracks.length; i++) {
  15873. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15874. this.soundTracks[i].soundCollection[j].pause();
  15875. }
  15876. }
  15877. };
  15878. Scene.prototype._enableAudio = function () {
  15879. var i;
  15880. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15881. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  15882. this.mainSoundTrack.soundCollection[i].play();
  15883. }
  15884. }
  15885. for (i = 0; i < this.soundTracks.length; i++) {
  15886. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15887. if (this.soundTracks[i].soundCollection[j].isPaused) {
  15888. this.soundTracks[i].soundCollection[j].play();
  15889. }
  15890. }
  15891. }
  15892. };
  15893. Object.defineProperty(Scene.prototype, "headphone", {
  15894. get: function () {
  15895. return this._headphone;
  15896. },
  15897. set: function (value) {
  15898. this._headphone = value;
  15899. if (BABYLON.AudioEngine) {
  15900. if (this._headphone) {
  15901. this._switchAudioModeForHeadphones();
  15902. }
  15903. else {
  15904. this._switchAudioModeForNormalSpeakers();
  15905. }
  15906. }
  15907. },
  15908. enumerable: true,
  15909. configurable: true
  15910. });
  15911. Scene.prototype._switchAudioModeForHeadphones = function () {
  15912. this.mainSoundTrack.switchPanningModelToHRTF();
  15913. for (var i = 0; i < this.soundTracks.length; i++) {
  15914. this.soundTracks[i].switchPanningModelToHRTF();
  15915. }
  15916. };
  15917. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  15918. this.mainSoundTrack.switchPanningModelToEqualPower();
  15919. for (var i = 0; i < this.soundTracks.length; i++) {
  15920. this.soundTracks[i].switchPanningModelToEqualPower();
  15921. }
  15922. };
  15923. Scene.prototype.enableDepthRenderer = function () {
  15924. if (this._depthRenderer) {
  15925. return this._depthRenderer;
  15926. }
  15927. this._depthRenderer = new BABYLON.DepthRenderer(this);
  15928. return this._depthRenderer;
  15929. };
  15930. Scene.prototype.disableDepthRenderer = function () {
  15931. if (!this._depthRenderer) {
  15932. return;
  15933. }
  15934. this._depthRenderer.dispose();
  15935. this._depthRenderer = null;
  15936. };
  15937. Scene.prototype.freezeMaterials = function () {
  15938. for (var i = 0; i < this.materials.length; i++) {
  15939. this.materials[i].freeze();
  15940. }
  15941. };
  15942. Scene.prototype.unfreezeMaterials = function () {
  15943. for (var i = 0; i < this.materials.length; i++) {
  15944. this.materials[i].unfreeze();
  15945. }
  15946. };
  15947. Scene.prototype.dispose = function () {
  15948. this.beforeRender = null;
  15949. this.afterRender = null;
  15950. this.skeletons = [];
  15951. this._boundingBoxRenderer.dispose();
  15952. if (this._depthRenderer) {
  15953. this._depthRenderer.dispose();
  15954. }
  15955. // Debug layer
  15956. this.debugLayer.hide();
  15957. // Events
  15958. if (this.onDispose) {
  15959. this.onDispose();
  15960. }
  15961. this.onBeforeRenderObservable.clear();
  15962. this.onAfterRenderObservable.clear();
  15963. this.detachControl();
  15964. // Release sounds & sounds tracks
  15965. if (BABYLON.AudioEngine) {
  15966. this.disposeSounds();
  15967. }
  15968. // Detach cameras
  15969. var canvas = this._engine.getRenderingCanvas();
  15970. var index;
  15971. for (index = 0; index < this.cameras.length; index++) {
  15972. this.cameras[index].detachControl(canvas);
  15973. }
  15974. // Release lights
  15975. while (this.lights.length) {
  15976. this.lights[0].dispose();
  15977. }
  15978. // Release meshes
  15979. while (this.meshes.length) {
  15980. this.meshes[0].dispose(true);
  15981. }
  15982. // Release cameras
  15983. while (this.cameras.length) {
  15984. this.cameras[0].dispose();
  15985. }
  15986. // Release materials
  15987. while (this.materials.length) {
  15988. this.materials[0].dispose();
  15989. }
  15990. // Release particles
  15991. while (this.particleSystems.length) {
  15992. this.particleSystems[0].dispose();
  15993. }
  15994. // Release sprites
  15995. while (this.spriteManagers.length) {
  15996. this.spriteManagers[0].dispose();
  15997. }
  15998. // Release layers
  15999. while (this.layers.length) {
  16000. this.layers[0].dispose();
  16001. }
  16002. // Release textures
  16003. while (this.textures.length) {
  16004. this.textures[0].dispose();
  16005. }
  16006. // Post-processes
  16007. this.postProcessManager.dispose();
  16008. // Physics
  16009. if (this._physicsEngine) {
  16010. this.disablePhysicsEngine();
  16011. }
  16012. // Remove from engine
  16013. index = this._engine.scenes.indexOf(this);
  16014. if (index > -1) {
  16015. this._engine.scenes.splice(index, 1);
  16016. }
  16017. this._engine.wipeCaches();
  16018. };
  16019. // Release sounds & sounds tracks
  16020. Scene.prototype.disposeSounds = function () {
  16021. this.mainSoundTrack.dispose();
  16022. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  16023. this.soundTracks[scIndex].dispose();
  16024. }
  16025. };
  16026. // Octrees
  16027. Scene.prototype.getWorldExtends = function () {
  16028. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16029. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16030. for (var index = 0; index < this.meshes.length; index++) {
  16031. var mesh = this.meshes[index];
  16032. mesh.computeWorldMatrix(true);
  16033. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  16034. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  16035. BABYLON.Tools.CheckExtends(minBox, min, max);
  16036. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16037. }
  16038. return {
  16039. min: min,
  16040. max: max
  16041. };
  16042. };
  16043. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  16044. if (maxCapacity === void 0) { maxCapacity = 64; }
  16045. if (maxDepth === void 0) { maxDepth = 2; }
  16046. if (!this._selectionOctree) {
  16047. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  16048. }
  16049. var worldExtends = this.getWorldExtends();
  16050. // Update octree
  16051. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  16052. return this._selectionOctree;
  16053. };
  16054. // Picking
  16055. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  16056. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  16057. var engine = this._engine;
  16058. if (!camera) {
  16059. if (!this.activeCamera)
  16060. throw new Error("Active camera not set");
  16061. camera = this.activeCamera;
  16062. }
  16063. var cameraViewport = camera.viewport;
  16064. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  16065. // Moving coordinates to local viewport world
  16066. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  16067. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  16068. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  16069. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  16070. };
  16071. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  16072. var engine = this._engine;
  16073. if (!camera) {
  16074. if (!this.activeCamera)
  16075. throw new Error("Active camera not set");
  16076. camera = this.activeCamera;
  16077. }
  16078. var cameraViewport = camera.viewport;
  16079. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  16080. var identity = BABYLON.Matrix.Identity();
  16081. // Moving coordinates to local viewport world
  16082. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  16083. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  16084. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  16085. };
  16086. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  16087. var pickingInfo = null;
  16088. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  16089. var mesh = this.meshes[meshIndex];
  16090. if (predicate) {
  16091. if (!predicate(mesh)) {
  16092. continue;
  16093. }
  16094. }
  16095. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  16096. continue;
  16097. }
  16098. var world = mesh.getWorldMatrix();
  16099. var ray = rayFunction(world);
  16100. var result = mesh.intersects(ray, fastCheck);
  16101. if (!result || !result.hit)
  16102. continue;
  16103. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  16104. continue;
  16105. pickingInfo = result;
  16106. if (fastCheck) {
  16107. break;
  16108. }
  16109. }
  16110. return pickingInfo || new BABYLON.PickingInfo();
  16111. };
  16112. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  16113. var pickingInfo = null;
  16114. camera = camera || this.activeCamera;
  16115. if (this.spriteManagers.length > 0) {
  16116. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  16117. var spriteManager = this.spriteManagers[spriteIndex];
  16118. if (!spriteManager.isPickable) {
  16119. continue;
  16120. }
  16121. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  16122. if (!result || !result.hit)
  16123. continue;
  16124. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  16125. continue;
  16126. pickingInfo = result;
  16127. if (fastCheck) {
  16128. break;
  16129. }
  16130. }
  16131. }
  16132. return pickingInfo || new BABYLON.PickingInfo();
  16133. };
  16134. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  16135. var _this = this;
  16136. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  16137. /// <param name="x">X position on screen</param>
  16138. /// <param name="y">Y position on screen</param>
  16139. /// <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>
  16140. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  16141. /// <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>
  16142. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  16143. };
  16144. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  16145. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  16146. /// <param name="x">X position on screen</param>
  16147. /// <param name="y">Y position on screen</param>
  16148. /// <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>
  16149. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  16150. /// <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>
  16151. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  16152. };
  16153. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  16154. var _this = this;
  16155. return this._internalPick(function (world) {
  16156. if (!_this._pickWithRayInverseMatrix) {
  16157. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  16158. }
  16159. world.invertToRef(_this._pickWithRayInverseMatrix);
  16160. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  16161. }, predicate, fastCheck);
  16162. };
  16163. Scene.prototype.setPointerOverMesh = function (mesh) {
  16164. if (this._pointerOverMesh === mesh) {
  16165. return;
  16166. }
  16167. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  16168. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  16169. }
  16170. this._pointerOverMesh = mesh;
  16171. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  16172. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  16173. }
  16174. };
  16175. Scene.prototype.getPointerOverMesh = function () {
  16176. return this._pointerOverMesh;
  16177. };
  16178. Scene.prototype.setPointerOverSprite = function (sprite) {
  16179. if (this._pointerOverSprite === sprite) {
  16180. return;
  16181. }
  16182. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  16183. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  16184. }
  16185. this._pointerOverSprite = sprite;
  16186. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  16187. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  16188. }
  16189. };
  16190. Scene.prototype.getPointerOverSprite = function () {
  16191. return this._pointerOverSprite;
  16192. };
  16193. // Physics
  16194. Scene.prototype.getPhysicsEngine = function () {
  16195. return this._physicsEngine;
  16196. };
  16197. /**
  16198. * Enables physics to the current scene
  16199. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  16200. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  16201. * @return {boolean} was the physics engine initialized
  16202. */
  16203. Scene.prototype.enablePhysics = function (gravity, plugin) {
  16204. if (this._physicsEngine) {
  16205. return true;
  16206. }
  16207. try {
  16208. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  16209. return true;
  16210. }
  16211. catch (e) {
  16212. BABYLON.Tools.Error(e.message);
  16213. return false;
  16214. }
  16215. };
  16216. Scene.prototype.disablePhysicsEngine = function () {
  16217. if (!this._physicsEngine) {
  16218. return;
  16219. }
  16220. this._physicsEngine.dispose();
  16221. this._physicsEngine = undefined;
  16222. };
  16223. Scene.prototype.isPhysicsEnabled = function () {
  16224. return this._physicsEngine !== undefined;
  16225. };
  16226. /**
  16227. *
  16228. * Sets the gravity of the physics engine (and NOT of the scene)
  16229. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  16230. */
  16231. Scene.prototype.setGravity = function (gravity) {
  16232. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  16233. if (!this._physicsEngine) {
  16234. return;
  16235. }
  16236. this._physicsEngine.setGravity(gravity);
  16237. };
  16238. /**
  16239. * Legacy support, using the new API
  16240. * @Deprecated
  16241. */
  16242. Scene.prototype.createCompoundImpostor = function (parts, options) {
  16243. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  16244. if (parts.parts) {
  16245. options = parts;
  16246. parts = parts.parts;
  16247. }
  16248. var mainMesh = parts[0].mesh;
  16249. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  16250. for (var index = 1; index < parts.length; index++) {
  16251. var mesh = parts[index].mesh;
  16252. if (mesh.parent !== mainMesh) {
  16253. mesh.position = mesh.position.subtract(mainMesh.position);
  16254. mesh.parent = mainMesh;
  16255. }
  16256. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  16257. }
  16258. mainMesh.physicsImpostor.forceUpdate();
  16259. };
  16260. Scene.prototype.deleteCompoundImpostor = function (compound) {
  16261. var mesh = compound.parts[0].mesh;
  16262. mesh.physicsImpostor.dispose();
  16263. mesh.physicsImpostor = null;
  16264. };
  16265. // Misc.
  16266. Scene.prototype.createDefaultCameraOrLight = function () {
  16267. // Light
  16268. if (this.lights.length === 0) {
  16269. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  16270. }
  16271. // Camera
  16272. if (!this.activeCamera) {
  16273. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  16274. // Compute position
  16275. var worldExtends = this.getWorldExtends();
  16276. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  16277. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  16278. camera.setTarget(worldCenter);
  16279. this.activeCamera = camera;
  16280. }
  16281. };
  16282. // Tags
  16283. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  16284. if (tagsQuery === undefined) {
  16285. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  16286. return list;
  16287. }
  16288. var listByTags = [];
  16289. forEach = forEach || (function (item) { return; });
  16290. for (var i in list) {
  16291. var item = list[i];
  16292. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  16293. listByTags.push(item);
  16294. forEach(item);
  16295. }
  16296. }
  16297. return listByTags;
  16298. };
  16299. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  16300. return this._getByTags(this.meshes, tagsQuery, forEach);
  16301. };
  16302. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  16303. return this._getByTags(this.cameras, tagsQuery, forEach);
  16304. };
  16305. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  16306. return this._getByTags(this.lights, tagsQuery, forEach);
  16307. };
  16308. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  16309. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  16310. };
  16311. // Statics
  16312. Scene._FOGMODE_NONE = 0;
  16313. Scene._FOGMODE_EXP = 1;
  16314. Scene._FOGMODE_EXP2 = 2;
  16315. Scene._FOGMODE_LINEAR = 3;
  16316. Scene.MinDeltaTime = 1.0;
  16317. Scene.MaxDeltaTime = 1000.0;
  16318. return Scene;
  16319. })();
  16320. BABYLON.Scene = Scene;
  16321. })(BABYLON || (BABYLON = {}));
  16322. var BABYLON;
  16323. (function (BABYLON) {
  16324. var VertexBuffer = (function () {
  16325. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  16326. if (engine instanceof BABYLON.Mesh) {
  16327. this._engine = engine.getScene().getEngine();
  16328. }
  16329. else {
  16330. this._engine = engine;
  16331. }
  16332. this._updatable = updatable;
  16333. this._data = data;
  16334. if (!postponeInternalCreation) {
  16335. this.create();
  16336. }
  16337. this._kind = kind;
  16338. if (stride) {
  16339. this._strideSize = stride;
  16340. return;
  16341. }
  16342. // Deduce stride from kind
  16343. switch (kind) {
  16344. case VertexBuffer.PositionKind:
  16345. this._strideSize = 3;
  16346. break;
  16347. case VertexBuffer.NormalKind:
  16348. this._strideSize = 3;
  16349. break;
  16350. case VertexBuffer.UVKind:
  16351. case VertexBuffer.UV2Kind:
  16352. case VertexBuffer.UV3Kind:
  16353. case VertexBuffer.UV4Kind:
  16354. case VertexBuffer.UV5Kind:
  16355. case VertexBuffer.UV6Kind:
  16356. this._strideSize = 2;
  16357. break;
  16358. case VertexBuffer.ColorKind:
  16359. this._strideSize = 4;
  16360. break;
  16361. case VertexBuffer.MatricesIndicesKind:
  16362. case VertexBuffer.MatricesIndicesExtraKind:
  16363. this._strideSize = 4;
  16364. break;
  16365. case VertexBuffer.MatricesWeightsKind:
  16366. case VertexBuffer.MatricesWeightsExtraKind:
  16367. this._strideSize = 4;
  16368. break;
  16369. }
  16370. }
  16371. // Properties
  16372. VertexBuffer.prototype.isUpdatable = function () {
  16373. return this._updatable;
  16374. };
  16375. VertexBuffer.prototype.getData = function () {
  16376. return this._data;
  16377. };
  16378. VertexBuffer.prototype.getBuffer = function () {
  16379. return this._buffer;
  16380. };
  16381. VertexBuffer.prototype.getStrideSize = function () {
  16382. return this._strideSize;
  16383. };
  16384. // Methods
  16385. VertexBuffer.prototype.create = function (data) {
  16386. if (!data && this._buffer) {
  16387. return; // nothing to do
  16388. }
  16389. data = data || this._data;
  16390. if (!this._buffer) {
  16391. if (this._updatable) {
  16392. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  16393. }
  16394. else {
  16395. this._buffer = this._engine.createVertexBuffer(data);
  16396. }
  16397. }
  16398. if (this._updatable) {
  16399. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  16400. this._data = data;
  16401. }
  16402. };
  16403. VertexBuffer.prototype.update = function (data) {
  16404. this.create(data);
  16405. };
  16406. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  16407. if (!this._buffer) {
  16408. return;
  16409. }
  16410. if (this._updatable) {
  16411. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  16412. this._data = null;
  16413. }
  16414. };
  16415. VertexBuffer.prototype.dispose = function () {
  16416. if (!this._buffer) {
  16417. return;
  16418. }
  16419. if (this._engine._releaseBuffer(this._buffer)) {
  16420. this._buffer = null;
  16421. }
  16422. };
  16423. Object.defineProperty(VertexBuffer, "PositionKind", {
  16424. get: function () {
  16425. return VertexBuffer._PositionKind;
  16426. },
  16427. enumerable: true,
  16428. configurable: true
  16429. });
  16430. Object.defineProperty(VertexBuffer, "NormalKind", {
  16431. get: function () {
  16432. return VertexBuffer._NormalKind;
  16433. },
  16434. enumerable: true,
  16435. configurable: true
  16436. });
  16437. Object.defineProperty(VertexBuffer, "UVKind", {
  16438. get: function () {
  16439. return VertexBuffer._UVKind;
  16440. },
  16441. enumerable: true,
  16442. configurable: true
  16443. });
  16444. Object.defineProperty(VertexBuffer, "UV2Kind", {
  16445. get: function () {
  16446. return VertexBuffer._UV2Kind;
  16447. },
  16448. enumerable: true,
  16449. configurable: true
  16450. });
  16451. Object.defineProperty(VertexBuffer, "UV3Kind", {
  16452. get: function () {
  16453. return VertexBuffer._UV3Kind;
  16454. },
  16455. enumerable: true,
  16456. configurable: true
  16457. });
  16458. Object.defineProperty(VertexBuffer, "UV4Kind", {
  16459. get: function () {
  16460. return VertexBuffer._UV4Kind;
  16461. },
  16462. enumerable: true,
  16463. configurable: true
  16464. });
  16465. Object.defineProperty(VertexBuffer, "UV5Kind", {
  16466. get: function () {
  16467. return VertexBuffer._UV5Kind;
  16468. },
  16469. enumerable: true,
  16470. configurable: true
  16471. });
  16472. Object.defineProperty(VertexBuffer, "UV6Kind", {
  16473. get: function () {
  16474. return VertexBuffer._UV6Kind;
  16475. },
  16476. enumerable: true,
  16477. configurable: true
  16478. });
  16479. Object.defineProperty(VertexBuffer, "ColorKind", {
  16480. get: function () {
  16481. return VertexBuffer._ColorKind;
  16482. },
  16483. enumerable: true,
  16484. configurable: true
  16485. });
  16486. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  16487. get: function () {
  16488. return VertexBuffer._MatricesIndicesKind;
  16489. },
  16490. enumerable: true,
  16491. configurable: true
  16492. });
  16493. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  16494. get: function () {
  16495. return VertexBuffer._MatricesWeightsKind;
  16496. },
  16497. enumerable: true,
  16498. configurable: true
  16499. });
  16500. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  16501. get: function () {
  16502. return VertexBuffer._MatricesIndicesExtraKind;
  16503. },
  16504. enumerable: true,
  16505. configurable: true
  16506. });
  16507. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  16508. get: function () {
  16509. return VertexBuffer._MatricesWeightsExtraKind;
  16510. },
  16511. enumerable: true,
  16512. configurable: true
  16513. });
  16514. // Enums
  16515. VertexBuffer._PositionKind = "position";
  16516. VertexBuffer._NormalKind = "normal";
  16517. VertexBuffer._UVKind = "uv";
  16518. VertexBuffer._UV2Kind = "uv2";
  16519. VertexBuffer._UV3Kind = "uv3";
  16520. VertexBuffer._UV4Kind = "uv4";
  16521. VertexBuffer._UV5Kind = "uv5";
  16522. VertexBuffer._UV6Kind = "uv6";
  16523. VertexBuffer._ColorKind = "color";
  16524. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  16525. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  16526. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  16527. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  16528. return VertexBuffer;
  16529. })();
  16530. BABYLON.VertexBuffer = VertexBuffer;
  16531. })(BABYLON || (BABYLON = {}));
  16532. var BABYLON;
  16533. (function (BABYLON) {
  16534. /**
  16535. * Creates an instance based on a source mesh.
  16536. */
  16537. var InstancedMesh = (function (_super) {
  16538. __extends(InstancedMesh, _super);
  16539. function InstancedMesh(name, source) {
  16540. _super.call(this, name, source.getScene());
  16541. source.instances.push(this);
  16542. this._sourceMesh = source;
  16543. this.position.copyFrom(source.position);
  16544. this.rotation.copyFrom(source.rotation);
  16545. this.scaling.copyFrom(source.scaling);
  16546. if (source.rotationQuaternion) {
  16547. this.rotationQuaternion = source.rotationQuaternion.clone();
  16548. }
  16549. this.infiniteDistance = source.infiniteDistance;
  16550. this.setPivotMatrix(source.getPivotMatrix());
  16551. this.refreshBoundingInfo();
  16552. this._syncSubMeshes();
  16553. }
  16554. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  16555. // Methods
  16556. get: function () {
  16557. return this._sourceMesh.receiveShadows;
  16558. },
  16559. enumerable: true,
  16560. configurable: true
  16561. });
  16562. Object.defineProperty(InstancedMesh.prototype, "material", {
  16563. get: function () {
  16564. return this._sourceMesh.material;
  16565. },
  16566. enumerable: true,
  16567. configurable: true
  16568. });
  16569. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  16570. get: function () {
  16571. return this._sourceMesh.visibility;
  16572. },
  16573. enumerable: true,
  16574. configurable: true
  16575. });
  16576. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  16577. get: function () {
  16578. return this._sourceMesh.skeleton;
  16579. },
  16580. enumerable: true,
  16581. configurable: true
  16582. });
  16583. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  16584. get: function () {
  16585. return this._sourceMesh.renderingGroupId;
  16586. },
  16587. enumerable: true,
  16588. configurable: true
  16589. });
  16590. InstancedMesh.prototype.getTotalVertices = function () {
  16591. return this._sourceMesh.getTotalVertices();
  16592. };
  16593. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  16594. get: function () {
  16595. return this._sourceMesh;
  16596. },
  16597. enumerable: true,
  16598. configurable: true
  16599. });
  16600. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  16601. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  16602. };
  16603. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  16604. return this._sourceMesh.isVerticesDataPresent(kind);
  16605. };
  16606. InstancedMesh.prototype.getIndices = function () {
  16607. return this._sourceMesh.getIndices();
  16608. };
  16609. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  16610. get: function () {
  16611. return this._sourceMesh._positions;
  16612. },
  16613. enumerable: true,
  16614. configurable: true
  16615. });
  16616. InstancedMesh.prototype.refreshBoundingInfo = function () {
  16617. var meshBB = this._sourceMesh.getBoundingInfo();
  16618. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  16619. this._updateBoundingInfo();
  16620. };
  16621. InstancedMesh.prototype._preActivate = function () {
  16622. if (this._currentLOD) {
  16623. this._currentLOD._preActivate();
  16624. }
  16625. };
  16626. InstancedMesh.prototype._activate = function (renderId) {
  16627. if (this._currentLOD) {
  16628. this._currentLOD._registerInstanceForRenderId(this, renderId);
  16629. }
  16630. };
  16631. InstancedMesh.prototype.getLOD = function (camera) {
  16632. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  16633. if (this._currentLOD === this.sourceMesh) {
  16634. return this;
  16635. }
  16636. return this._currentLOD;
  16637. };
  16638. InstancedMesh.prototype._syncSubMeshes = function () {
  16639. this.releaseSubMeshes();
  16640. if (this._sourceMesh.subMeshes) {
  16641. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  16642. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  16643. }
  16644. }
  16645. };
  16646. InstancedMesh.prototype._generatePointsArray = function () {
  16647. return this._sourceMesh._generatePointsArray();
  16648. };
  16649. // Clone
  16650. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16651. var result = this._sourceMesh.createInstance(name);
  16652. // Deep copy
  16653. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  16654. // Bounding info
  16655. this.refreshBoundingInfo();
  16656. // Parent
  16657. if (newParent) {
  16658. result.parent = newParent;
  16659. }
  16660. if (!doNotCloneChildren) {
  16661. // Children
  16662. for (var index = 0; index < this.getScene().meshes.length; index++) {
  16663. var mesh = this.getScene().meshes[index];
  16664. if (mesh.parent === this) {
  16665. mesh.clone(mesh.name, result);
  16666. }
  16667. }
  16668. }
  16669. result.computeWorldMatrix(true);
  16670. return result;
  16671. };
  16672. // Dispoe
  16673. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  16674. // Remove from mesh
  16675. var index = this._sourceMesh.instances.indexOf(this);
  16676. this._sourceMesh.instances.splice(index, 1);
  16677. _super.prototype.dispose.call(this, doNotRecurse);
  16678. };
  16679. return InstancedMesh;
  16680. })(BABYLON.AbstractMesh);
  16681. BABYLON.InstancedMesh = InstancedMesh;
  16682. })(BABYLON || (BABYLON = {}));
  16683. var BABYLON;
  16684. (function (BABYLON) {
  16685. var _InstancesBatch = (function () {
  16686. function _InstancesBatch() {
  16687. this.mustReturn = false;
  16688. this.visibleInstances = new Array();
  16689. this.renderSelf = new Array();
  16690. }
  16691. return _InstancesBatch;
  16692. })();
  16693. BABYLON._InstancesBatch = _InstancesBatch;
  16694. var Mesh = (function (_super) {
  16695. __extends(Mesh, _super);
  16696. /**
  16697. * @constructor
  16698. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  16699. * @param {Scene} scene - The scene to add this mesh to.
  16700. * @param {Node} parent - The parent of this mesh, if it has one
  16701. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  16702. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  16703. * When false, achieved by calling a clone(), also passing False.
  16704. * This will make creation of children, recursive.
  16705. */
  16706. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  16707. if (parent === void 0) { parent = null; }
  16708. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  16709. _super.call(this, name, scene);
  16710. // Events
  16711. /**
  16712. * An event triggered before rendering the mesh
  16713. * @type {BABYLON.Observable}
  16714. */
  16715. this.onBeforeRenderObservable = new BABYLON.Observable();
  16716. /**
  16717. * An event triggered after rendering the mesh
  16718. * @type {BABYLON.Observable}
  16719. */
  16720. this.onAfterRenderObservable = new BABYLON.Observable();
  16721. /**
  16722. * An event triggered before drawing the mesh
  16723. * @type {BABYLON.Observable}
  16724. */
  16725. this.onBeforeDrawObservable = new BABYLON.Observable();
  16726. // Members
  16727. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16728. this.instances = new Array();
  16729. this._LODLevels = new Array();
  16730. this._visibleInstances = {};
  16731. this._renderIdForInstances = new Array();
  16732. this._batchCache = new _InstancesBatch();
  16733. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  16734. this._sideOrientation = Mesh._DEFAULTSIDE;
  16735. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  16736. if (source) {
  16737. // Geometry
  16738. if (source._geometry) {
  16739. source._geometry.applyToMesh(this);
  16740. }
  16741. // Deep copy
  16742. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  16743. // Pivot
  16744. this.setPivotMatrix(source.getPivotMatrix());
  16745. this.id = name + "." + source.id;
  16746. // Material
  16747. this.material = source.material;
  16748. var index;
  16749. if (!doNotCloneChildren) {
  16750. // Children
  16751. for (index = 0; index < scene.meshes.length; index++) {
  16752. var mesh = scene.meshes[index];
  16753. if (mesh.parent === source) {
  16754. // doNotCloneChildren is always going to be False
  16755. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  16756. }
  16757. }
  16758. }
  16759. // Physics clone
  16760. var physicsEngine = this.getScene().getPhysicsEngine();
  16761. if (clonePhysicsImpostor && physicsEngine) {
  16762. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  16763. if (impostor) {
  16764. this.physicsImpostor = impostor.clone(this);
  16765. }
  16766. }
  16767. // Particles
  16768. for (index = 0; index < scene.particleSystems.length; index++) {
  16769. var system = scene.particleSystems[index];
  16770. if (system.emitter === source) {
  16771. system.clone(system.name, this);
  16772. }
  16773. }
  16774. this.computeWorldMatrix(true);
  16775. }
  16776. // Parent
  16777. if (parent !== null) {
  16778. this.parent = parent;
  16779. }
  16780. }
  16781. Object.defineProperty(Mesh, "FRONTSIDE", {
  16782. /**
  16783. * Mesh side orientation : usually the external or front surface
  16784. */
  16785. get: function () {
  16786. return Mesh._FRONTSIDE;
  16787. },
  16788. enumerable: true,
  16789. configurable: true
  16790. });
  16791. Object.defineProperty(Mesh, "BACKSIDE", {
  16792. /**
  16793. * Mesh side orientation : usually the internal or back surface
  16794. */
  16795. get: function () {
  16796. return Mesh._BACKSIDE;
  16797. },
  16798. enumerable: true,
  16799. configurable: true
  16800. });
  16801. Object.defineProperty(Mesh, "DOUBLESIDE", {
  16802. /**
  16803. * Mesh side orientation : both internal and external or front and back surfaces
  16804. */
  16805. get: function () {
  16806. return Mesh._DOUBLESIDE;
  16807. },
  16808. enumerable: true,
  16809. configurable: true
  16810. });
  16811. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  16812. /**
  16813. * Mesh side orientation : by default, `FRONTSIDE`
  16814. */
  16815. get: function () {
  16816. return Mesh._DEFAULTSIDE;
  16817. },
  16818. enumerable: true,
  16819. configurable: true
  16820. });
  16821. Object.defineProperty(Mesh, "NO_CAP", {
  16822. /**
  16823. * Mesh cap setting : no cap
  16824. */
  16825. get: function () {
  16826. return Mesh._NO_CAP;
  16827. },
  16828. enumerable: true,
  16829. configurable: true
  16830. });
  16831. Object.defineProperty(Mesh, "CAP_START", {
  16832. /**
  16833. * Mesh cap setting : one cap at the beginning of the mesh
  16834. */
  16835. get: function () {
  16836. return Mesh._CAP_START;
  16837. },
  16838. enumerable: true,
  16839. configurable: true
  16840. });
  16841. Object.defineProperty(Mesh, "CAP_END", {
  16842. /**
  16843. * Mesh cap setting : one cap at the end of the mesh
  16844. */
  16845. get: function () {
  16846. return Mesh._CAP_END;
  16847. },
  16848. enumerable: true,
  16849. configurable: true
  16850. });
  16851. Object.defineProperty(Mesh, "CAP_ALL", {
  16852. /**
  16853. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  16854. */
  16855. get: function () {
  16856. return Mesh._CAP_ALL;
  16857. },
  16858. enumerable: true,
  16859. configurable: true
  16860. });
  16861. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  16862. set: function (callback) {
  16863. if (this._onBeforeDrawObserver) {
  16864. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  16865. }
  16866. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  16867. },
  16868. enumerable: true,
  16869. configurable: true
  16870. });
  16871. // Methods
  16872. /**
  16873. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16874. */
  16875. Mesh.prototype.toString = function (fullDetails) {
  16876. var ret = _super.prototype.toString.call(this, fullDetails);
  16877. ret += ", n vertices: " + this.getTotalVertices();
  16878. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  16879. if (this.animations) {
  16880. for (var i = 0; i < this.animations.length; i++) {
  16881. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16882. }
  16883. }
  16884. if (fullDetails) {
  16885. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  16886. }
  16887. return ret;
  16888. };
  16889. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  16890. get: function () {
  16891. return this._LODLevels.length > 0;
  16892. },
  16893. enumerable: true,
  16894. configurable: true
  16895. });
  16896. Mesh.prototype._sortLODLevels = function () {
  16897. this._LODLevels.sort(function (a, b) {
  16898. if (a.distance < b.distance) {
  16899. return 1;
  16900. }
  16901. if (a.distance > b.distance) {
  16902. return -1;
  16903. }
  16904. return 0;
  16905. });
  16906. };
  16907. /**
  16908. * Add a mesh as LOD level triggered at the given distance.
  16909. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  16910. * @param {number} distance - the distance from the center of the object to show this level
  16911. * @param {Mesh} mesh - the mesh to be added as LOD level
  16912. * @return {Mesh} this mesh (for chaining)
  16913. */
  16914. Mesh.prototype.addLODLevel = function (distance, mesh) {
  16915. if (mesh && mesh._masterMesh) {
  16916. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  16917. return this;
  16918. }
  16919. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  16920. this._LODLevels.push(level);
  16921. if (mesh) {
  16922. mesh._masterMesh = this;
  16923. }
  16924. this._sortLODLevels();
  16925. return this;
  16926. };
  16927. /**
  16928. * Returns the LOD level mesh at the passed distance or null if not found.
  16929. * It is related to the method `addLODLevel(distance, mesh)`.
  16930. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  16931. */
  16932. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  16933. for (var index = 0; index < this._LODLevels.length; index++) {
  16934. var level = this._LODLevels[index];
  16935. if (level.distance === distance) {
  16936. return level.mesh;
  16937. }
  16938. }
  16939. return null;
  16940. };
  16941. /**
  16942. * Remove a mesh from the LOD array
  16943. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  16944. * @param {Mesh} mesh - the mesh to be removed.
  16945. * @return {Mesh} this mesh (for chaining)
  16946. */
  16947. Mesh.prototype.removeLODLevel = function (mesh) {
  16948. for (var index = 0; index < this._LODLevels.length; index++) {
  16949. if (this._LODLevels[index].mesh === mesh) {
  16950. this._LODLevels.splice(index, 1);
  16951. if (mesh) {
  16952. mesh._masterMesh = null;
  16953. }
  16954. }
  16955. }
  16956. this._sortLODLevels();
  16957. return this;
  16958. };
  16959. /**
  16960. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  16961. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  16962. */
  16963. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  16964. if (!this._LODLevels || this._LODLevels.length === 0) {
  16965. return this;
  16966. }
  16967. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  16968. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  16969. if (this.onLODLevelSelection) {
  16970. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  16971. }
  16972. return this;
  16973. }
  16974. for (var index = 0; index < this._LODLevels.length; index++) {
  16975. var level = this._LODLevels[index];
  16976. if (level.distance < distanceToCamera) {
  16977. if (level.mesh) {
  16978. level.mesh._preActivate();
  16979. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16980. }
  16981. if (this.onLODLevelSelection) {
  16982. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  16983. }
  16984. return level.mesh;
  16985. }
  16986. }
  16987. if (this.onLODLevelSelection) {
  16988. this.onLODLevelSelection(distanceToCamera, this, this);
  16989. }
  16990. return this;
  16991. };
  16992. Object.defineProperty(Mesh.prototype, "geometry", {
  16993. /**
  16994. * Returns the mesh internal `Geometry` object.
  16995. */
  16996. get: function () {
  16997. return this._geometry;
  16998. },
  16999. enumerable: true,
  17000. configurable: true
  17001. });
  17002. /**
  17003. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  17004. */
  17005. Mesh.prototype.getTotalVertices = function () {
  17006. if (!this._geometry) {
  17007. return 0;
  17008. }
  17009. return this._geometry.getTotalVertices();
  17010. };
  17011. /**
  17012. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  17013. * If `copywhenShared` is true (default false) and if the mesh has submeshes, the submesh data are duplicated in the returned array.
  17014. * Returns null if the mesh has no geometry or no vertex buffer.
  17015. * Possible `kind` values :
  17016. * - BABYLON.VertexBuffer.PositionKind
  17017. * - BABYLON.VertexBuffer.UVKind
  17018. * - BABYLON.VertexBuffer.UV2Kind
  17019. * - BABYLON.VertexBuffer.UV3Kind
  17020. * - BABYLON.VertexBuffer.UV4Kind
  17021. * - BABYLON.VertexBuffer.UV5Kind
  17022. * - BABYLON.VertexBuffer.UV6Kind
  17023. * - BABYLON.VertexBuffer.ColorKind
  17024. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17025. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17026. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17027. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17028. */
  17029. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  17030. if (!this._geometry) {
  17031. return null;
  17032. }
  17033. return this._geometry.getVerticesData(kind, copyWhenShared);
  17034. };
  17035. /**
  17036. * Returns the mesh `VertexBuffer` object from the requested `kind` : positions, indices, normals, etc.
  17037. * Returns `undefined` if the mesh has no geometry.
  17038. * Possible `kind` values :
  17039. * - BABYLON.VertexBuffer.PositionKind
  17040. * - BABYLON.VertexBuffer.UVKind
  17041. * - BABYLON.VertexBuffer.UV2Kind
  17042. * - BABYLON.VertexBuffer.UV3Kind
  17043. * - BABYLON.VertexBuffer.UV4Kind
  17044. * - BABYLON.VertexBuffer.UV5Kind
  17045. * - BABYLON.VertexBuffer.UV6Kind
  17046. * - BABYLON.VertexBuffer.ColorKind
  17047. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17048. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17049. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17050. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17051. */
  17052. Mesh.prototype.getVertexBuffer = function (kind) {
  17053. if (!this._geometry) {
  17054. return undefined;
  17055. }
  17056. return this._geometry.getVertexBuffer(kind);
  17057. };
  17058. /**
  17059. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  17060. * Possible `kind` values :
  17061. * - BABYLON.VertexBuffer.PositionKind
  17062. * - BABYLON.VertexBuffer.UVKind
  17063. * - BABYLON.VertexBuffer.UV2Kind
  17064. * - BABYLON.VertexBuffer.UV3Kind
  17065. * - BABYLON.VertexBuffer.UV4Kind
  17066. * - BABYLON.VertexBuffer.UV5Kind
  17067. * - BABYLON.VertexBuffer.UV6Kind
  17068. * - BABYLON.VertexBuffer.ColorKind
  17069. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17070. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17071. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17072. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17073. */
  17074. Mesh.prototype.isVerticesDataPresent = function (kind) {
  17075. if (!this._geometry) {
  17076. if (this._delayInfo) {
  17077. return this._delayInfo.indexOf(kind) !== -1;
  17078. }
  17079. return false;
  17080. }
  17081. return this._geometry.isVerticesDataPresent(kind);
  17082. };
  17083. /**
  17084. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  17085. * Possible `kind` values :
  17086. * - BABYLON.VertexBuffer.PositionKind
  17087. * - BABYLON.VertexBuffer.UVKind
  17088. * - BABYLON.VertexBuffer.UV2Kind
  17089. * - BABYLON.VertexBuffer.UV3Kind
  17090. * - BABYLON.VertexBuffer.UV4Kind
  17091. * - BABYLON.VertexBuffer.UV5Kind
  17092. * - BABYLON.VertexBuffer.UV6Kind
  17093. * - BABYLON.VertexBuffer.ColorKind
  17094. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17095. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17096. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17097. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17098. */
  17099. Mesh.prototype.getVerticesDataKinds = function () {
  17100. if (!this._geometry) {
  17101. var result = [];
  17102. if (this._delayInfo) {
  17103. for (var kind in this._delayInfo) {
  17104. result.push(kind);
  17105. }
  17106. }
  17107. return result;
  17108. }
  17109. return this._geometry.getVerticesDataKinds();
  17110. };
  17111. /**
  17112. * Returns a positive integer : the total number of indices in this mesh geometry.
  17113. * Returns zero if the mesh has no geometry.
  17114. */
  17115. Mesh.prototype.getTotalIndices = function () {
  17116. if (!this._geometry) {
  17117. return 0;
  17118. }
  17119. return this._geometry.getTotalIndices();
  17120. };
  17121. /**
  17122. * Returns an array of integers or a Int32Array populated with the mesh indices.
  17123. * If the parameter `copyWhenShared` is true (default false) and if the mesh has submeshes, the submesh indices are duplicated in the returned array.
  17124. * Returns an empty array if the mesh has no geometry.
  17125. */
  17126. Mesh.prototype.getIndices = function (copyWhenShared) {
  17127. if (!this._geometry) {
  17128. return [];
  17129. }
  17130. return this._geometry.getIndices(copyWhenShared);
  17131. };
  17132. Object.defineProperty(Mesh.prototype, "isBlocked", {
  17133. get: function () {
  17134. return this._masterMesh !== null && this._masterMesh !== undefined;
  17135. },
  17136. enumerable: true,
  17137. configurable: true
  17138. });
  17139. /**
  17140. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  17141. */
  17142. Mesh.prototype.isReady = function () {
  17143. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17144. return false;
  17145. }
  17146. return _super.prototype.isReady.call(this);
  17147. };
  17148. /**
  17149. * Boolean : true if the mesh has been disposed.
  17150. */
  17151. Mesh.prototype.isDisposed = function () {
  17152. return this._isDisposed;
  17153. };
  17154. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  17155. get: function () {
  17156. return this._sideOrientation;
  17157. },
  17158. /**
  17159. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  17160. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  17161. */
  17162. set: function (sideO) {
  17163. this._sideOrientation = sideO;
  17164. },
  17165. enumerable: true,
  17166. configurable: true
  17167. });
  17168. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  17169. /**
  17170. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  17171. * This property is pertinent only for updatable parametric shapes.
  17172. */
  17173. get: function () {
  17174. return this._areNormalsFrozen;
  17175. },
  17176. enumerable: true,
  17177. configurable: true
  17178. });
  17179. /**
  17180. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  17181. * It has no effect at all on other shapes.
  17182. * It prevents the mesh normals from being recomputed on next `positions` array update.
  17183. */
  17184. Mesh.prototype.freezeNormals = function () {
  17185. this._areNormalsFrozen = true;
  17186. };
  17187. /**
  17188. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  17189. * It has no effect at all on other shapes.
  17190. * It reactivates the mesh normals computation if it was previously frozen.
  17191. */
  17192. Mesh.prototype.unfreezeNormals = function () {
  17193. this._areNormalsFrozen = false;
  17194. };
  17195. // Methods
  17196. Mesh.prototype._preActivate = function () {
  17197. var sceneRenderId = this.getScene().getRenderId();
  17198. if (this._preActivateId === sceneRenderId) {
  17199. return;
  17200. }
  17201. this._preActivateId = sceneRenderId;
  17202. this._visibleInstances = null;
  17203. };
  17204. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17205. if (this._visibleInstances) {
  17206. this._visibleInstances.intermediateDefaultRenderId = renderId;
  17207. }
  17208. };
  17209. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  17210. if (!this._visibleInstances) {
  17211. this._visibleInstances = {};
  17212. this._visibleInstances.defaultRenderId = renderId;
  17213. this._visibleInstances.selfDefaultRenderId = this._renderId;
  17214. }
  17215. if (!this._visibleInstances[renderId]) {
  17216. this._visibleInstances[renderId] = new Array();
  17217. }
  17218. this._visibleInstances[renderId].push(instance);
  17219. };
  17220. /**
  17221. * This method recomputes and sets a new `BoundingInfo` to the mesh unless it is locked.
  17222. * This means the mesh underlying bounding box and shpere are recomputed.
  17223. */
  17224. Mesh.prototype.refreshBoundingInfo = function () {
  17225. if (this._boundingInfo.isLocked) {
  17226. return;
  17227. }
  17228. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17229. if (data) {
  17230. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  17231. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  17232. }
  17233. if (this.subMeshes) {
  17234. for (var index = 0; index < this.subMeshes.length; index++) {
  17235. this.subMeshes[index].refreshBoundingInfo();
  17236. }
  17237. }
  17238. this._updateBoundingInfo();
  17239. };
  17240. Mesh.prototype._createGlobalSubMesh = function () {
  17241. var totalVertices = this.getTotalVertices();
  17242. if (!totalVertices || !this.getIndices()) {
  17243. return null;
  17244. }
  17245. this.releaseSubMeshes();
  17246. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  17247. };
  17248. Mesh.prototype.subdivide = function (count) {
  17249. if (count < 1) {
  17250. return;
  17251. }
  17252. var totalIndices = this.getTotalIndices();
  17253. var subdivisionSize = (totalIndices / count) | 0;
  17254. var offset = 0;
  17255. // Ensure that subdivisionSize is a multiple of 3
  17256. while (subdivisionSize % 3 !== 0) {
  17257. subdivisionSize++;
  17258. }
  17259. this.releaseSubMeshes();
  17260. for (var index = 0; index < count; index++) {
  17261. if (offset >= totalIndices) {
  17262. break;
  17263. }
  17264. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  17265. offset += subdivisionSize;
  17266. }
  17267. this.synchronizeInstances();
  17268. };
  17269. /**
  17270. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17271. * If the mesh has no geometry, a new `Geometry` object is set to the mesh and then passed this vertex data.
  17272. * The `data` are either a numeric array either a Float32Array.
  17273. * 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).
  17274. * Note that a new underlying `VertexBuffer` object is created each call.
  17275. * If the `kind` is the `PositionKind`, the mesh `BoundingInfo` is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17276. * The same for the mesh submeshes if any.
  17277. *
  17278. * Possible `kind` values :
  17279. * - BABYLON.VertexBuffer.PositionKind
  17280. * - BABYLON.VertexBuffer.UVKind
  17281. * - BABYLON.VertexBuffer.UV2Kind
  17282. * - BABYLON.VertexBuffer.UV3Kind
  17283. * - BABYLON.VertexBuffer.UV4Kind
  17284. * - BABYLON.VertexBuffer.UV5Kind
  17285. * - BABYLON.VertexBuffer.UV6Kind
  17286. * - BABYLON.VertexBuffer.ColorKind
  17287. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17288. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17289. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17290. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17291. */
  17292. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17293. if (!this._geometry) {
  17294. var vertexData = new BABYLON.VertexData();
  17295. vertexData.set(data, kind);
  17296. var scene = this.getScene();
  17297. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  17298. }
  17299. else {
  17300. this._geometry.setVerticesData(kind, data, updatable, stride);
  17301. }
  17302. };
  17303. /**
  17304. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17305. * If the mesh has no geometry, it is simply returned as it is.
  17306. * The `data` are either a numeric array either a Float32Array.
  17307. * No new underlying `VertexBuffer` object is created.
  17308. * 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.
  17309. * The same for the mesh submeshes if any.
  17310. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17311. *
  17312. * Possible `kind` values :
  17313. * - BABYLON.VertexBuffer.PositionKind
  17314. * - BABYLON.VertexBuffer.UVKind
  17315. * - BABYLON.VertexBuffer.UV2Kind
  17316. * - BABYLON.VertexBuffer.UV3Kind
  17317. * - BABYLON.VertexBuffer.UV4Kind
  17318. * - BABYLON.VertexBuffer.UV5Kind
  17319. * - BABYLON.VertexBuffer.UV6Kind
  17320. * - BABYLON.VertexBuffer.ColorKind
  17321. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17322. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17323. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17324. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17325. */
  17326. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17327. if (!this._geometry) {
  17328. return;
  17329. }
  17330. if (!makeItUnique) {
  17331. this._geometry.updateVerticesData(kind, data, updateExtends);
  17332. }
  17333. else {
  17334. this.makeGeometryUnique();
  17335. this.updateVerticesData(kind, data, updateExtends, false);
  17336. }
  17337. };
  17338. /**
  17339. * Deprecated since BabylonJS v2.3
  17340. */
  17341. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  17342. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  17343. if (!this._geometry) {
  17344. return;
  17345. }
  17346. if (!makeItUnique) {
  17347. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  17348. }
  17349. else {
  17350. this.makeGeometryUnique();
  17351. this.updateVerticesDataDirectly(kind, data, offset, false);
  17352. }
  17353. };
  17354. /**
  17355. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  17356. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  17357. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  17358. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  17359. */
  17360. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  17361. if (computeNormals === void 0) { computeNormals = true; }
  17362. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17363. positionFunction(positions);
  17364. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  17365. if (computeNormals) {
  17366. var indices = this.getIndices();
  17367. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17368. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17369. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  17370. }
  17371. };
  17372. Mesh.prototype.makeGeometryUnique = function () {
  17373. if (!this._geometry) {
  17374. return;
  17375. }
  17376. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  17377. geometry.applyToMesh(this);
  17378. };
  17379. /**
  17380. * Sets the mesh indices.
  17381. * Expects an array populated with integers or a Int32Array.
  17382. * If the mesh has no geometry, a new `Geometry` object is created and set to the mesh.
  17383. * This method creates a new index buffer each call.
  17384. */
  17385. Mesh.prototype.setIndices = function (indices, totalVertices) {
  17386. if (!this._geometry) {
  17387. var vertexData = new BABYLON.VertexData();
  17388. vertexData.indices = indices;
  17389. var scene = this.getScene();
  17390. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  17391. }
  17392. else {
  17393. this._geometry.setIndices(indices, totalVertices);
  17394. }
  17395. };
  17396. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  17397. var engine = this.getScene().getEngine();
  17398. // Wireframe
  17399. var indexToBind;
  17400. if (this._unIndexed) {
  17401. indexToBind = null;
  17402. }
  17403. else {
  17404. switch (fillMode) {
  17405. case BABYLON.Material.PointFillMode:
  17406. indexToBind = null;
  17407. break;
  17408. case BABYLON.Material.WireFrameFillMode:
  17409. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  17410. break;
  17411. default:
  17412. case BABYLON.Material.TriangleFillMode:
  17413. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  17414. break;
  17415. }
  17416. }
  17417. // VBOs
  17418. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  17419. };
  17420. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  17421. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  17422. return;
  17423. }
  17424. this.onBeforeDrawObservable.notifyObservers(this);
  17425. var engine = this.getScene().getEngine();
  17426. // Draw order
  17427. switch (fillMode) {
  17428. case BABYLON.Material.PointFillMode:
  17429. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17430. break;
  17431. case BABYLON.Material.WireFrameFillMode:
  17432. if (this._unIndexed) {
  17433. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17434. }
  17435. else {
  17436. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  17437. }
  17438. break;
  17439. default:
  17440. if (this._unIndexed) {
  17441. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17442. }
  17443. else {
  17444. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  17445. }
  17446. }
  17447. };
  17448. /**
  17449. * Registers a javascript function for this mesh that will be called just before the rendering process.
  17450. * This function is passed the current mesh and doesn't return anything.
  17451. */
  17452. Mesh.prototype.registerBeforeRender = function (func) {
  17453. this.onBeforeRenderObservable.add(func);
  17454. };
  17455. /**
  17456. * Disposes a previously registered javascript function called before the rendering.
  17457. * This function is passed the current mesh and doesn't return anything.
  17458. */
  17459. Mesh.prototype.unregisterBeforeRender = function (func) {
  17460. this.onBeforeRenderObservable.removeCallback(func);
  17461. };
  17462. /**
  17463. * Registers a javascript function for this mesh that will be called just after the rendering is complete.
  17464. * This function is passed the current mesh and doesn't return anything.
  17465. */
  17466. Mesh.prototype.registerAfterRender = function (func) {
  17467. this.onAfterRenderObservable.add(func);
  17468. };
  17469. /**
  17470. * Disposes a previously registered javascript function called after the rendering.
  17471. * This function is passed the current mesh and doesn't return anything.
  17472. */
  17473. Mesh.prototype.unregisterAfterRender = function (func) {
  17474. this.onAfterRenderObservable.removeCallback(func);
  17475. };
  17476. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  17477. var scene = this.getScene();
  17478. this._batchCache.mustReturn = false;
  17479. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  17480. this._batchCache.visibleInstances[subMeshId] = null;
  17481. if (this._visibleInstances) {
  17482. var currentRenderId = scene.getRenderId();
  17483. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  17484. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  17485. var selfRenderId = this._renderId;
  17486. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  17487. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  17488. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  17489. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  17490. }
  17491. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  17492. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  17493. this._batchCache.mustReturn = true;
  17494. return this._batchCache;
  17495. }
  17496. if (currentRenderId !== selfRenderId) {
  17497. this._batchCache.renderSelf[subMeshId] = false;
  17498. }
  17499. }
  17500. this._renderIdForInstances[subMeshId] = currentRenderId;
  17501. }
  17502. return this._batchCache;
  17503. };
  17504. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  17505. var visibleInstances = batch.visibleInstances[subMesh._id];
  17506. var matricesCount = visibleInstances.length + 1;
  17507. var bufferSize = matricesCount * 16 * 4;
  17508. while (this._instancesBufferSize < bufferSize) {
  17509. this._instancesBufferSize *= 2;
  17510. }
  17511. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  17512. if (this._worldMatricesInstancesBuffer) {
  17513. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  17514. }
  17515. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  17516. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  17517. }
  17518. var offset = 0;
  17519. var instancesCount = 0;
  17520. var world = this.getWorldMatrix();
  17521. if (batch.renderSelf[subMesh._id]) {
  17522. world.copyToArray(this._worldMatricesInstancesArray, offset);
  17523. offset += 16;
  17524. instancesCount++;
  17525. }
  17526. if (visibleInstances) {
  17527. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  17528. var instance = visibleInstances[instanceIndex];
  17529. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  17530. offset += 16;
  17531. instancesCount++;
  17532. }
  17533. }
  17534. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  17535. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  17536. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  17537. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  17538. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  17539. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  17540. this._draw(subMesh, fillMode, instancesCount);
  17541. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  17542. };
  17543. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  17544. var scene = this.getScene();
  17545. var engine = scene.getEngine();
  17546. if (hardwareInstancedRendering) {
  17547. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  17548. }
  17549. else {
  17550. if (batch.renderSelf[subMesh._id]) {
  17551. // Draw
  17552. if (onBeforeDraw) {
  17553. onBeforeDraw(false, this.getWorldMatrix());
  17554. }
  17555. this._draw(subMesh, fillMode);
  17556. }
  17557. if (batch.visibleInstances[subMesh._id]) {
  17558. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  17559. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  17560. // World
  17561. var world = instance.getWorldMatrix();
  17562. if (onBeforeDraw) {
  17563. onBeforeDraw(true, world);
  17564. }
  17565. // Draw
  17566. this._draw(subMesh, fillMode);
  17567. }
  17568. }
  17569. }
  17570. };
  17571. /**
  17572. * Triggers the draw call for the mesh.
  17573. * You don't need to call this method by your own usually because the mesh rendering is handled by the scene rendering manager.
  17574. */
  17575. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  17576. var scene = this.getScene();
  17577. // Managing instances
  17578. var batch = this._getInstancesRenderList(subMesh._id);
  17579. if (batch.mustReturn) {
  17580. return;
  17581. }
  17582. // Checking geometry state
  17583. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  17584. return;
  17585. }
  17586. var callbackIndex;
  17587. this.onBeforeRenderObservable.notifyObservers(this);
  17588. var engine = scene.getEngine();
  17589. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  17590. // Material
  17591. var effectiveMaterial = subMesh.getMaterial();
  17592. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  17593. return;
  17594. }
  17595. // Outline - step 1
  17596. var savedDepthWrite = engine.getDepthWrite();
  17597. if (this.renderOutline) {
  17598. engine.setDepthWrite(false);
  17599. scene.getOutlineRenderer().render(subMesh, batch);
  17600. engine.setDepthWrite(savedDepthWrite);
  17601. }
  17602. effectiveMaterial._preBind();
  17603. var effect = effectiveMaterial.getEffect();
  17604. // Bind
  17605. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  17606. this._bind(subMesh, effect, fillMode);
  17607. var world = this.getWorldMatrix();
  17608. effectiveMaterial.bind(world, this);
  17609. // Alpha mode
  17610. if (enableAlphaMode) {
  17611. engine.setAlphaMode(effectiveMaterial.alphaMode);
  17612. }
  17613. // Draw
  17614. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  17615. if (isInstance) {
  17616. effectiveMaterial.bindOnlyWorldMatrix(world);
  17617. }
  17618. });
  17619. // Unbind
  17620. effectiveMaterial.unbind();
  17621. // Outline - step 2
  17622. if (this.renderOutline && savedDepthWrite) {
  17623. engine.setDepthWrite(true);
  17624. engine.setColorWrite(false);
  17625. scene.getOutlineRenderer().render(subMesh, batch);
  17626. engine.setColorWrite(true);
  17627. }
  17628. // Overlay
  17629. if (this.renderOverlay) {
  17630. var currentMode = engine.getAlphaMode();
  17631. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  17632. scene.getOutlineRenderer().render(subMesh, batch, true);
  17633. engine.setAlphaMode(currentMode);
  17634. }
  17635. this.onAfterRenderObservable.notifyObservers(this);
  17636. };
  17637. /**
  17638. * Returns an array populated with `ParticleSystem` objects whose the mesh is the emitter.
  17639. */
  17640. Mesh.prototype.getEmittedParticleSystems = function () {
  17641. var results = new Array();
  17642. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  17643. var particleSystem = this.getScene().particleSystems[index];
  17644. if (particleSystem.emitter === this) {
  17645. results.push(particleSystem);
  17646. }
  17647. }
  17648. return results;
  17649. };
  17650. /**
  17651. * Returns an array populated with `ParticleSystem` objects whose the mesh or its children are the emitter.
  17652. */
  17653. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  17654. var results = new Array();
  17655. var descendants = this.getDescendants();
  17656. descendants.push(this);
  17657. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  17658. var particleSystem = this.getScene().particleSystems[index];
  17659. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  17660. results.push(particleSystem);
  17661. }
  17662. }
  17663. return results;
  17664. };
  17665. Mesh.prototype._checkDelayState = function () {
  17666. var _this = this;
  17667. var that = this;
  17668. var scene = this.getScene();
  17669. if (this._geometry) {
  17670. this._geometry.load(scene);
  17671. }
  17672. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17673. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  17674. scene._addPendingData(that);
  17675. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  17676. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  17677. if (data instanceof ArrayBuffer) {
  17678. _this._delayLoadingFunction(data, _this);
  17679. }
  17680. else {
  17681. _this._delayLoadingFunction(JSON.parse(data), _this);
  17682. }
  17683. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17684. scene._removePendingData(_this);
  17685. }, function () { }, scene.database, getBinaryData);
  17686. }
  17687. };
  17688. /**
  17689. * Boolean, true is the mesh in the frustum defined by the `Plane` objects from the `frustumPlanes` array parameter.
  17690. */
  17691. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  17692. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17693. return false;
  17694. }
  17695. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  17696. return false;
  17697. }
  17698. this._checkDelayState();
  17699. return true;
  17700. };
  17701. Mesh.prototype.setMaterialByID = function (id) {
  17702. var materials = this.getScene().materials;
  17703. var index;
  17704. for (index = 0; index < materials.length; index++) {
  17705. if (materials[index].id === id) {
  17706. this.material = materials[index];
  17707. return;
  17708. }
  17709. }
  17710. // Multi
  17711. var multiMaterials = this.getScene().multiMaterials;
  17712. for (index = 0; index < multiMaterials.length; index++) {
  17713. if (multiMaterials[index].id === id) {
  17714. this.material = multiMaterials[index];
  17715. return;
  17716. }
  17717. }
  17718. };
  17719. Mesh.prototype.getAnimatables = function () {
  17720. var results = [];
  17721. if (this.material) {
  17722. results.push(this.material);
  17723. }
  17724. if (this.skeleton) {
  17725. results.push(this.skeleton);
  17726. }
  17727. return results;
  17728. };
  17729. // Geometry
  17730. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  17731. // Position
  17732. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17733. return;
  17734. }
  17735. this._resetPointsArrayCache();
  17736. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17737. var temp = [];
  17738. var index;
  17739. for (index = 0; index < data.length; index += 3) {
  17740. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  17741. }
  17742. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  17743. // Normals
  17744. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17745. return;
  17746. }
  17747. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17748. temp = [];
  17749. for (index = 0; index < data.length; index += 3) {
  17750. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  17751. }
  17752. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  17753. // flip faces?
  17754. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  17755. this.flipFaces();
  17756. }
  17757. };
  17758. // Will apply current transform to mesh and reset world matrix
  17759. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  17760. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  17761. this.scaling.copyFromFloats(1, 1, 1);
  17762. this.position.copyFromFloats(0, 0, 0);
  17763. this.rotation.copyFromFloats(0, 0, 0);
  17764. //only if quaternion is already set
  17765. if (this.rotationQuaternion) {
  17766. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  17767. }
  17768. this._worldMatrix = BABYLON.Matrix.Identity();
  17769. };
  17770. // Cache
  17771. Mesh.prototype._resetPointsArrayCache = function () {
  17772. this._positions = null;
  17773. };
  17774. Mesh.prototype._generatePointsArray = function () {
  17775. if (this._positions)
  17776. return true;
  17777. this._positions = [];
  17778. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17779. if (!data) {
  17780. return false;
  17781. }
  17782. for (var index = 0; index < data.length; index += 3) {
  17783. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  17784. }
  17785. return true;
  17786. };
  17787. // Clone
  17788. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  17789. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  17790. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  17791. };
  17792. // Dispose
  17793. Mesh.prototype.dispose = function (doNotRecurse) {
  17794. if (this._geometry) {
  17795. this._geometry.releaseForMesh(this, true);
  17796. }
  17797. // Instances
  17798. if (this._worldMatricesInstancesBuffer) {
  17799. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  17800. this._worldMatricesInstancesBuffer = null;
  17801. }
  17802. while (this.instances.length) {
  17803. this.instances[0].dispose();
  17804. }
  17805. _super.prototype.dispose.call(this, doNotRecurse);
  17806. };
  17807. // Geometric tools
  17808. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  17809. var _this = this;
  17810. var scene = this.getScene();
  17811. var onload = function (img) {
  17812. // Getting height map data
  17813. var canvas = document.createElement("canvas");
  17814. var context = canvas.getContext("2d");
  17815. var heightMapWidth = img.width;
  17816. var heightMapHeight = img.height;
  17817. canvas.width = heightMapWidth;
  17818. canvas.height = heightMapHeight;
  17819. context.drawImage(img, 0, 0);
  17820. // Create VertexData from map data
  17821. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  17822. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  17823. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  17824. //execute success callback, if set
  17825. if (onSuccess) {
  17826. onSuccess(_this);
  17827. }
  17828. };
  17829. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  17830. };
  17831. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  17832. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  17833. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  17834. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17835. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  17836. return;
  17837. }
  17838. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17839. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17840. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17841. var position = BABYLON.Vector3.Zero();
  17842. var normal = BABYLON.Vector3.Zero();
  17843. var uv = BABYLON.Vector2.Zero();
  17844. for (var index = 0; index < positions.length; index += 3) {
  17845. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  17846. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  17847. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  17848. // Compute height
  17849. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  17850. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  17851. var pos = (u + v * heightMapWidth) * 4;
  17852. var r = buffer[pos] / 255.0;
  17853. var g = buffer[pos + 1] / 255.0;
  17854. var b = buffer[pos + 2] / 255.0;
  17855. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  17856. normal.normalize();
  17857. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  17858. position = position.add(normal);
  17859. position.toArray(positions, index);
  17860. }
  17861. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  17862. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  17863. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  17864. };
  17865. /**
  17866. * Modify the mesh to get a flat shading rendering.
  17867. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  17868. * Warning : the mesh is really modified.
  17869. */
  17870. Mesh.prototype.convertToFlatShadedMesh = function () {
  17871. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  17872. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  17873. var kinds = this.getVerticesDataKinds();
  17874. var vbs = [];
  17875. var data = [];
  17876. var newdata = [];
  17877. var updatableNormals = false;
  17878. var kindIndex;
  17879. var kind;
  17880. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17881. kind = kinds[kindIndex];
  17882. var vertexBuffer = this.getVertexBuffer(kind);
  17883. if (kind === BABYLON.VertexBuffer.NormalKind) {
  17884. updatableNormals = vertexBuffer.isUpdatable();
  17885. kinds.splice(kindIndex, 1);
  17886. kindIndex--;
  17887. continue;
  17888. }
  17889. vbs[kind] = vertexBuffer;
  17890. data[kind] = vbs[kind].getData();
  17891. newdata[kind] = [];
  17892. }
  17893. // Save previous submeshes
  17894. var previousSubmeshes = this.subMeshes.slice(0);
  17895. var indices = this.getIndices();
  17896. var totalIndices = this.getTotalIndices();
  17897. // Generating unique vertices per face
  17898. var index;
  17899. for (index = 0; index < totalIndices; index++) {
  17900. var vertexIndex = indices[index];
  17901. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17902. kind = kinds[kindIndex];
  17903. var stride = vbs[kind].getStrideSize();
  17904. for (var offset = 0; offset < stride; offset++) {
  17905. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  17906. }
  17907. }
  17908. }
  17909. // Updating faces & normal
  17910. var normals = [];
  17911. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  17912. for (index = 0; index < totalIndices; index += 3) {
  17913. indices[index] = index;
  17914. indices[index + 1] = index + 1;
  17915. indices[index + 2] = index + 2;
  17916. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  17917. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  17918. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  17919. var p1p2 = p1.subtract(p2);
  17920. var p3p2 = p3.subtract(p2);
  17921. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  17922. // Store same normals for every vertex
  17923. for (var localIndex = 0; localIndex < 3; localIndex++) {
  17924. normals.push(normal.x);
  17925. normals.push(normal.y);
  17926. normals.push(normal.z);
  17927. }
  17928. }
  17929. this.setIndices(indices);
  17930. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  17931. // Updating vertex buffers
  17932. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17933. kind = kinds[kindIndex];
  17934. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  17935. }
  17936. // Updating submeshes
  17937. this.releaseSubMeshes();
  17938. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  17939. var previousOne = previousSubmeshes[submeshIndex];
  17940. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  17941. }
  17942. this.synchronizeInstances();
  17943. };
  17944. /**
  17945. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  17946. * In other words, more vertices, no more indices and a single bigger VBO.
  17947. */
  17948. Mesh.prototype.convertToUnIndexedMesh = function () {
  17949. /// <summary>Remove indices by unfolding faces into buffers</summary>
  17950. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  17951. var kinds = this.getVerticesDataKinds();
  17952. var vbs = [];
  17953. var data = [];
  17954. var newdata = [];
  17955. var updatableNormals = false;
  17956. var kindIndex;
  17957. var kind;
  17958. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17959. kind = kinds[kindIndex];
  17960. var vertexBuffer = this.getVertexBuffer(kind);
  17961. vbs[kind] = vertexBuffer;
  17962. data[kind] = vbs[kind].getData();
  17963. newdata[kind] = [];
  17964. }
  17965. // Save previous submeshes
  17966. var previousSubmeshes = this.subMeshes.slice(0);
  17967. var indices = this.getIndices();
  17968. var totalIndices = this.getTotalIndices();
  17969. // Generating unique vertices per face
  17970. var index;
  17971. for (index = 0; index < totalIndices; index++) {
  17972. var vertexIndex = indices[index];
  17973. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17974. kind = kinds[kindIndex];
  17975. var stride = vbs[kind].getStrideSize();
  17976. for (var offset = 0; offset < stride; offset++) {
  17977. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  17978. }
  17979. }
  17980. }
  17981. // Updating indices
  17982. for (index = 0; index < totalIndices; index += 3) {
  17983. indices[index] = index;
  17984. indices[index + 1] = index + 1;
  17985. indices[index + 2] = index + 2;
  17986. }
  17987. this.setIndices(indices);
  17988. // Updating vertex buffers
  17989. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17990. kind = kinds[kindIndex];
  17991. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  17992. }
  17993. // Updating submeshes
  17994. this.releaseSubMeshes();
  17995. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  17996. var previousOne = previousSubmeshes[submeshIndex];
  17997. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  17998. }
  17999. this._unIndexed = true;
  18000. this.synchronizeInstances();
  18001. };
  18002. /**
  18003. * Inverses facet orientations and inverts also the normals with `flipNormals` (default false) if true.
  18004. * Warning : the mesh is really modified.
  18005. */
  18006. Mesh.prototype.flipFaces = function (flipNormals) {
  18007. if (flipNormals === void 0) { flipNormals = false; }
  18008. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  18009. var i;
  18010. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18011. for (i = 0; i < vertex_data.normals.length; i++) {
  18012. vertex_data.normals[i] *= -1;
  18013. }
  18014. }
  18015. var temp;
  18016. for (i = 0; i < vertex_data.indices.length; i += 3) {
  18017. // reassign indices
  18018. temp = vertex_data.indices[i + 1];
  18019. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  18020. vertex_data.indices[i + 2] = temp;
  18021. }
  18022. vertex_data.applyToMesh(this);
  18023. };
  18024. // Instances
  18025. /**
  18026. * Creates a new `InstancedMesh` object from the mesh model.
  18027. */
  18028. Mesh.prototype.createInstance = function (name) {
  18029. return new BABYLON.InstancedMesh(name, this);
  18030. };
  18031. Mesh.prototype.synchronizeInstances = function () {
  18032. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  18033. var instance = this.instances[instanceIndex];
  18034. instance._syncSubMeshes();
  18035. }
  18036. };
  18037. /**
  18038. * Simplify the mesh according to the given array of settings.
  18039. * Function will return immediately and will simplify async.
  18040. * @param settings a collection of simplification settings.
  18041. * @param parallelProcessing should all levels calculate parallel or one after the other.
  18042. * @param type the type of simplification to run.
  18043. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  18044. */
  18045. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  18046. if (parallelProcessing === void 0) { parallelProcessing = true; }
  18047. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  18048. this.getScene().simplificationQueue.addTask({
  18049. settings: settings,
  18050. parallelProcessing: parallelProcessing,
  18051. mesh: this,
  18052. simplificationType: simplificationType,
  18053. successCallback: successCallback
  18054. });
  18055. };
  18056. /**
  18057. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  18058. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  18059. * This should be used together with the simplification to avoid disappearing triangles.
  18060. * @param successCallback an optional success callback to be called after the optimization finished.
  18061. */
  18062. Mesh.prototype.optimizeIndices = function (successCallback) {
  18063. var _this = this;
  18064. var indices = this.getIndices();
  18065. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18066. var vectorPositions = [];
  18067. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  18068. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  18069. }
  18070. var dupes = [];
  18071. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  18072. var realPos = vectorPositions.length - 1 - iteration;
  18073. var testedPosition = vectorPositions[realPos];
  18074. for (var j = 0; j < realPos; ++j) {
  18075. var againstPosition = vectorPositions[j];
  18076. if (testedPosition.equals(againstPosition)) {
  18077. dupes[realPos] = j;
  18078. break;
  18079. }
  18080. }
  18081. }, function () {
  18082. for (var i = 0; i < indices.length; ++i) {
  18083. indices[i] = dupes[indices[i]] || indices[i];
  18084. }
  18085. //indices are now reordered
  18086. var originalSubMeshes = _this.subMeshes.slice(0);
  18087. _this.setIndices(indices);
  18088. _this.subMeshes = originalSubMeshes;
  18089. if (successCallback) {
  18090. successCallback(_this);
  18091. }
  18092. });
  18093. };
  18094. // Statics
  18095. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  18096. var mesh = new Mesh(parsedMesh.name, scene);
  18097. mesh.id = parsedMesh.id;
  18098. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18099. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18100. if (parsedMesh.rotationQuaternion) {
  18101. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18102. }
  18103. else if (parsedMesh.rotation) {
  18104. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18105. }
  18106. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18107. if (parsedMesh.localMatrix) {
  18108. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18109. }
  18110. else if (parsedMesh.pivotMatrix) {
  18111. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18112. }
  18113. mesh.setEnabled(parsedMesh.isEnabled);
  18114. mesh.isVisible = parsedMesh.isVisible;
  18115. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18116. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18117. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18118. if (parsedMesh.applyFog !== undefined) {
  18119. mesh.applyFog = parsedMesh.applyFog;
  18120. }
  18121. if (parsedMesh.pickable !== undefined) {
  18122. mesh.isPickable = parsedMesh.pickable;
  18123. }
  18124. if (parsedMesh.alphaIndex !== undefined) {
  18125. mesh.alphaIndex = parsedMesh.alphaIndex;
  18126. }
  18127. mesh.receiveShadows = parsedMesh.receiveShadows;
  18128. mesh.billboardMode = parsedMesh.billboardMode;
  18129. if (parsedMesh.visibility !== undefined) {
  18130. mesh.visibility = parsedMesh.visibility;
  18131. }
  18132. mesh.checkCollisions = parsedMesh.checkCollisions;
  18133. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18134. // freezeWorldMatrix
  18135. if (parsedMesh.freezeWorldMatrix) {
  18136. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  18137. }
  18138. // Parent
  18139. if (parsedMesh.parentId) {
  18140. mesh._waitingParentId = parsedMesh.parentId;
  18141. }
  18142. // Actions
  18143. if (parsedMesh.actions !== undefined) {
  18144. mesh._waitingActions = parsedMesh.actions;
  18145. }
  18146. // Geometry
  18147. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18148. if (parsedMesh.delayLoadingFile) {
  18149. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18150. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18151. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18152. if (parsedMesh._binaryInfo) {
  18153. mesh._binaryInfo = parsedMesh._binaryInfo;
  18154. }
  18155. mesh._delayInfo = [];
  18156. if (parsedMesh.hasUVs) {
  18157. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18158. }
  18159. if (parsedMesh.hasUVs2) {
  18160. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18161. }
  18162. if (parsedMesh.hasUVs3) {
  18163. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  18164. }
  18165. if (parsedMesh.hasUVs4) {
  18166. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  18167. }
  18168. if (parsedMesh.hasUVs5) {
  18169. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  18170. }
  18171. if (parsedMesh.hasUVs6) {
  18172. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  18173. }
  18174. if (parsedMesh.hasColors) {
  18175. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18176. }
  18177. if (parsedMesh.hasMatricesIndices) {
  18178. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18179. }
  18180. if (parsedMesh.hasMatricesWeights) {
  18181. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18182. }
  18183. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  18184. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18185. mesh._checkDelayState();
  18186. }
  18187. }
  18188. else {
  18189. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  18190. }
  18191. // Material
  18192. if (parsedMesh.materialId) {
  18193. mesh.setMaterialByID(parsedMesh.materialId);
  18194. }
  18195. else {
  18196. mesh.material = null;
  18197. }
  18198. // Skeleton
  18199. if (parsedMesh.skeletonId > -1) {
  18200. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18201. if (parsedMesh.numBoneInfluencers) {
  18202. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  18203. }
  18204. }
  18205. // Animations
  18206. if (parsedMesh.animations) {
  18207. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18208. var parsedAnimation = parsedMesh.animations[animationIndex];
  18209. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18210. }
  18211. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  18212. }
  18213. if (parsedMesh.autoAnimate) {
  18214. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  18215. }
  18216. // Layer Mask
  18217. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18218. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18219. }
  18220. else {
  18221. mesh.layerMask = 0x0FFFFFFF;
  18222. }
  18223. //(Deprecated) physics
  18224. if (parsedMesh.physicsImpostor) {
  18225. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  18226. mass: parsedMesh.physicsMass,
  18227. friction: parsedMesh.physicsFriction,
  18228. restitution: parsedMesh.physicsRestitution
  18229. }, scene);
  18230. }
  18231. // Instances
  18232. if (parsedMesh.instances) {
  18233. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18234. var parsedInstance = parsedMesh.instances[index];
  18235. var instance = mesh.createInstance(parsedInstance.name);
  18236. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18237. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18238. if (parsedInstance.rotationQuaternion) {
  18239. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18240. }
  18241. else if (parsedInstance.rotation) {
  18242. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18243. }
  18244. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18245. instance.checkCollisions = mesh.checkCollisions;
  18246. if (parsedMesh.animations) {
  18247. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18248. parsedAnimation = parsedMesh.animations[animationIndex];
  18249. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18250. }
  18251. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  18252. }
  18253. }
  18254. }
  18255. return mesh;
  18256. };
  18257. /**
  18258. * Creates a ribbon mesh.
  18259. * Please consider using the same method from the `MeshBuilder` class instead.
  18260. * 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.
  18261. *
  18262. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  18263. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  18264. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  18265. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  18266. * 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.
  18267. * 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.
  18268. * 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
  18269. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18270. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18271. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18272. */
  18273. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  18274. return BABYLON.MeshBuilder.CreateRibbon(name, {
  18275. pathArray: pathArray,
  18276. closeArray: closeArray,
  18277. closePath: closePath,
  18278. offset: offset,
  18279. updatable: updatable,
  18280. sideOrientation: sideOrientation,
  18281. instance: instance
  18282. }, scene);
  18283. };
  18284. /**
  18285. * Creates a plane polygonal mesh. By default, this is a disc.
  18286. * Please consider using the same method from the `MeshBuilder` class instead.
  18287. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  18288. * 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.
  18289. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18290. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18291. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18292. */
  18293. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  18294. var options = {
  18295. radius: radius,
  18296. tessellation: tessellation,
  18297. sideOrientation: sideOrientation,
  18298. updatable: updatable
  18299. };
  18300. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  18301. };
  18302. /**
  18303. * Creates a box mesh.
  18304. * Please consider using the same method from the `MeshBuilder` class instead.
  18305. * The parameter `size` sets the size (float) of each box side (default 1).
  18306. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18307. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18308. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18309. */
  18310. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  18311. var options = {
  18312. size: size,
  18313. sideOrientation: sideOrientation,
  18314. updatable: updatable
  18315. };
  18316. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  18317. };
  18318. /**
  18319. * Creates a sphere mesh.
  18320. * Please consider using the same method from the `MeshBuilder` class instead.
  18321. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  18322. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  18323. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18324. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18325. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18326. */
  18327. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  18328. var options = {
  18329. segments: segments,
  18330. diameterX: diameter,
  18331. diameterY: diameter,
  18332. diameterZ: diameter,
  18333. sideOrientation: sideOrientation,
  18334. updatable: updatable
  18335. };
  18336. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  18337. };
  18338. /**
  18339. * Creates a cylinder or a cone mesh.
  18340. * Please consider using the same method from the `MeshBuilder` class instead.
  18341. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  18342. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  18343. * 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.
  18344. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  18345. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  18346. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18347. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18348. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18349. */
  18350. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  18351. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  18352. if (scene !== undefined) {
  18353. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  18354. updatable = scene;
  18355. }
  18356. scene = subdivisions;
  18357. subdivisions = 1;
  18358. }
  18359. var options = {
  18360. height: height,
  18361. diameterTop: diameterTop,
  18362. diameterBottom: diameterBottom,
  18363. tessellation: tessellation,
  18364. subdivisions: subdivisions,
  18365. sideOrientation: sideOrientation,
  18366. updatable: updatable
  18367. };
  18368. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  18369. };
  18370. // Torus (Code from SharpDX.org)
  18371. /**
  18372. * Creates a torus mesh.
  18373. * Please consider using the same method from the `MeshBuilder` class instead.
  18374. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  18375. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  18376. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  18377. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18378. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18379. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18380. */
  18381. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  18382. var options = {
  18383. diameter: diameter,
  18384. thickness: thickness,
  18385. tessellation: tessellation,
  18386. sideOrientation: sideOrientation,
  18387. updatable: updatable
  18388. };
  18389. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  18390. };
  18391. /**
  18392. * Creates a torus knot mesh.
  18393. * Please consider using the same method from the `MeshBuilder` class instead.
  18394. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  18395. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  18396. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  18397. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  18398. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18399. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18400. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18401. */
  18402. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  18403. var options = {
  18404. radius: radius,
  18405. tube: tube,
  18406. radialSegments: radialSegments,
  18407. tubularSegments: tubularSegments,
  18408. p: p,
  18409. q: q,
  18410. sideOrientation: sideOrientation,
  18411. updatable: updatable
  18412. };
  18413. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  18414. };
  18415. /**
  18416. * Creates a line mesh.
  18417. * Please consider using the same method from the `MeshBuilder` class instead.
  18418. * 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.
  18419. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18420. * The parameter `points` is an array successive Vector3.
  18421. * 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
  18422. * When updating an instance, remember that only point positions can change, not the number of points.
  18423. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18424. */
  18425. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  18426. var options = {
  18427. points: points,
  18428. updatable: updatable,
  18429. instance: instance
  18430. };
  18431. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  18432. };
  18433. /**
  18434. * Creates a dashed line mesh.
  18435. * Please consider using the same method from the `MeshBuilder` class instead.
  18436. * 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.
  18437. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18438. * The parameter `points` is an array successive Vector3.
  18439. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  18440. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  18441. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  18442. * 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
  18443. * When updating an instance, remember that only point positions can change, not the number of points.
  18444. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18445. */
  18446. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  18447. var options = {
  18448. points: points,
  18449. dashSize: dashSize,
  18450. gapSize: gapSize,
  18451. dashNb: dashNb,
  18452. updatable: updatable
  18453. };
  18454. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  18455. };
  18456. /**
  18457. * Creates an extruded shape mesh.
  18458. * 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.
  18459. * Please consider using the same method from the `MeshBuilder` class instead.
  18460. *
  18461. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18462. * 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
  18463. * extruded along the Z axis.
  18464. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18465. * 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.
  18466. * The parameter `scale` (float, default 1) is the value to scale the shape.
  18467. * 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
  18468. * 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
  18469. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18470. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18471. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18472. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18473. */
  18474. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  18475. var options = {
  18476. shape: shape,
  18477. path: path,
  18478. scale: scale,
  18479. rotation: rotation,
  18480. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  18481. sideOrientation: sideOrientation,
  18482. instance: instance,
  18483. updatable: updatable
  18484. };
  18485. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  18486. };
  18487. /**
  18488. * Creates an custom extruded shape mesh.
  18489. * 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.
  18490. * Please consider using the same method from the `MeshBuilder` class instead.
  18491. *
  18492. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18493. * 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
  18494. * extruded along the Z axis.
  18495. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18496. * 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
  18497. * and the distance of this point from the begining of the path :
  18498. * ```rotationFunction = function(i, distance) {
  18499. * // do things
  18500. * return rotationValue; }```
  18501. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  18502. * 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
  18503. * and the distance of this point from the begining of the path :
  18504. * ````scaleFunction = function(i, distance) {
  18505. * // do things
  18506. * return scaleValue;}```
  18507. * It must returns a float value that will be the scale value applied to the shape on each path point.
  18508. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  18509. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  18510. * 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
  18511. * 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
  18512. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18513. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18514. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18515. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18516. */
  18517. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  18518. var options = {
  18519. shape: shape,
  18520. path: path,
  18521. scaleFunction: scaleFunction,
  18522. rotationFunction: rotationFunction,
  18523. ribbonCloseArray: ribbonCloseArray,
  18524. ribbonClosePath: ribbonClosePath,
  18525. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  18526. sideOrientation: sideOrientation,
  18527. instance: instance,
  18528. updatable: updatable
  18529. };
  18530. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  18531. };
  18532. /**
  18533. * Creates lathe mesh.
  18534. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  18535. * Please consider using the same method from the `MeshBuilder` class instead.
  18536. *
  18537. * 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
  18538. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  18539. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  18540. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  18541. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18542. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18543. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18544. */
  18545. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  18546. var options = {
  18547. shape: shape,
  18548. radius: radius,
  18549. tessellation: tessellation,
  18550. sideOrientation: sideOrientation,
  18551. updatable: updatable
  18552. };
  18553. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  18554. };
  18555. /**
  18556. * Creates a plane mesh.
  18557. * Please consider using the same method from the `MeshBuilder` class instead.
  18558. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  18559. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18560. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18561. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18562. */
  18563. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  18564. var options = {
  18565. size: size,
  18566. width: size,
  18567. height: size,
  18568. sideOrientation: sideOrientation,
  18569. updatable: updatable
  18570. };
  18571. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  18572. };
  18573. /**
  18574. * Creates a ground mesh.
  18575. * Please consider using the same method from the `MeshBuilder` class instead.
  18576. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  18577. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  18578. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18579. */
  18580. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  18581. var options = {
  18582. width: width,
  18583. height: height,
  18584. subdivisions: subdivisions,
  18585. updatable: updatable
  18586. };
  18587. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  18588. };
  18589. /**
  18590. * Creates a tiled ground mesh.
  18591. * Please consider using the same method from the `MeshBuilder` class instead.
  18592. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  18593. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  18594. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  18595. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  18596. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  18597. * numbers of subdivisions on the ground width and height of each tile.
  18598. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18599. */
  18600. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  18601. var options = {
  18602. xmin: xmin,
  18603. zmin: zmin,
  18604. xmax: xmax,
  18605. zmax: zmax,
  18606. subdivisions: subdivisions,
  18607. precision: precision,
  18608. updatable: updatable
  18609. };
  18610. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  18611. };
  18612. /**
  18613. * Creates a ground mesh from a height map.
  18614. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  18615. * Please consider using the same method from the `MeshBuilder` class instead.
  18616. * The parameter `url` sets the URL of the height map image resource.
  18617. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  18618. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  18619. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  18620. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  18621. * 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).
  18622. * This function is passed the newly built mesh : ```function(mesh) { // do things
  18623. * return; }```
  18624. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18625. */
  18626. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  18627. var options = {
  18628. width: width,
  18629. height: height,
  18630. subdivisions: subdivisions,
  18631. minHeight: minHeight,
  18632. maxHeight: maxHeight,
  18633. updatable: updatable,
  18634. onReady: onReady
  18635. };
  18636. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  18637. };
  18638. /**
  18639. * Creates a tube mesh.
  18640. * 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.
  18641. *
  18642. * Please consider using the same method from the `MeshBuilder` class instead.
  18643. * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
  18644. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  18645. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  18646. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  18647. * 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.
  18648. * It must return a radius value (positive float) :
  18649. * ```var radiusFunction = function(i, distance) {
  18650. * // do things
  18651. * return radius; }```
  18652. * 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
  18653. * 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
  18654. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18655. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18656. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18657. */
  18658. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  18659. var options = {
  18660. path: path,
  18661. radius: radius,
  18662. tessellation: tessellation,
  18663. radiusFunction: radiusFunction,
  18664. arc: 1,
  18665. cap: cap,
  18666. updatable: updatable,
  18667. sideOrientation: sideOrientation,
  18668. instance: instance
  18669. };
  18670. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  18671. };
  18672. /**
  18673. * Creates a polyhedron mesh.
  18674. *
  18675. * Please consider using the same method from the `MeshBuilder` class instead.
  18676. * 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
  18677. * to choose the wanted type.
  18678. * The parameter `size` (positive float, default 1) sets the polygon size.
  18679. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  18680. * 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`.
  18681. * 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
  18682. * 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)`).
  18683. * 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
  18684. * 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.
  18685. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18686. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18687. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18688. */
  18689. Mesh.CreatePolyhedron = function (name, options, scene) {
  18690. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  18691. };
  18692. /**
  18693. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  18694. * Please consider using the same method from the `MeshBuilder` class instead.
  18695. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  18696. * 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`).
  18697. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  18698. * 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.
  18699. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18700. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18701. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18702. */
  18703. Mesh.CreateIcoSphere = function (name, options, scene) {
  18704. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  18705. };
  18706. /**
  18707. * Creates a decal mesh.
  18708. * Please consider using the same method from the `MeshBuilder` class instead.
  18709. * 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.
  18710. * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  18711. * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  18712. * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
  18713. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  18714. */
  18715. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  18716. var options = {
  18717. position: position,
  18718. normal: normal,
  18719. size: size,
  18720. angle: angle
  18721. };
  18722. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  18723. };
  18724. // Skeletons
  18725. /**
  18726. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  18727. */
  18728. Mesh.prototype.setPositionsForCPUSkinning = function () {
  18729. var source;
  18730. if (!this._sourcePositions) {
  18731. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18732. this._sourcePositions = new Float32Array(source);
  18733. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  18734. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  18735. }
  18736. }
  18737. return this._sourcePositions;
  18738. };
  18739. /**
  18740. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  18741. */
  18742. Mesh.prototype.setNormalsForCPUSkinning = function () {
  18743. var source;
  18744. if (!this._sourceNormals) {
  18745. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18746. this._sourceNormals = new Float32Array(source);
  18747. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  18748. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  18749. }
  18750. }
  18751. return this._sourceNormals;
  18752. };
  18753. /**
  18754. * Update the vertex buffers by applying transformation from the bones
  18755. * @param {skeleton} skeleton to apply
  18756. */
  18757. Mesh.prototype.applySkeleton = function (skeleton) {
  18758. if (!this.geometry) {
  18759. return;
  18760. }
  18761. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  18762. return;
  18763. }
  18764. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  18765. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18766. return this;
  18767. }
  18768. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18769. return this;
  18770. }
  18771. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  18772. return this;
  18773. }
  18774. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  18775. return this;
  18776. }
  18777. if (!this._sourcePositions) {
  18778. this.setPositionsForCPUSkinning();
  18779. }
  18780. if (!this._sourceNormals) {
  18781. this.setNormalsForCPUSkinning();
  18782. }
  18783. // positionsData checks for not being Float32Array will only pass at most once
  18784. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18785. if (!(positionsData instanceof Float32Array)) {
  18786. positionsData = new Float32Array(positionsData);
  18787. }
  18788. // normalsData checks for not being Float32Array will only pass at most once
  18789. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18790. if (!(normalsData instanceof Float32Array)) {
  18791. normalsData = new Float32Array(normalsData);
  18792. }
  18793. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  18794. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  18795. var needExtras = this.numBoneInfluencers > 4;
  18796. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  18797. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  18798. var skeletonMatrices = skeleton.getTransformMatrices(this);
  18799. var tempVector3 = BABYLON.Vector3.Zero();
  18800. var finalMatrix = new BABYLON.Matrix();
  18801. var tempMatrix = new BABYLON.Matrix();
  18802. var matWeightIdx = 0;
  18803. var inf;
  18804. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  18805. var weight;
  18806. for (inf = 0; inf < 4; inf++) {
  18807. weight = matricesWeightsData[matWeightIdx + inf];
  18808. if (weight > 0) {
  18809. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  18810. finalMatrix.addToSelf(tempMatrix);
  18811. }
  18812. else
  18813. break;
  18814. }
  18815. if (needExtras) {
  18816. for (inf = 0; inf < 4; inf++) {
  18817. weight = matricesWeightsExtraData[matWeightIdx + inf];
  18818. if (weight > 0) {
  18819. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  18820. finalMatrix.addToSelf(tempMatrix);
  18821. }
  18822. else
  18823. break;
  18824. }
  18825. }
  18826. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  18827. tempVector3.toArray(positionsData, index);
  18828. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  18829. tempVector3.toArray(normalsData, index);
  18830. finalMatrix.reset();
  18831. }
  18832. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  18833. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  18834. return this;
  18835. };
  18836. // Tools
  18837. Mesh.MinMax = function (meshes) {
  18838. var minVector = null;
  18839. var maxVector = null;
  18840. for (var i in meshes) {
  18841. var mesh = meshes[i];
  18842. var boundingBox = mesh.getBoundingInfo().boundingBox;
  18843. if (!minVector) {
  18844. minVector = boundingBox.minimumWorld;
  18845. maxVector = boundingBox.maximumWorld;
  18846. continue;
  18847. }
  18848. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  18849. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  18850. }
  18851. return {
  18852. min: minVector,
  18853. max: maxVector
  18854. };
  18855. };
  18856. Mesh.Center = function (meshesOrMinMaxVector) {
  18857. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  18858. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  18859. };
  18860. /**
  18861. * Merge the array of meshes into a single mesh for performance reasons.
  18862. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  18863. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  18864. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  18865. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  18866. */
  18867. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  18868. if (disposeSource === void 0) { disposeSource = true; }
  18869. var index;
  18870. if (!allow32BitsIndices) {
  18871. var totalVertices = 0;
  18872. // Counting vertices
  18873. for (index = 0; index < meshes.length; index++) {
  18874. if (meshes[index]) {
  18875. totalVertices += meshes[index].getTotalVertices();
  18876. if (totalVertices > 65536) {
  18877. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  18878. return null;
  18879. }
  18880. }
  18881. }
  18882. }
  18883. // Merge
  18884. var vertexData;
  18885. var otherVertexData;
  18886. var source;
  18887. for (index = 0; index < meshes.length; index++) {
  18888. if (meshes[index]) {
  18889. meshes[index].computeWorldMatrix(true);
  18890. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  18891. otherVertexData.transform(meshes[index].getWorldMatrix());
  18892. if (vertexData) {
  18893. vertexData.merge(otherVertexData);
  18894. }
  18895. else {
  18896. vertexData = otherVertexData;
  18897. source = meshes[index];
  18898. }
  18899. }
  18900. }
  18901. if (!meshSubclass) {
  18902. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  18903. }
  18904. vertexData.applyToMesh(meshSubclass);
  18905. // Setting properties
  18906. meshSubclass.material = source.material;
  18907. meshSubclass.checkCollisions = source.checkCollisions;
  18908. // Cleaning
  18909. if (disposeSource) {
  18910. for (index = 0; index < meshes.length; index++) {
  18911. if (meshes[index]) {
  18912. meshes[index].dispose();
  18913. }
  18914. }
  18915. }
  18916. return meshSubclass;
  18917. };
  18918. // Consts
  18919. Mesh._FRONTSIDE = 0;
  18920. Mesh._BACKSIDE = 1;
  18921. Mesh._DOUBLESIDE = 2;
  18922. Mesh._DEFAULTSIDE = 0;
  18923. Mesh._NO_CAP = 0;
  18924. Mesh._CAP_START = 1;
  18925. Mesh._CAP_END = 2;
  18926. Mesh._CAP_ALL = 3;
  18927. return Mesh;
  18928. })(BABYLON.AbstractMesh);
  18929. BABYLON.Mesh = Mesh;
  18930. })(BABYLON || (BABYLON = {}));
  18931. var BABYLON;
  18932. (function (BABYLON) {
  18933. var SubMesh = (function () {
  18934. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  18935. if (createBoundingBox === void 0) { createBoundingBox = true; }
  18936. this.materialIndex = materialIndex;
  18937. this.verticesStart = verticesStart;
  18938. this.verticesCount = verticesCount;
  18939. this.indexStart = indexStart;
  18940. this.indexCount = indexCount;
  18941. this._renderId = 0;
  18942. this._mesh = mesh;
  18943. this._renderingMesh = renderingMesh || mesh;
  18944. mesh.subMeshes.push(this);
  18945. this._trianglePlanes = [];
  18946. this._id = mesh.subMeshes.length - 1;
  18947. if (createBoundingBox) {
  18948. this.refreshBoundingInfo();
  18949. mesh.computeWorldMatrix(true);
  18950. }
  18951. }
  18952. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  18953. get: function () {
  18954. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  18955. },
  18956. enumerable: true,
  18957. configurable: true
  18958. });
  18959. SubMesh.prototype.getBoundingInfo = function () {
  18960. if (this.IsGlobal) {
  18961. return this._mesh.getBoundingInfo();
  18962. }
  18963. return this._boundingInfo;
  18964. };
  18965. SubMesh.prototype.getMesh = function () {
  18966. return this._mesh;
  18967. };
  18968. SubMesh.prototype.getRenderingMesh = function () {
  18969. return this._renderingMesh;
  18970. };
  18971. SubMesh.prototype.getMaterial = function () {
  18972. var rootMaterial = this._renderingMesh.material;
  18973. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  18974. var multiMaterial = rootMaterial;
  18975. return multiMaterial.getSubMaterial(this.materialIndex);
  18976. }
  18977. if (!rootMaterial) {
  18978. return this._mesh.getScene().defaultMaterial;
  18979. }
  18980. return rootMaterial;
  18981. };
  18982. // Methods
  18983. SubMesh.prototype.refreshBoundingInfo = function () {
  18984. this._lastColliderWorldVertices = null;
  18985. if (this.IsGlobal) {
  18986. return;
  18987. }
  18988. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18989. if (!data) {
  18990. this._boundingInfo = this._mesh._boundingInfo;
  18991. return;
  18992. }
  18993. var indices = this._renderingMesh.getIndices();
  18994. var extend;
  18995. //is this the only submesh?
  18996. if (this.indexStart === 0 && this.indexCount === indices.length) {
  18997. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  18998. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  18999. }
  19000. else {
  19001. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  19002. }
  19003. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19004. };
  19005. SubMesh.prototype._checkCollision = function (collider) {
  19006. return this.getBoundingInfo()._checkCollision(collider);
  19007. };
  19008. SubMesh.prototype.updateBoundingInfo = function (world) {
  19009. if (!this.getBoundingInfo()) {
  19010. this.refreshBoundingInfo();
  19011. }
  19012. this.getBoundingInfo().update(world);
  19013. };
  19014. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  19015. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  19016. };
  19017. SubMesh.prototype.render = function (enableAlphaMode) {
  19018. this._renderingMesh.render(this, enableAlphaMode);
  19019. };
  19020. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  19021. if (!this._linesIndexBuffer) {
  19022. var linesIndices = [];
  19023. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  19024. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  19025. }
  19026. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  19027. this.linesIndexCount = linesIndices.length;
  19028. }
  19029. return this._linesIndexBuffer;
  19030. };
  19031. SubMesh.prototype.canIntersects = function (ray) {
  19032. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  19033. };
  19034. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  19035. var intersectInfo = null;
  19036. // LineMesh first as it's also a Mesh...
  19037. if (this._mesh instanceof BABYLON.LinesMesh) {
  19038. var lineMesh = this._mesh;
  19039. // Line test
  19040. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  19041. var p0 = positions[indices[index]];
  19042. var p1 = positions[indices[index + 1]];
  19043. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  19044. if (length < 0) {
  19045. continue;
  19046. }
  19047. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  19048. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  19049. if (fastCheck) {
  19050. break;
  19051. }
  19052. }
  19053. }
  19054. }
  19055. else {
  19056. // Triangles test
  19057. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  19058. var p0 = positions[indices[index]];
  19059. var p1 = positions[indices[index + 1]];
  19060. var p2 = positions[indices[index + 2]];
  19061. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  19062. if (currentIntersectInfo) {
  19063. if (currentIntersectInfo.distance < 0) {
  19064. continue;
  19065. }
  19066. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  19067. intersectInfo = currentIntersectInfo;
  19068. intersectInfo.faceId = index / 3;
  19069. if (fastCheck) {
  19070. break;
  19071. }
  19072. }
  19073. }
  19074. }
  19075. }
  19076. return intersectInfo;
  19077. };
  19078. // Clone
  19079. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  19080. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  19081. if (!this.IsGlobal) {
  19082. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  19083. }
  19084. return result;
  19085. };
  19086. // Dispose
  19087. SubMesh.prototype.dispose = function () {
  19088. if (this._linesIndexBuffer) {
  19089. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  19090. this._linesIndexBuffer = null;
  19091. }
  19092. // Remove from mesh
  19093. var index = this._mesh.subMeshes.indexOf(this);
  19094. this._mesh.subMeshes.splice(index, 1);
  19095. };
  19096. // Statics
  19097. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  19098. var minVertexIndex = Number.MAX_VALUE;
  19099. var maxVertexIndex = -Number.MAX_VALUE;
  19100. renderingMesh = renderingMesh || mesh;
  19101. var indices = renderingMesh.getIndices();
  19102. for (var index = startIndex; index < startIndex + indexCount; index++) {
  19103. var vertexIndex = indices[index];
  19104. if (vertexIndex < minVertexIndex)
  19105. minVertexIndex = vertexIndex;
  19106. if (vertexIndex > maxVertexIndex)
  19107. maxVertexIndex = vertexIndex;
  19108. }
  19109. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  19110. };
  19111. return SubMesh;
  19112. })();
  19113. BABYLON.SubMesh = SubMesh;
  19114. })(BABYLON || (BABYLON = {}));
  19115. var BABYLON;
  19116. (function (BABYLON) {
  19117. var MeshBuilder = (function () {
  19118. function MeshBuilder() {
  19119. }
  19120. /**
  19121. * Creates a box mesh.
  19122. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  19123. * The parameter `size` sets the size (float) of each box side (default 1).
  19124. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  19125. * 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).
  19126. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  19127. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19128. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19129. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19130. */
  19131. MeshBuilder.CreateBox = function (name, options, scene) {
  19132. var box = new BABYLON.Mesh(name, scene);
  19133. var vertexData = BABYLON.VertexData.CreateBox(options);
  19134. vertexData.applyToMesh(box, options.updatable);
  19135. return box;
  19136. };
  19137. /**
  19138. * Creates a sphere mesh.
  19139. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  19140. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  19141. * 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`).
  19142. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  19143. * 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
  19144. * 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).
  19145. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19146. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19147. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19148. */
  19149. MeshBuilder.CreateSphere = function (name, options, scene) {
  19150. var sphere = new BABYLON.Mesh(name, scene);
  19151. var vertexData = BABYLON.VertexData.CreateSphere(options);
  19152. vertexData.applyToMesh(sphere, options.updatable);
  19153. return sphere;
  19154. };
  19155. /**
  19156. * Creates a plane polygonal mesh. By default, this is a disc.
  19157. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  19158. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  19159. * 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.
  19160. * 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
  19161. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19162. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19163. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19164. */
  19165. MeshBuilder.CreateDisc = function (name, options, scene) {
  19166. var disc = new BABYLON.Mesh(name, scene);
  19167. var vertexData = BABYLON.VertexData.CreateDisc(options);
  19168. vertexData.applyToMesh(disc, options.updatable);
  19169. return disc;
  19170. };
  19171. /**
  19172. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  19173. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  19174. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  19175. * 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`).
  19176. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  19177. * 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.
  19178. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19179. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19180. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19181. */
  19182. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  19183. var sphere = new BABYLON.Mesh(name, scene);
  19184. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  19185. vertexData.applyToMesh(sphere, options.updatable);
  19186. return sphere;
  19187. };
  19188. ;
  19189. /**
  19190. * Creates a ribbon mesh.
  19191. * 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.
  19192. *
  19193. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  19194. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  19195. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  19196. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  19197. * 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.
  19198. * 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.
  19199. * 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
  19200. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19201. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19202. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19203. */
  19204. MeshBuilder.CreateRibbon = function (name, options, scene) {
  19205. var pathArray = options.pathArray;
  19206. var closeArray = options.closeArray;
  19207. var closePath = options.closePath;
  19208. var offset = options.offset;
  19209. var sideOrientation = options.sideOrientation;
  19210. var instance = options.instance;
  19211. var updatable = options.updatable;
  19212. if (instance) {
  19213. // positionFunction : ribbon case
  19214. // only pathArray and sideOrientation parameters are taken into account for positions update
  19215. var positionFunction = function (positions) {
  19216. var minlg = pathArray[0].length;
  19217. var i = 0;
  19218. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  19219. for (var si = 1; si <= ns; si++) {
  19220. for (var p = 0; p < pathArray.length; p++) {
  19221. var path = pathArray[p];
  19222. var l = path.length;
  19223. minlg = (minlg < l) ? minlg : l;
  19224. var j = 0;
  19225. while (j < minlg) {
  19226. positions[i] = path[j].x;
  19227. positions[i + 1] = path[j].y;
  19228. positions[i + 2] = path[j].z;
  19229. j++;
  19230. i += 3;
  19231. }
  19232. if (instance._closePath) {
  19233. positions[i] = path[0].x;
  19234. positions[i + 1] = path[0].y;
  19235. positions[i + 2] = path[0].z;
  19236. i += 3;
  19237. }
  19238. }
  19239. }
  19240. };
  19241. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19242. positionFunction(positions);
  19243. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19244. if (!(instance.areNormalsFrozen)) {
  19245. var indices = instance.getIndices();
  19246. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19247. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19248. if (instance._closePath) {
  19249. var indexFirst = 0;
  19250. var indexLast = 0;
  19251. for (var p = 0; p < pathArray.length; p++) {
  19252. indexFirst = instance._idx[p] * 3;
  19253. if (p + 1 < pathArray.length) {
  19254. indexLast = (instance._idx[p + 1] - 1) * 3;
  19255. }
  19256. else {
  19257. indexLast = normals.length - 3;
  19258. }
  19259. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  19260. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  19261. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  19262. normals[indexLast] = normals[indexFirst];
  19263. normals[indexLast + 1] = normals[indexFirst + 1];
  19264. normals[indexLast + 2] = normals[indexFirst + 2];
  19265. }
  19266. }
  19267. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19268. }
  19269. return instance;
  19270. }
  19271. else {
  19272. var ribbon = new BABYLON.Mesh(name, scene);
  19273. ribbon.sideOrientation = sideOrientation;
  19274. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  19275. if (closePath) {
  19276. ribbon._idx = vertexData._idx;
  19277. }
  19278. ribbon._closePath = closePath;
  19279. ribbon._closeArray = closeArray;
  19280. vertexData.applyToMesh(ribbon, updatable);
  19281. return ribbon;
  19282. }
  19283. };
  19284. /**
  19285. * Creates a cylinder or a cone mesh.
  19286. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  19287. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  19288. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  19289. * 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.
  19290. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  19291. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  19292. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  19293. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  19294. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  19295. * 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).
  19296. * 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
  19297. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  19298. * 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
  19299. * 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.
  19300. * If `enclose` is false, a ring surface is one element.
  19301. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  19302. * 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
  19303. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19304. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19305. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19306. */
  19307. MeshBuilder.CreateCylinder = function (name, options, scene) {
  19308. var cylinder = new BABYLON.Mesh(name, scene);
  19309. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  19310. vertexData.applyToMesh(cylinder, options.updatable);
  19311. return cylinder;
  19312. };
  19313. /**
  19314. * Creates a torus mesh.
  19315. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  19316. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  19317. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  19318. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  19319. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19320. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19321. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19322. */
  19323. MeshBuilder.CreateTorus = function (name, options, scene) {
  19324. var torus = new BABYLON.Mesh(name, scene);
  19325. var vertexData = BABYLON.VertexData.CreateTorus(options);
  19326. vertexData.applyToMesh(torus, options.updatable);
  19327. return torus;
  19328. };
  19329. /**
  19330. * Creates a torus knot mesh.
  19331. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  19332. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  19333. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  19334. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  19335. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  19336. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19337. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19338. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19339. */
  19340. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  19341. var torusKnot = new BABYLON.Mesh(name, scene);
  19342. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  19343. vertexData.applyToMesh(torusKnot, options.updatable);
  19344. return torusKnot;
  19345. };
  19346. /**
  19347. * Creates a line system mesh.
  19348. * A line system is a pool of many lines gathered in a single mesh.
  19349. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  19350. * 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.
  19351. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  19352. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  19353. * 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
  19354. * 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
  19355. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  19356. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19357. */
  19358. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  19359. var instance = options.instance;
  19360. var lines = options.lines;
  19361. if (instance) {
  19362. var positionFunction = function (positions) {
  19363. var i = 0;
  19364. for (var l = 0; l < lines.length; l++) {
  19365. var points = lines[l];
  19366. for (var p = 0; p < points.length; p++) {
  19367. positions[i] = points[p].x;
  19368. positions[i + 1] = points[p].y;
  19369. positions[i + 2] = points[p].z;
  19370. i += 3;
  19371. }
  19372. }
  19373. };
  19374. instance.updateMeshPositions(positionFunction, false);
  19375. return instance;
  19376. }
  19377. // line system creation
  19378. var lineSystem = new BABYLON.LinesMesh(name, scene);
  19379. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  19380. vertexData.applyToMesh(lineSystem, options.updatable);
  19381. return lineSystem;
  19382. };
  19383. /**
  19384. * Creates a line mesh.
  19385. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  19386. * 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.
  19387. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19388. * The parameter `points` is an array successive Vector3.
  19389. * 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
  19390. * When updating an instance, remember that only point positions can change, not the number of points.
  19391. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19392. */
  19393. MeshBuilder.CreateLines = function (name, options, scene) {
  19394. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  19395. return lines;
  19396. };
  19397. /**
  19398. * Creates a dashed line mesh.
  19399. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  19400. * 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.
  19401. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19402. * The parameter `points` is an array successive Vector3.
  19403. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  19404. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  19405. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  19406. * 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
  19407. * When updating an instance, remember that only point positions can change, not the number of points.
  19408. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19409. */
  19410. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  19411. var points = options.points;
  19412. var instance = options.instance;
  19413. var gapSize = options.gapSize;
  19414. var dashNb = options.dashNb;
  19415. var dashSize = options.dashSize;
  19416. if (instance) {
  19417. var positionFunction = function (positions) {
  19418. var curvect = BABYLON.Vector3.Zero();
  19419. var nbSeg = positions.length / 6;
  19420. var lg = 0;
  19421. var nb = 0;
  19422. var shft = 0;
  19423. var dashshft = 0;
  19424. var curshft = 0;
  19425. var p = 0;
  19426. var i = 0;
  19427. var j = 0;
  19428. for (i = 0; i < points.length - 1; i++) {
  19429. points[i + 1].subtractToRef(points[i], curvect);
  19430. lg += curvect.length();
  19431. }
  19432. shft = lg / nbSeg;
  19433. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  19434. for (i = 0; i < points.length - 1; i++) {
  19435. points[i + 1].subtractToRef(points[i], curvect);
  19436. nb = Math.floor(curvect.length() / shft);
  19437. curvect.normalize();
  19438. j = 0;
  19439. while (j < nb && p < positions.length) {
  19440. curshft = shft * j;
  19441. positions[p] = points[i].x + curshft * curvect.x;
  19442. positions[p + 1] = points[i].y + curshft * curvect.y;
  19443. positions[p + 2] = points[i].z + curshft * curvect.z;
  19444. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  19445. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  19446. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  19447. p += 6;
  19448. j++;
  19449. }
  19450. }
  19451. while (p < positions.length) {
  19452. positions[p] = points[i].x;
  19453. positions[p + 1] = points[i].y;
  19454. positions[p + 2] = points[i].z;
  19455. p += 3;
  19456. }
  19457. };
  19458. instance.updateMeshPositions(positionFunction, false);
  19459. return instance;
  19460. }
  19461. // dashed lines creation
  19462. var dashedLines = new BABYLON.LinesMesh(name, scene);
  19463. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  19464. vertexData.applyToMesh(dashedLines, options.updatable);
  19465. dashedLines.dashSize = dashSize;
  19466. dashedLines.gapSize = gapSize;
  19467. return dashedLines;
  19468. };
  19469. /**
  19470. * Creates an extruded shape mesh.
  19471. * 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.
  19472. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  19473. *
  19474. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19475. * 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
  19476. * extruded along the Z axis.
  19477. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19478. * 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.
  19479. * The parameter `scale` (float, default 1) is the value to scale the shape.
  19480. * 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
  19481. * 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
  19482. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19483. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19484. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19485. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19486. */
  19487. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  19488. var path = options.path;
  19489. var shape = options.shape;
  19490. var scale = options.scale || 1;
  19491. var rotation = options.rotation || 0;
  19492. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  19493. var updatable = options.updatable;
  19494. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19495. var instance = options.instance;
  19496. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  19497. };
  19498. /**
  19499. * Creates an custom extruded shape mesh.
  19500. * 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.
  19501. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  19502. *
  19503. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19504. * 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
  19505. * extruded along the Z axis.
  19506. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19507. * 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
  19508. * and the distance of this point from the begining of the path :
  19509. * ```rotationFunction = function(i, distance) {
  19510. * // do things
  19511. * return rotationValue; }```
  19512. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  19513. * 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
  19514. * and the distance of this point from the begining of the path :
  19515. * ````scaleFunction = function(i, distance) {
  19516. * // do things
  19517. * return scaleValue;}```
  19518. * It must returns a float value that will be the scale value applied to the shape on each path point.
  19519. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  19520. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  19521. * 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
  19522. * 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
  19523. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19524. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19525. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19526. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19527. */
  19528. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  19529. var path = options.path;
  19530. var shape = options.shape;
  19531. var scaleFunction = options.scaleFunction || (function () { return 1; });
  19532. var rotationFunction = options.rotationFunction || (function () { return 0; });
  19533. var ribbonCloseArray = options.ribbonCloseArray || false;
  19534. var ribbonClosePath = options.ribbonClosePath || false;
  19535. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  19536. var updatable = options.updatable;
  19537. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19538. var instance = options.instance;
  19539. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  19540. };
  19541. /**
  19542. * Creates lathe mesh.
  19543. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  19544. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  19545. *
  19546. * 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
  19547. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  19548. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  19549. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  19550. * 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.
  19551. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  19552. * 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
  19553. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19554. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19555. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19556. */
  19557. MeshBuilder.CreateLathe = function (name, options, scene) {
  19558. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  19559. var closed = (options.closed === undefined) ? true : options.closed;
  19560. var shape = options.shape;
  19561. var radius = options.radius || 1;
  19562. var tessellation = options.tessellation || 64;
  19563. var updatable = options.updatable;
  19564. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19565. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  19566. var pi2 = Math.PI * 2;
  19567. var paths = new Array();
  19568. var i = 0;
  19569. var p = 0;
  19570. var step = pi2 / tessellation * arc;
  19571. var rotated;
  19572. var path = new Array();
  19573. ;
  19574. for (i = 0; i <= tessellation; i++) {
  19575. var path = [];
  19576. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  19577. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  19578. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  19579. }
  19580. for (p = 0; p < shape.length; p++) {
  19581. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  19582. path.push(rotated);
  19583. }
  19584. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  19585. 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));
  19586. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  19587. }
  19588. paths.push(path);
  19589. }
  19590. // lathe ribbon
  19591. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  19592. return lathe;
  19593. };
  19594. /**
  19595. * Creates a plane mesh.
  19596. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  19597. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  19598. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  19599. * The parameter `sourcePlane` is a `Plane` instance. It builds a mesh plane from a Math plane.
  19600. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19601. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19602. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19603. */
  19604. MeshBuilder.CreatePlane = function (name, options, scene) {
  19605. var plane = new BABYLON.Mesh(name, scene);
  19606. var vertexData = BABYLON.VertexData.CreatePlane(options);
  19607. vertexData.applyToMesh(plane, options.updatable);
  19608. if (options.sourcePlane) {
  19609. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  19610. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  19611. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  19612. plane.rotate(vectorProduct, product);
  19613. }
  19614. return plane;
  19615. };
  19616. /**
  19617. * Creates a ground mesh.
  19618. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  19619. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  19620. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  19621. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19622. */
  19623. MeshBuilder.CreateGround = function (name, options, scene) {
  19624. var ground = new BABYLON.GroundMesh(name, scene);
  19625. ground._setReady(false);
  19626. ground._subdivisions = options.subdivisions || 1;
  19627. ground._width = options.width || 1;
  19628. ground._height = options.height || 1;
  19629. ground._maxX = ground._width / 2;
  19630. ground._maxZ = ground._height / 2;
  19631. ground._minX = -ground._maxX;
  19632. ground._minZ = -ground._maxZ;
  19633. var vertexData = BABYLON.VertexData.CreateGround(options);
  19634. vertexData.applyToMesh(ground, options.updatable);
  19635. ground._setReady(true);
  19636. return ground;
  19637. };
  19638. /**
  19639. * Creates a tiled ground mesh.
  19640. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  19641. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  19642. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  19643. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  19644. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  19645. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  19646. * numbers of subdivisions on the ground width and height of each tile.
  19647. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19648. */
  19649. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  19650. var tiledGround = new BABYLON.Mesh(name, scene);
  19651. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  19652. vertexData.applyToMesh(tiledGround, options.updatable);
  19653. return tiledGround;
  19654. };
  19655. /**
  19656. * Creates a ground mesh from a height map.
  19657. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  19658. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  19659. * The parameter `url` sets the URL of the height map image resource.
  19660. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  19661. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  19662. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  19663. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  19664. * 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).
  19665. * This function is passed the newly built mesh : ```function(mesh) { // do things
  19666. * return; }```
  19667. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19668. */
  19669. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  19670. var width = options.width || 10;
  19671. var height = options.height || 10;
  19672. var subdivisions = options.subdivisions || 1;
  19673. var minHeight = options.minHeight;
  19674. var maxHeight = options.maxHeight || 10;
  19675. var updatable = options.updatable;
  19676. var onReady = options.onReady;
  19677. var ground = new BABYLON.GroundMesh(name, scene);
  19678. ground._subdivisions = subdivisions;
  19679. ground._width = width;
  19680. ground._height = height;
  19681. ground._maxX = ground._width / 2;
  19682. ground._maxZ = ground._height / 2;
  19683. ground._minX = -ground._maxX;
  19684. ground._minZ = -ground._maxZ;
  19685. ground._setReady(false);
  19686. var onload = function (img) {
  19687. // Getting height map data
  19688. var canvas = document.createElement("canvas");
  19689. var context = canvas.getContext("2d");
  19690. var bufferWidth = img.width;
  19691. var bufferHeight = img.height;
  19692. canvas.width = bufferWidth;
  19693. canvas.height = bufferHeight;
  19694. context.drawImage(img, 0, 0);
  19695. // Create VertexData from map data
  19696. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  19697. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  19698. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  19699. width: width, height: height,
  19700. subdivisions: subdivisions,
  19701. minHeight: minHeight, maxHeight: maxHeight,
  19702. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  19703. });
  19704. vertexData.applyToMesh(ground, updatable);
  19705. ground._setReady(true);
  19706. //execute ready callback, if set
  19707. if (onReady) {
  19708. onReady(ground);
  19709. }
  19710. };
  19711. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  19712. return ground;
  19713. };
  19714. /**
  19715. * Creates a tube mesh.
  19716. * 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.
  19717. *
  19718. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  19719. * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
  19720. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  19721. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  19722. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  19723. * 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.
  19724. * It must return a radius value (positive float) :
  19725. * ```var radiusFunction = function(i, distance) {
  19726. * // do things
  19727. * return radius; }```
  19728. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  19729. * 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
  19730. * 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
  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.CreateTube = function (name, options, scene) {
  19736. var path = options.path;
  19737. var radius = options.radius || 1;
  19738. var tessellation = options.tessellation || 64;
  19739. var radiusFunction = options.radiusFunction;
  19740. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  19741. var updatable = options.updatable;
  19742. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19743. var instance = options.instance;
  19744. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  19745. // tube geometry
  19746. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  19747. var tangents = path3D.getTangents();
  19748. var normals = path3D.getNormals();
  19749. var distances = path3D.getDistances();
  19750. var pi2 = Math.PI * 2;
  19751. var step = pi2 / tessellation * arc;
  19752. var returnRadius = function () { return radius; };
  19753. var radiusFunctionFinal = radiusFunction || returnRadius;
  19754. var circlePath;
  19755. var rad;
  19756. var normal;
  19757. var rotated;
  19758. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  19759. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  19760. for (var i = 0; i < path.length; i++) {
  19761. rad = radiusFunctionFinal(i, distances[i]); // current radius
  19762. circlePath = Array(); // current circle array
  19763. normal = normals[i]; // current normal
  19764. for (var t = 0; t < tessellation; t++) {
  19765. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  19766. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  19767. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  19768. rotated.scaleInPlace(rad).addInPlace(path[i]);
  19769. circlePath[t] = rotated;
  19770. }
  19771. circlePaths[index] = circlePath;
  19772. index++;
  19773. }
  19774. // cap
  19775. var capPath = function (nbPoints, pathIndex) {
  19776. var pointCap = Array();
  19777. for (var i = 0; i < nbPoints; i++) {
  19778. pointCap.push(path[pathIndex]);
  19779. }
  19780. return pointCap;
  19781. };
  19782. switch (cap) {
  19783. case BABYLON.Mesh.NO_CAP:
  19784. break;
  19785. case BABYLON.Mesh.CAP_START:
  19786. circlePaths[0] = capPath(tessellation, 0);
  19787. circlePaths[1] = circlePaths[2].slice(0);
  19788. break;
  19789. case BABYLON.Mesh.CAP_END:
  19790. circlePaths[index] = circlePaths[index - 1].slice(0);
  19791. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  19792. break;
  19793. case BABYLON.Mesh.CAP_ALL:
  19794. circlePaths[0] = capPath(tessellation, 0);
  19795. circlePaths[1] = circlePaths[2].slice(0);
  19796. circlePaths[index] = circlePaths[index - 1].slice(0);
  19797. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  19798. break;
  19799. default:
  19800. break;
  19801. }
  19802. return circlePaths;
  19803. };
  19804. var path3D;
  19805. var pathArray;
  19806. if (instance) {
  19807. var arc = options.arc || instance.arc;
  19808. path3D = (instance.path3D).update(path);
  19809. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  19810. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  19811. instance.path3D = path3D;
  19812. instance.pathArray = pathArray;
  19813. instance.arc = arc;
  19814. return instance;
  19815. }
  19816. // tube creation
  19817. path3D = new BABYLON.Path3D(path);
  19818. var newPathArray = new Array();
  19819. cap = (cap < 0 || cap > 3) ? 0 : cap;
  19820. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  19821. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  19822. tube.pathArray = pathArray;
  19823. tube.path3D = path3D;
  19824. tube.tessellation = tessellation;
  19825. tube.cap = cap;
  19826. tube.arc = options.arc;
  19827. return tube;
  19828. };
  19829. /**
  19830. * Creates a polyhedron mesh.
  19831. *
  19832. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  19833. * 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
  19834. * to choose the wanted type.
  19835. * The parameter `size` (positive float, default 1) sets the polygon size.
  19836. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  19837. * 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`.
  19838. * 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
  19839. * 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)`).
  19840. * 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
  19841. * 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.
  19842. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19843. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19844. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19845. */
  19846. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  19847. var polyhedron = new BABYLON.Mesh(name, scene);
  19848. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  19849. vertexData.applyToMesh(polyhedron, options.updatable);
  19850. return polyhedron;
  19851. };
  19852. /**
  19853. * Creates a decal mesh.
  19854. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  19855. * 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.
  19856. * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  19857. * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  19858. * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
  19859. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  19860. */
  19861. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  19862. var indices = sourceMesh.getIndices();
  19863. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19864. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19865. var position = options.position || BABYLON.Vector3.Zero();
  19866. var normal = options.normal || BABYLON.Vector3.Up();
  19867. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  19868. var angle = options.angle || 0;
  19869. // Getting correct rotation
  19870. if (!normal) {
  19871. var target = new BABYLON.Vector3(0, 0, 1);
  19872. var camera = sourceMesh.getScene().activeCamera;
  19873. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  19874. normal = camera.globalPosition.subtract(cameraWorldTarget);
  19875. }
  19876. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  19877. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  19878. var pitch = Math.atan2(normal.y, len);
  19879. // Matrix
  19880. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  19881. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  19882. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  19883. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  19884. var vertexData = new BABYLON.VertexData();
  19885. vertexData.indices = [];
  19886. vertexData.positions = [];
  19887. vertexData.normals = [];
  19888. vertexData.uvs = [];
  19889. var currentVertexDataIndex = 0;
  19890. var extractDecalVector3 = function (indexId) {
  19891. var vertexId = indices[indexId];
  19892. var result = new BABYLON.PositionNormalVertex();
  19893. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  19894. // Send vector to decal local world
  19895. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  19896. // Get normal
  19897. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  19898. return result;
  19899. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  19900. var clip = function (vertices, axis) {
  19901. if (vertices.length === 0) {
  19902. return vertices;
  19903. }
  19904. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  19905. var clipVertices = function (v0, v1) {
  19906. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  19907. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  19908. };
  19909. var result = new Array();
  19910. for (var index = 0; index < vertices.length; index += 3) {
  19911. var v1Out;
  19912. var v2Out;
  19913. var v3Out;
  19914. var total = 0;
  19915. var nV1, nV2, nV3, nV4;
  19916. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  19917. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  19918. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  19919. v1Out = d1 > 0;
  19920. v2Out = d2 > 0;
  19921. v3Out = d3 > 0;
  19922. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  19923. switch (total) {
  19924. case 0:
  19925. result.push(vertices[index]);
  19926. result.push(vertices[index + 1]);
  19927. result.push(vertices[index + 2]);
  19928. break;
  19929. case 1:
  19930. if (v1Out) {
  19931. nV1 = vertices[index + 1];
  19932. nV2 = vertices[index + 2];
  19933. nV3 = clipVertices(vertices[index], nV1);
  19934. nV4 = clipVertices(vertices[index], nV2);
  19935. }
  19936. if (v2Out) {
  19937. nV1 = vertices[index];
  19938. nV2 = vertices[index + 2];
  19939. nV3 = clipVertices(vertices[index + 1], nV1);
  19940. nV4 = clipVertices(vertices[index + 1], nV2);
  19941. result.push(nV3);
  19942. result.push(nV2.clone());
  19943. result.push(nV1.clone());
  19944. result.push(nV2.clone());
  19945. result.push(nV3.clone());
  19946. result.push(nV4);
  19947. break;
  19948. }
  19949. if (v3Out) {
  19950. nV1 = vertices[index];
  19951. nV2 = vertices[index + 1];
  19952. nV3 = clipVertices(vertices[index + 2], nV1);
  19953. nV4 = clipVertices(vertices[index + 2], nV2);
  19954. }
  19955. result.push(nV1.clone());
  19956. result.push(nV2.clone());
  19957. result.push(nV3);
  19958. result.push(nV4);
  19959. result.push(nV3.clone());
  19960. result.push(nV2.clone());
  19961. break;
  19962. case 2:
  19963. if (!v1Out) {
  19964. nV1 = vertices[index].clone();
  19965. nV2 = clipVertices(nV1, vertices[index + 1]);
  19966. nV3 = clipVertices(nV1, vertices[index + 2]);
  19967. result.push(nV1);
  19968. result.push(nV2);
  19969. result.push(nV3);
  19970. }
  19971. if (!v2Out) {
  19972. nV1 = vertices[index + 1].clone();
  19973. nV2 = clipVertices(nV1, vertices[index + 2]);
  19974. nV3 = clipVertices(nV1, vertices[index]);
  19975. result.push(nV1);
  19976. result.push(nV2);
  19977. result.push(nV3);
  19978. }
  19979. if (!v3Out) {
  19980. nV1 = vertices[index + 2].clone();
  19981. nV2 = clipVertices(nV1, vertices[index]);
  19982. nV3 = clipVertices(nV1, vertices[index + 1]);
  19983. result.push(nV1);
  19984. result.push(nV2);
  19985. result.push(nV3);
  19986. }
  19987. break;
  19988. case 3:
  19989. break;
  19990. }
  19991. }
  19992. return result;
  19993. };
  19994. for (var index = 0; index < indices.length; index += 3) {
  19995. var faceVertices = new Array();
  19996. faceVertices.push(extractDecalVector3(index));
  19997. faceVertices.push(extractDecalVector3(index + 1));
  19998. faceVertices.push(extractDecalVector3(index + 2));
  19999. // Clip
  20000. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  20001. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  20002. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  20003. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  20004. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  20005. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  20006. if (faceVertices.length === 0) {
  20007. continue;
  20008. }
  20009. // Add UVs and get back to world
  20010. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  20011. var vertex = faceVertices[vIndex];
  20012. //TODO check for Int32Array
  20013. vertexData.indices.push(currentVertexDataIndex);
  20014. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  20015. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  20016. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  20017. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  20018. currentVertexDataIndex++;
  20019. }
  20020. }
  20021. // Return mesh
  20022. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  20023. vertexData.applyToMesh(decal);
  20024. decal.position = position.clone();
  20025. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  20026. return decal;
  20027. };
  20028. // Privates
  20029. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  20030. // extrusion geometry
  20031. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  20032. var tangents = path3D.getTangents();
  20033. var normals = path3D.getNormals();
  20034. var binormals = path3D.getBinormals();
  20035. var distances = path3D.getDistances();
  20036. var angle = 0;
  20037. var returnScale = function () { return scale; };
  20038. var returnRotation = function () { return rotation; };
  20039. var rotate = custom ? rotateFunction : returnRotation;
  20040. var scl = custom ? scaleFunction : returnScale;
  20041. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  20042. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  20043. for (var i = 0; i < curve.length; i++) {
  20044. var shapePath = new Array();
  20045. var angleStep = rotate(i, distances[i]);
  20046. var scaleRatio = scl(i, distances[i]);
  20047. for (var p = 0; p < shape.length; p++) {
  20048. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  20049. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  20050. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  20051. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  20052. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  20053. shapePath[p] = rotated;
  20054. }
  20055. shapePaths[index] = shapePath;
  20056. angle += angleStep;
  20057. index++;
  20058. }
  20059. // cap
  20060. var capPath = function (shapePath) {
  20061. var pointCap = Array();
  20062. var barycenter = BABYLON.Vector3.Zero();
  20063. var i;
  20064. for (i = 0; i < shapePath.length; i++) {
  20065. barycenter.addInPlace(shapePath[i]);
  20066. }
  20067. barycenter.scaleInPlace(1 / shapePath.length);
  20068. for (i = 0; i < shapePath.length; i++) {
  20069. pointCap.push(barycenter);
  20070. }
  20071. return pointCap;
  20072. };
  20073. switch (cap) {
  20074. case BABYLON.Mesh.NO_CAP:
  20075. break;
  20076. case BABYLON.Mesh.CAP_START:
  20077. shapePaths[0] = capPath(shapePaths[2]);
  20078. shapePaths[1] = shapePaths[2].slice(0);
  20079. break;
  20080. case BABYLON.Mesh.CAP_END:
  20081. shapePaths[index] = shapePaths[index - 1];
  20082. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  20083. break;
  20084. case BABYLON.Mesh.CAP_ALL:
  20085. shapePaths[0] = capPath(shapePaths[2]);
  20086. shapePaths[1] = shapePaths[2].slice(0);
  20087. shapePaths[index] = shapePaths[index - 1];
  20088. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  20089. break;
  20090. default:
  20091. break;
  20092. }
  20093. return shapePaths;
  20094. };
  20095. var path3D;
  20096. var pathArray;
  20097. if (instance) {
  20098. path3D = (instance.path3D).update(curve);
  20099. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  20100. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  20101. return instance;
  20102. }
  20103. // extruded shape creation
  20104. path3D = new BABYLON.Path3D(curve);
  20105. var newShapePaths = new Array();
  20106. cap = (cap < 0 || cap > 3) ? 0 : cap;
  20107. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  20108. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  20109. extrudedGeneric.pathArray = pathArray;
  20110. extrudedGeneric.path3D = path3D;
  20111. extrudedGeneric.cap = cap;
  20112. return extrudedGeneric;
  20113. };
  20114. return MeshBuilder;
  20115. })();
  20116. BABYLON.MeshBuilder = MeshBuilder;
  20117. })(BABYLON || (BABYLON = {}));
  20118. var BABYLON;
  20119. (function (BABYLON) {
  20120. var BaseTexture = (function () {
  20121. function BaseTexture(scene) {
  20122. this.hasAlpha = false;
  20123. this.getAlphaFromRGB = false;
  20124. this.level = 1;
  20125. this.coordinatesIndex = 0;
  20126. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20127. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20128. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20129. this.anisotropicFilteringLevel = 4;
  20130. this.isCube = false;
  20131. this.isRenderTarget = false;
  20132. this.animations = new Array();
  20133. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20134. this._scene = scene;
  20135. this._scene.textures.push(this);
  20136. }
  20137. BaseTexture.prototype.getScene = function () {
  20138. return this._scene;
  20139. };
  20140. BaseTexture.prototype.getTextureMatrix = function () {
  20141. return null;
  20142. };
  20143. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20144. return null;
  20145. };
  20146. BaseTexture.prototype.getInternalTexture = function () {
  20147. return this._texture;
  20148. };
  20149. BaseTexture.prototype.isReady = function () {
  20150. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20151. return true;
  20152. }
  20153. if (this._texture) {
  20154. return this._texture.isReady;
  20155. }
  20156. return false;
  20157. };
  20158. BaseTexture.prototype.getSize = function () {
  20159. if (this._texture._width) {
  20160. return { width: this._texture._width, height: this._texture._height };
  20161. }
  20162. if (this._texture._size) {
  20163. return { width: this._texture._size, height: this._texture._size };
  20164. }
  20165. return { width: 0, height: 0 };
  20166. };
  20167. BaseTexture.prototype.getBaseSize = function () {
  20168. if (!this.isReady() || !this._texture)
  20169. return { width: 0, height: 0 };
  20170. if (this._texture._size) {
  20171. return { width: this._texture._size, height: this._texture._size };
  20172. }
  20173. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  20174. };
  20175. BaseTexture.prototype.scale = function (ratio) {
  20176. };
  20177. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20178. get: function () {
  20179. return false;
  20180. },
  20181. enumerable: true,
  20182. configurable: true
  20183. });
  20184. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  20185. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20186. for (var index = 0; index < texturesCache.length; index++) {
  20187. var texturesCacheEntry = texturesCache[index];
  20188. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  20189. texturesCache.splice(index, 1);
  20190. return;
  20191. }
  20192. }
  20193. };
  20194. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20195. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20196. for (var index = 0; index < texturesCache.length; index++) {
  20197. var texturesCacheEntry = texturesCache[index];
  20198. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  20199. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20200. texturesCacheEntry.references++;
  20201. return texturesCacheEntry;
  20202. }
  20203. }
  20204. }
  20205. return null;
  20206. };
  20207. BaseTexture.prototype.delayLoad = function () {
  20208. };
  20209. BaseTexture.prototype.clone = function () {
  20210. return null;
  20211. };
  20212. BaseTexture.prototype.releaseInternalTexture = function () {
  20213. if (this._texture) {
  20214. this._scene.getEngine().releaseInternalTexture(this._texture);
  20215. delete this._texture;
  20216. }
  20217. };
  20218. BaseTexture.prototype.dispose = function () {
  20219. // Animations
  20220. this.getScene().stopAnimation(this);
  20221. // Remove from scene
  20222. var index = this._scene.textures.indexOf(this);
  20223. if (index >= 0) {
  20224. this._scene.textures.splice(index, 1);
  20225. }
  20226. if (this._texture === undefined) {
  20227. return;
  20228. }
  20229. // Release
  20230. this.releaseInternalTexture();
  20231. // Callback
  20232. if (this.onDispose) {
  20233. this.onDispose();
  20234. }
  20235. };
  20236. BaseTexture.prototype.serialize = function () {
  20237. if (!this.name) {
  20238. return null;
  20239. }
  20240. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20241. // Animations
  20242. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20243. return serializationObject;
  20244. };
  20245. __decorate([
  20246. BABYLON.serialize()
  20247. ], BaseTexture.prototype, "name", void 0);
  20248. __decorate([
  20249. BABYLON.serialize()
  20250. ], BaseTexture.prototype, "hasAlpha", void 0);
  20251. __decorate([
  20252. BABYLON.serialize()
  20253. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20254. __decorate([
  20255. BABYLON.serialize()
  20256. ], BaseTexture.prototype, "level", void 0);
  20257. __decorate([
  20258. BABYLON.serialize()
  20259. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20260. __decorate([
  20261. BABYLON.serialize()
  20262. ], BaseTexture.prototype, "coordinatesMode", void 0);
  20263. __decorate([
  20264. BABYLON.serialize()
  20265. ], BaseTexture.prototype, "wrapU", void 0);
  20266. __decorate([
  20267. BABYLON.serialize()
  20268. ], BaseTexture.prototype, "wrapV", void 0);
  20269. __decorate([
  20270. BABYLON.serialize()
  20271. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20272. __decorate([
  20273. BABYLON.serialize()
  20274. ], BaseTexture.prototype, "isCube", void 0);
  20275. __decorate([
  20276. BABYLON.serialize()
  20277. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20278. return BaseTexture;
  20279. })();
  20280. BABYLON.BaseTexture = BaseTexture;
  20281. })(BABYLON || (BABYLON = {}));
  20282. var BABYLON;
  20283. (function (BABYLON) {
  20284. var Texture = (function (_super) {
  20285. __extends(Texture, _super);
  20286. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  20287. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20288. if (onLoad === void 0) { onLoad = null; }
  20289. if (onError === void 0) { onError = null; }
  20290. if (buffer === void 0) { buffer = null; }
  20291. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20292. _super.call(this, scene);
  20293. this.uOffset = 0;
  20294. this.vOffset = 0;
  20295. this.uScale = 1.0;
  20296. this.vScale = 1.0;
  20297. this.uAng = 0;
  20298. this.vAng = 0;
  20299. this.wAng = 0;
  20300. this.name = url;
  20301. this.url = url;
  20302. this._noMipmap = noMipmap;
  20303. this._invertY = invertY;
  20304. this._samplingMode = samplingMode;
  20305. this._buffer = buffer;
  20306. this._deleteBuffer = deleteBuffer;
  20307. if (!url) {
  20308. return;
  20309. }
  20310. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  20311. if (!this._texture) {
  20312. if (!scene.useDelayedTextureLoading) {
  20313. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  20314. if (deleteBuffer) {
  20315. delete this._buffer;
  20316. }
  20317. }
  20318. else {
  20319. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20320. this._delayedOnLoad = onLoad;
  20321. this._delayedOnError = onError;
  20322. }
  20323. }
  20324. else {
  20325. BABYLON.Tools.SetImmediate(function () {
  20326. if (onLoad) {
  20327. onLoad();
  20328. }
  20329. });
  20330. }
  20331. }
  20332. Texture.prototype.delayLoad = function () {
  20333. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20334. return;
  20335. }
  20336. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20337. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  20338. if (!this._texture) {
  20339. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  20340. if (this._deleteBuffer) {
  20341. delete this._buffer;
  20342. }
  20343. }
  20344. };
  20345. Texture.prototype.updateSamplingMode = function (samplingMode) {
  20346. if (!this._texture) {
  20347. return;
  20348. }
  20349. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  20350. };
  20351. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  20352. x *= this.uScale;
  20353. y *= this.vScale;
  20354. x -= 0.5 * this.uScale;
  20355. y -= 0.5 * this.vScale;
  20356. z -= 0.5;
  20357. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  20358. t.x += 0.5 * this.uScale + this.uOffset;
  20359. t.y += 0.5 * this.vScale + this.vOffset;
  20360. t.z += 0.5;
  20361. };
  20362. Texture.prototype.getTextureMatrix = function () {
  20363. if (this.uOffset === this._cachedUOffset &&
  20364. this.vOffset === this._cachedVOffset &&
  20365. this.uScale === this._cachedUScale &&
  20366. this.vScale === this._cachedVScale &&
  20367. this.uAng === this._cachedUAng &&
  20368. this.vAng === this._cachedVAng &&
  20369. this.wAng === this._cachedWAng) {
  20370. return this._cachedTextureMatrix;
  20371. }
  20372. this._cachedUOffset = this.uOffset;
  20373. this._cachedVOffset = this.vOffset;
  20374. this._cachedUScale = this.uScale;
  20375. this._cachedVScale = this.vScale;
  20376. this._cachedUAng = this.uAng;
  20377. this._cachedVAng = this.vAng;
  20378. this._cachedWAng = this.wAng;
  20379. if (!this._cachedTextureMatrix) {
  20380. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20381. this._rowGenerationMatrix = new BABYLON.Matrix();
  20382. this._t0 = BABYLON.Vector3.Zero();
  20383. this._t1 = BABYLON.Vector3.Zero();
  20384. this._t2 = BABYLON.Vector3.Zero();
  20385. }
  20386. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  20387. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  20388. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  20389. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  20390. this._t1.subtractInPlace(this._t0);
  20391. this._t2.subtractInPlace(this._t0);
  20392. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20393. this._cachedTextureMatrix.m[0] = this._t1.x;
  20394. this._cachedTextureMatrix.m[1] = this._t1.y;
  20395. this._cachedTextureMatrix.m[2] = this._t1.z;
  20396. this._cachedTextureMatrix.m[4] = this._t2.x;
  20397. this._cachedTextureMatrix.m[5] = this._t2.y;
  20398. this._cachedTextureMatrix.m[6] = this._t2.z;
  20399. this._cachedTextureMatrix.m[8] = this._t0.x;
  20400. this._cachedTextureMatrix.m[9] = this._t0.y;
  20401. this._cachedTextureMatrix.m[10] = this._t0.z;
  20402. return this._cachedTextureMatrix;
  20403. };
  20404. Texture.prototype.getReflectionTextureMatrix = function () {
  20405. if (this.uOffset === this._cachedUOffset &&
  20406. this.vOffset === this._cachedVOffset &&
  20407. this.uScale === this._cachedUScale &&
  20408. this.vScale === this._cachedVScale &&
  20409. this.coordinatesMode === this._cachedCoordinatesMode) {
  20410. return this._cachedTextureMatrix;
  20411. }
  20412. if (!this._cachedTextureMatrix) {
  20413. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20414. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  20415. }
  20416. this._cachedCoordinatesMode = this.coordinatesMode;
  20417. switch (this.coordinatesMode) {
  20418. case Texture.PLANAR_MODE:
  20419. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20420. this._cachedTextureMatrix[0] = this.uScale;
  20421. this._cachedTextureMatrix[5] = this.vScale;
  20422. this._cachedTextureMatrix[12] = this.uOffset;
  20423. this._cachedTextureMatrix[13] = this.vOffset;
  20424. break;
  20425. case Texture.PROJECTION_MODE:
  20426. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  20427. this._projectionModeMatrix.m[0] = 0.5;
  20428. this._projectionModeMatrix.m[5] = -0.5;
  20429. this._projectionModeMatrix.m[10] = 0.0;
  20430. this._projectionModeMatrix.m[12] = 0.5;
  20431. this._projectionModeMatrix.m[13] = 0.5;
  20432. this._projectionModeMatrix.m[14] = 1.0;
  20433. this._projectionModeMatrix.m[15] = 1.0;
  20434. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  20435. break;
  20436. default:
  20437. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20438. break;
  20439. }
  20440. return this._cachedTextureMatrix;
  20441. };
  20442. Texture.prototype.clone = function () {
  20443. var _this = this;
  20444. return BABYLON.SerializationHelper.Clone(function () {
  20445. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  20446. }, this);
  20447. };
  20448. // Statics
  20449. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  20450. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20451. if (onLoad === void 0) { onLoad = null; }
  20452. if (onError === void 0) { onError = null; }
  20453. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  20454. };
  20455. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  20456. if (parsedTexture.isCube) {
  20457. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  20458. }
  20459. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  20460. return null;
  20461. }
  20462. var texture = BABYLON.SerializationHelper.Parse(function () {
  20463. if (parsedTexture.mirrorPlane) {
  20464. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20465. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  20466. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  20467. return mirrorTexture;
  20468. }
  20469. else if (parsedTexture.isRenderTarget) {
  20470. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20471. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  20472. return renderTargetTexture;
  20473. }
  20474. else {
  20475. var texture;
  20476. if (parsedTexture.base64String) {
  20477. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  20478. }
  20479. else {
  20480. texture = new Texture(rootUrl + parsedTexture.name, scene);
  20481. }
  20482. return texture;
  20483. }
  20484. }, parsedTexture, scene);
  20485. // Animations
  20486. if (parsedTexture.animations) {
  20487. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20488. var parsedAnimation = parsedTexture.animations[animationIndex];
  20489. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20490. }
  20491. }
  20492. return texture;
  20493. };
  20494. // Constants
  20495. Texture.NEAREST_SAMPLINGMODE = 1;
  20496. Texture.BILINEAR_SAMPLINGMODE = 2;
  20497. Texture.TRILINEAR_SAMPLINGMODE = 3;
  20498. Texture.EXPLICIT_MODE = 0;
  20499. Texture.SPHERICAL_MODE = 1;
  20500. Texture.PLANAR_MODE = 2;
  20501. Texture.CUBIC_MODE = 3;
  20502. Texture.PROJECTION_MODE = 4;
  20503. Texture.SKYBOX_MODE = 5;
  20504. Texture.INVCUBIC_MODE = 6;
  20505. Texture.EQUIRECTANGULAR_MODE = 7;
  20506. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  20507. Texture.CLAMP_ADDRESSMODE = 0;
  20508. Texture.WRAP_ADDRESSMODE = 1;
  20509. Texture.MIRROR_ADDRESSMODE = 2;
  20510. __decorate([
  20511. BABYLON.serialize()
  20512. ], Texture.prototype, "url", void 0);
  20513. __decorate([
  20514. BABYLON.serialize()
  20515. ], Texture.prototype, "uOffset", void 0);
  20516. __decorate([
  20517. BABYLON.serialize()
  20518. ], Texture.prototype, "vOffset", void 0);
  20519. __decorate([
  20520. BABYLON.serialize()
  20521. ], Texture.prototype, "uScale", void 0);
  20522. __decorate([
  20523. BABYLON.serialize()
  20524. ], Texture.prototype, "vScale", void 0);
  20525. __decorate([
  20526. BABYLON.serialize()
  20527. ], Texture.prototype, "uAng", void 0);
  20528. __decorate([
  20529. BABYLON.serialize()
  20530. ], Texture.prototype, "vAng", void 0);
  20531. __decorate([
  20532. BABYLON.serialize()
  20533. ], Texture.prototype, "wAng", void 0);
  20534. return Texture;
  20535. })(BABYLON.BaseTexture);
  20536. BABYLON.Texture = Texture;
  20537. })(BABYLON || (BABYLON = {}));
  20538. var BABYLON;
  20539. (function (BABYLON) {
  20540. var CubeTexture = (function (_super) {
  20541. __extends(CubeTexture, _super);
  20542. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  20543. _super.call(this, scene);
  20544. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  20545. this.name = rootUrl;
  20546. this.url = rootUrl;
  20547. this._noMipmap = noMipmap;
  20548. this.hasAlpha = false;
  20549. if (!rootUrl && !files) {
  20550. return;
  20551. }
  20552. this._texture = this._getFromCache(rootUrl, noMipmap);
  20553. if (!files) {
  20554. if (!extensions) {
  20555. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  20556. }
  20557. files = [];
  20558. for (var index = 0; index < extensions.length; index++) {
  20559. files.push(rootUrl + extensions[index]);
  20560. }
  20561. this._extensions = extensions;
  20562. }
  20563. this._files = files;
  20564. if (!this._texture) {
  20565. if (!scene.useDelayedTextureLoading) {
  20566. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  20567. }
  20568. else {
  20569. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20570. }
  20571. }
  20572. this.isCube = true;
  20573. this._textureMatrix = BABYLON.Matrix.Identity();
  20574. }
  20575. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  20576. return new CubeTexture("", scene, null, noMipmap, files);
  20577. };
  20578. // Methods
  20579. CubeTexture.prototype.delayLoad = function () {
  20580. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20581. return;
  20582. }
  20583. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20584. this._texture = this._getFromCache(this.url, this._noMipmap);
  20585. if (!this._texture) {
  20586. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  20587. }
  20588. };
  20589. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  20590. return this._textureMatrix;
  20591. };
  20592. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  20593. var texture = BABYLON.SerializationHelper.Parse(function () {
  20594. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  20595. }, parsedTexture, scene);
  20596. // Animations
  20597. if (parsedTexture.animations) {
  20598. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20599. var parsedAnimation = parsedTexture.animations[animationIndex];
  20600. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20601. }
  20602. }
  20603. return texture;
  20604. };
  20605. CubeTexture.prototype.clone = function () {
  20606. var _this = this;
  20607. return BABYLON.SerializationHelper.Clone(function () {
  20608. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  20609. }, this);
  20610. };
  20611. return CubeTexture;
  20612. })(BABYLON.BaseTexture);
  20613. BABYLON.CubeTexture = CubeTexture;
  20614. })(BABYLON || (BABYLON = {}));
  20615. var BABYLON;
  20616. (function (BABYLON) {
  20617. var RenderTargetTexture = (function (_super) {
  20618. __extends(RenderTargetTexture, _super);
  20619. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  20620. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  20621. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  20622. if (isCube === void 0) { isCube = false; }
  20623. _super.call(this, null, scene, !generateMipMaps);
  20624. this.isCube = isCube;
  20625. this.renderList = new Array();
  20626. this.renderParticles = true;
  20627. this.renderSprites = false;
  20628. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  20629. this._currentRefreshId = -1;
  20630. this._refreshRate = 1;
  20631. this.name = name;
  20632. this.isRenderTarget = true;
  20633. this._size = size;
  20634. this._generateMipMaps = generateMipMaps;
  20635. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  20636. if (isCube) {
  20637. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  20638. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  20639. this._textureMatrix = BABYLON.Matrix.Identity();
  20640. }
  20641. else {
  20642. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  20643. }
  20644. // Rendering groups
  20645. this._renderingManager = new BABYLON.RenderingManager(scene);
  20646. }
  20647. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  20648. get: function () {
  20649. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  20650. },
  20651. enumerable: true,
  20652. configurable: true
  20653. });
  20654. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  20655. get: function () {
  20656. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  20657. },
  20658. enumerable: true,
  20659. configurable: true
  20660. });
  20661. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  20662. get: function () {
  20663. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  20664. },
  20665. enumerable: true,
  20666. configurable: true
  20667. });
  20668. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  20669. this._currentRefreshId = -1;
  20670. };
  20671. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  20672. get: function () {
  20673. return this._refreshRate;
  20674. },
  20675. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  20676. set: function (value) {
  20677. this._refreshRate = value;
  20678. this.resetRefreshCounter();
  20679. },
  20680. enumerable: true,
  20681. configurable: true
  20682. });
  20683. RenderTargetTexture.prototype._shouldRender = function () {
  20684. if (this._currentRefreshId === -1) {
  20685. this._currentRefreshId = 1;
  20686. return true;
  20687. }
  20688. if (this.refreshRate === this._currentRefreshId) {
  20689. this._currentRefreshId = 1;
  20690. return true;
  20691. }
  20692. this._currentRefreshId++;
  20693. return false;
  20694. };
  20695. RenderTargetTexture.prototype.isReady = function () {
  20696. if (!this.getScene().renderTargetsEnabled) {
  20697. return false;
  20698. }
  20699. return _super.prototype.isReady.call(this);
  20700. };
  20701. RenderTargetTexture.prototype.getRenderSize = function () {
  20702. return this._size;
  20703. };
  20704. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  20705. get: function () {
  20706. return true;
  20707. },
  20708. enumerable: true,
  20709. configurable: true
  20710. });
  20711. RenderTargetTexture.prototype.scale = function (ratio) {
  20712. var newSize = this._size * ratio;
  20713. this.resize(newSize, this._generateMipMaps);
  20714. };
  20715. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  20716. if (this.isCube) {
  20717. return this._textureMatrix;
  20718. }
  20719. return _super.prototype.getReflectionTextureMatrix.call(this);
  20720. };
  20721. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  20722. this.releaseInternalTexture();
  20723. if (this.isCube) {
  20724. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  20725. }
  20726. else {
  20727. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  20728. }
  20729. };
  20730. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  20731. var scene = this.getScene();
  20732. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  20733. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  20734. }
  20735. if (this._waitingRenderList) {
  20736. this.renderList = [];
  20737. for (var index = 0; index < this._waitingRenderList.length; index++) {
  20738. var id = this._waitingRenderList[index];
  20739. this.renderList.push(scene.getMeshByID(id));
  20740. }
  20741. delete this._waitingRenderList;
  20742. }
  20743. if (this.renderList && this.renderList.length === 0) {
  20744. return;
  20745. }
  20746. // Prepare renderingManager
  20747. this._renderingManager.reset();
  20748. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  20749. var sceneRenderId = scene.getRenderId();
  20750. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  20751. var mesh = currentRenderList[meshIndex];
  20752. if (mesh) {
  20753. if (!mesh.isReady()) {
  20754. // Reset _currentRefreshId
  20755. this.resetRefreshCounter();
  20756. continue;
  20757. }
  20758. mesh._preActivateForIntermediateRendering(sceneRenderId);
  20759. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  20760. mesh._activate(sceneRenderId);
  20761. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  20762. var subMesh = mesh.subMeshes[subIndex];
  20763. scene._activeIndices += subMesh.indexCount;
  20764. this._renderingManager.dispatch(subMesh);
  20765. }
  20766. }
  20767. }
  20768. }
  20769. if (this.isCube) {
  20770. for (var face = 0; face < 6; face++) {
  20771. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  20772. scene.incrementRenderId();
  20773. scene.resetCachedMaterial();
  20774. }
  20775. }
  20776. else {
  20777. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  20778. }
  20779. if (this.onAfterUnbind) {
  20780. this.onAfterUnbind();
  20781. }
  20782. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  20783. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  20784. }
  20785. scene.resetCachedMaterial();
  20786. };
  20787. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  20788. var scene = this.getScene();
  20789. var engine = scene.getEngine();
  20790. // Bind
  20791. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  20792. if (this.isCube) {
  20793. engine.bindFramebuffer(this._texture, faceIndex);
  20794. }
  20795. else {
  20796. engine.bindFramebuffer(this._texture);
  20797. }
  20798. }
  20799. if (this.onBeforeRender) {
  20800. this.onBeforeRender(faceIndex);
  20801. }
  20802. // Clear
  20803. if (this.onClear) {
  20804. this.onClear(engine);
  20805. }
  20806. else {
  20807. engine.clear(scene.clearColor, true, true);
  20808. }
  20809. if (!this._doNotChangeAspectRatio) {
  20810. scene.updateTransformMatrix(true);
  20811. }
  20812. // Render
  20813. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  20814. if (useCameraPostProcess) {
  20815. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  20816. }
  20817. if (!this._doNotChangeAspectRatio) {
  20818. scene.updateTransformMatrix(true);
  20819. }
  20820. if (this.onAfterRender) {
  20821. this.onAfterRender(faceIndex);
  20822. }
  20823. // Dump ?
  20824. if (dumpForDebug) {
  20825. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  20826. }
  20827. // Unbind
  20828. if (!this.isCube || faceIndex === 5) {
  20829. if (this.isCube) {
  20830. if (faceIndex === 5) {
  20831. engine.generateMipMapsForCubemap(this._texture);
  20832. }
  20833. }
  20834. engine.unBindFramebuffer(this._texture, this.isCube);
  20835. }
  20836. };
  20837. RenderTargetTexture.prototype.clone = function () {
  20838. var textureSize = this.getSize();
  20839. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  20840. // Base texture
  20841. newTexture.hasAlpha = this.hasAlpha;
  20842. newTexture.level = this.level;
  20843. // RenderTarget Texture
  20844. newTexture.coordinatesMode = this.coordinatesMode;
  20845. newTexture.renderList = this.renderList.slice(0);
  20846. return newTexture;
  20847. };
  20848. RenderTargetTexture.prototype.serialize = function () {
  20849. if (!this.name) {
  20850. return null;
  20851. }
  20852. var serializationObject = _super.prototype.serialize.call(this);
  20853. serializationObject.renderTargetSize = this.getRenderSize();
  20854. serializationObject.renderList = [];
  20855. for (var index = 0; index < this.renderList.length; index++) {
  20856. serializationObject.renderList.push(this.renderList[index].id);
  20857. }
  20858. return serializationObject;
  20859. };
  20860. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  20861. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  20862. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  20863. return RenderTargetTexture;
  20864. })(BABYLON.Texture);
  20865. BABYLON.RenderTargetTexture = RenderTargetTexture;
  20866. })(BABYLON || (BABYLON = {}));
  20867. var BABYLON;
  20868. (function (BABYLON) {
  20869. var ProceduralTexture = (function (_super) {
  20870. __extends(ProceduralTexture, _super);
  20871. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  20872. if (generateMipMaps === void 0) { generateMipMaps = true; }
  20873. if (isCube === void 0) { isCube = false; }
  20874. _super.call(this, null, scene, !generateMipMaps);
  20875. this.isCube = isCube;
  20876. this.isEnabled = true;
  20877. this._currentRefreshId = -1;
  20878. this._refreshRate = 1;
  20879. this._vertexDeclaration = [2];
  20880. this._vertexStrideSize = 2 * 4;
  20881. this._uniforms = new Array();
  20882. this._samplers = new Array();
  20883. this._textures = new Array();
  20884. this._floats = new Array();
  20885. this._floatsArrays = {};
  20886. this._colors3 = new Array();
  20887. this._colors4 = new Array();
  20888. this._vectors2 = new Array();
  20889. this._vectors3 = new Array();
  20890. this._matrices = new Array();
  20891. this._fallbackTextureUsed = false;
  20892. scene._proceduralTextures.push(this);
  20893. this.name = name;
  20894. this.isRenderTarget = true;
  20895. this._size = size;
  20896. this._generateMipMaps = generateMipMaps;
  20897. this.setFragment(fragment);
  20898. this._fallbackTexture = fallbackTexture;
  20899. if (isCube) {
  20900. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  20901. this.setFloat("face", 0);
  20902. }
  20903. else {
  20904. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  20905. }
  20906. // VBO
  20907. var vertices = [];
  20908. vertices.push(1, 1);
  20909. vertices.push(-1, 1);
  20910. vertices.push(-1, -1);
  20911. vertices.push(1, -1);
  20912. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20913. // Indices
  20914. var indices = [];
  20915. indices.push(0);
  20916. indices.push(1);
  20917. indices.push(2);
  20918. indices.push(0);
  20919. indices.push(2);
  20920. indices.push(3);
  20921. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20922. }
  20923. ProceduralTexture.prototype.reset = function () {
  20924. if (this._effect === undefined) {
  20925. return;
  20926. }
  20927. var engine = this.getScene().getEngine();
  20928. engine._releaseEffect(this._effect);
  20929. };
  20930. ProceduralTexture.prototype.isReady = function () {
  20931. var _this = this;
  20932. var engine = this.getScene().getEngine();
  20933. var shaders;
  20934. if (!this._fragment) {
  20935. return false;
  20936. }
  20937. if (this._fallbackTextureUsed) {
  20938. return true;
  20939. }
  20940. if (this._fragment.fragmentElement !== undefined) {
  20941. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  20942. }
  20943. else {
  20944. shaders = { vertex: "procedural", fragment: this._fragment };
  20945. }
  20946. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  20947. _this.releaseInternalTexture();
  20948. if (_this._fallbackTexture) {
  20949. _this._texture = _this._fallbackTexture._texture;
  20950. _this._texture.references++;
  20951. }
  20952. _this._fallbackTextureUsed = true;
  20953. });
  20954. return this._effect.isReady();
  20955. };
  20956. ProceduralTexture.prototype.resetRefreshCounter = function () {
  20957. this._currentRefreshId = -1;
  20958. };
  20959. ProceduralTexture.prototype.setFragment = function (fragment) {
  20960. this._fragment = fragment;
  20961. };
  20962. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  20963. get: function () {
  20964. return this._refreshRate;
  20965. },
  20966. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  20967. set: function (value) {
  20968. this._refreshRate = value;
  20969. this.resetRefreshCounter();
  20970. },
  20971. enumerable: true,
  20972. configurable: true
  20973. });
  20974. ProceduralTexture.prototype._shouldRender = function () {
  20975. if (!this.isEnabled || !this.isReady() || !this._texture) {
  20976. return false;
  20977. }
  20978. if (this._fallbackTextureUsed) {
  20979. return false;
  20980. }
  20981. if (this._currentRefreshId === -1) {
  20982. this._currentRefreshId = 1;
  20983. return true;
  20984. }
  20985. if (this.refreshRate === this._currentRefreshId) {
  20986. this._currentRefreshId = 1;
  20987. return true;
  20988. }
  20989. this._currentRefreshId++;
  20990. return false;
  20991. };
  20992. ProceduralTexture.prototype.getRenderSize = function () {
  20993. return this._size;
  20994. };
  20995. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  20996. if (this._fallbackTextureUsed) {
  20997. return;
  20998. }
  20999. this.releaseInternalTexture();
  21000. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  21001. };
  21002. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  21003. if (this._uniforms.indexOf(uniformName) === -1) {
  21004. this._uniforms.push(uniformName);
  21005. }
  21006. };
  21007. ProceduralTexture.prototype.setTexture = function (name, texture) {
  21008. if (this._samplers.indexOf(name) === -1) {
  21009. this._samplers.push(name);
  21010. }
  21011. this._textures[name] = texture;
  21012. return this;
  21013. };
  21014. ProceduralTexture.prototype.setFloat = function (name, value) {
  21015. this._checkUniform(name);
  21016. this._floats[name] = value;
  21017. return this;
  21018. };
  21019. ProceduralTexture.prototype.setFloats = function (name, value) {
  21020. this._checkUniform(name);
  21021. this._floatsArrays[name] = value;
  21022. return this;
  21023. };
  21024. ProceduralTexture.prototype.setColor3 = function (name, value) {
  21025. this._checkUniform(name);
  21026. this._colors3[name] = value;
  21027. return this;
  21028. };
  21029. ProceduralTexture.prototype.setColor4 = function (name, value) {
  21030. this._checkUniform(name);
  21031. this._colors4[name] = value;
  21032. return this;
  21033. };
  21034. ProceduralTexture.prototype.setVector2 = function (name, value) {
  21035. this._checkUniform(name);
  21036. this._vectors2[name] = value;
  21037. return this;
  21038. };
  21039. ProceduralTexture.prototype.setVector3 = function (name, value) {
  21040. this._checkUniform(name);
  21041. this._vectors3[name] = value;
  21042. return this;
  21043. };
  21044. ProceduralTexture.prototype.setMatrix = function (name, value) {
  21045. this._checkUniform(name);
  21046. this._matrices[name] = value;
  21047. return this;
  21048. };
  21049. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  21050. var scene = this.getScene();
  21051. var engine = scene.getEngine();
  21052. // Render
  21053. engine.enableEffect(this._effect);
  21054. engine.setState(false);
  21055. // Texture
  21056. for (var name in this._textures) {
  21057. this._effect.setTexture(name, this._textures[name]);
  21058. }
  21059. // Float
  21060. for (name in this._floats) {
  21061. this._effect.setFloat(name, this._floats[name]);
  21062. }
  21063. // Floats
  21064. for (name in this._floatsArrays) {
  21065. this._effect.setArray(name, this._floatsArrays[name]);
  21066. }
  21067. // Color3
  21068. for (name in this._colors3) {
  21069. this._effect.setColor3(name, this._colors3[name]);
  21070. }
  21071. // Color4
  21072. for (name in this._colors4) {
  21073. var color = this._colors4[name];
  21074. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  21075. }
  21076. // Vector2
  21077. for (name in this._vectors2) {
  21078. this._effect.setVector2(name, this._vectors2[name]);
  21079. }
  21080. // Vector3
  21081. for (name in this._vectors3) {
  21082. this._effect.setVector3(name, this._vectors3[name]);
  21083. }
  21084. // Matrix
  21085. for (name in this._matrices) {
  21086. this._effect.setMatrix(name, this._matrices[name]);
  21087. }
  21088. // VBOs
  21089. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21090. if (this.isCube) {
  21091. for (var face = 0; face < 6; face++) {
  21092. engine.bindFramebuffer(this._texture, face);
  21093. this._effect.setFloat("face", face);
  21094. // Clear
  21095. engine.clear(scene.clearColor, true, true);
  21096. // Draw order
  21097. engine.draw(true, 0, 6);
  21098. // Mipmaps
  21099. if (face === 5) {
  21100. engine.generateMipMapsForCubemap(this._texture);
  21101. }
  21102. }
  21103. }
  21104. else {
  21105. engine.bindFramebuffer(this._texture);
  21106. // Clear
  21107. engine.clear(scene.clearColor, true, true);
  21108. // Draw order
  21109. engine.draw(true, 0, 6);
  21110. }
  21111. // Unbind
  21112. engine.unBindFramebuffer(this._texture, this.isCube);
  21113. if (this.onGenerated) {
  21114. this.onGenerated();
  21115. }
  21116. };
  21117. ProceduralTexture.prototype.clone = function () {
  21118. var textureSize = this.getSize();
  21119. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  21120. // Base texture
  21121. newTexture.hasAlpha = this.hasAlpha;
  21122. newTexture.level = this.level;
  21123. // RenderTarget Texture
  21124. newTexture.coordinatesMode = this.coordinatesMode;
  21125. return newTexture;
  21126. };
  21127. ProceduralTexture.prototype.dispose = function () {
  21128. var index = this.getScene()._proceduralTextures.indexOf(this);
  21129. if (index >= 0) {
  21130. this.getScene()._proceduralTextures.splice(index, 1);
  21131. }
  21132. _super.prototype.dispose.call(this);
  21133. };
  21134. return ProceduralTexture;
  21135. })(BABYLON.Texture);
  21136. BABYLON.ProceduralTexture = ProceduralTexture;
  21137. })(BABYLON || (BABYLON = {}));
  21138. var BABYLON;
  21139. (function (BABYLON) {
  21140. var MirrorTexture = (function (_super) {
  21141. __extends(MirrorTexture, _super);
  21142. function MirrorTexture(name, size, scene, generateMipMaps) {
  21143. var _this = this;
  21144. _super.call(this, name, size, scene, generateMipMaps, true);
  21145. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  21146. this._transformMatrix = BABYLON.Matrix.Zero();
  21147. this._mirrorMatrix = BABYLON.Matrix.Zero();
  21148. this.onBeforeRender = function () {
  21149. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  21150. _this._savedViewMatrix = scene.getViewMatrix();
  21151. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  21152. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  21153. scene.clipPlane = _this.mirrorPlane;
  21154. scene.getEngine().cullBackFaces = false;
  21155. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  21156. };
  21157. this.onAfterRender = function () {
  21158. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  21159. scene.getEngine().cullBackFaces = true;
  21160. scene._mirroredCameraPosition = null;
  21161. delete scene.clipPlane;
  21162. };
  21163. }
  21164. MirrorTexture.prototype.clone = function () {
  21165. var textureSize = this.getSize();
  21166. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21167. // Base texture
  21168. newTexture.hasAlpha = this.hasAlpha;
  21169. newTexture.level = this.level;
  21170. // Mirror Texture
  21171. newTexture.mirrorPlane = this.mirrorPlane.clone();
  21172. newTexture.renderList = this.renderList.slice(0);
  21173. return newTexture;
  21174. };
  21175. MirrorTexture.prototype.serialize = function () {
  21176. if (!this.name) {
  21177. return null;
  21178. }
  21179. var serializationObject = _super.prototype.serialize.call(this);
  21180. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  21181. return serializationObject;
  21182. };
  21183. return MirrorTexture;
  21184. })(BABYLON.RenderTargetTexture);
  21185. BABYLON.MirrorTexture = MirrorTexture;
  21186. })(BABYLON || (BABYLON = {}));
  21187. var BABYLON;
  21188. (function (BABYLON) {
  21189. /**
  21190. * Creates a refraction texture used by refraction channel of the standard material.
  21191. * @param name the texture name
  21192. * @param size size of the underlying texture
  21193. * @param scene root scene
  21194. */
  21195. var RefractionTexture = (function (_super) {
  21196. __extends(RefractionTexture, _super);
  21197. function RefractionTexture(name, size, scene, generateMipMaps) {
  21198. var _this = this;
  21199. _super.call(this, name, size, scene, generateMipMaps, true);
  21200. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  21201. this.depth = 2.0;
  21202. this.onBeforeRender = function () {
  21203. scene.clipPlane = _this.refractionPlane;
  21204. };
  21205. this.onAfterRender = function () {
  21206. delete scene.clipPlane;
  21207. };
  21208. }
  21209. RefractionTexture.prototype.clone = function () {
  21210. var textureSize = this.getSize();
  21211. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21212. // Base texture
  21213. newTexture.hasAlpha = this.hasAlpha;
  21214. newTexture.level = this.level;
  21215. // Refraction Texture
  21216. newTexture.refractionPlane = this.refractionPlane.clone();
  21217. newTexture.renderList = this.renderList.slice(0);
  21218. newTexture.depth = this.depth;
  21219. return newTexture;
  21220. };
  21221. RefractionTexture.prototype.serialize = function () {
  21222. if (!this.name) {
  21223. return null;
  21224. }
  21225. var serializationObject = _super.prototype.serialize.call(this);
  21226. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  21227. serializationObject.depth = this.depth;
  21228. return serializationObject;
  21229. };
  21230. return RefractionTexture;
  21231. })(BABYLON.RenderTargetTexture);
  21232. BABYLON.RefractionTexture = RefractionTexture;
  21233. })(BABYLON || (BABYLON = {}));
  21234. var BABYLON;
  21235. (function (BABYLON) {
  21236. var DynamicTexture = (function (_super) {
  21237. __extends(DynamicTexture, _super);
  21238. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  21239. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21240. _super.call(this, null, scene, !generateMipMaps);
  21241. this.name = name;
  21242. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21243. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21244. this._generateMipMaps = generateMipMaps;
  21245. if (options.getContext) {
  21246. this._canvas = options;
  21247. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  21248. }
  21249. else {
  21250. this._canvas = document.createElement("canvas");
  21251. if (options.width) {
  21252. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  21253. }
  21254. else {
  21255. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  21256. }
  21257. }
  21258. var textureSize = this.getSize();
  21259. this._canvas.width = textureSize.width;
  21260. this._canvas.height = textureSize.height;
  21261. this._context = this._canvas.getContext("2d");
  21262. }
  21263. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  21264. get: function () {
  21265. return true;
  21266. },
  21267. enumerable: true,
  21268. configurable: true
  21269. });
  21270. DynamicTexture.prototype.scale = function (ratio) {
  21271. var textureSize = this.getSize();
  21272. textureSize.width *= ratio;
  21273. textureSize.height *= ratio;
  21274. this._canvas.width = textureSize.width;
  21275. this._canvas.height = textureSize.height;
  21276. this.releaseInternalTexture();
  21277. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  21278. };
  21279. DynamicTexture.prototype.getContext = function () {
  21280. return this._context;
  21281. };
  21282. DynamicTexture.prototype.clear = function () {
  21283. var size = this.getSize();
  21284. this._context.fillRect(0, 0, size.width, size.height);
  21285. };
  21286. DynamicTexture.prototype.update = function (invertY) {
  21287. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  21288. };
  21289. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  21290. if (update === void 0) { update = true; }
  21291. var size = this.getSize();
  21292. if (clearColor) {
  21293. this._context.fillStyle = clearColor;
  21294. this._context.fillRect(0, 0, size.width, size.height);
  21295. }
  21296. this._context.font = font;
  21297. if (x === null) {
  21298. var textSize = this._context.measureText(text);
  21299. x = (size.width - textSize.width) / 2;
  21300. }
  21301. this._context.fillStyle = color;
  21302. this._context.fillText(text, x, y);
  21303. if (update) {
  21304. this.update(invertY);
  21305. }
  21306. };
  21307. DynamicTexture.prototype.clone = function () {
  21308. var textureSize = this.getSize();
  21309. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21310. // Base texture
  21311. newTexture.hasAlpha = this.hasAlpha;
  21312. newTexture.level = this.level;
  21313. // Dynamic Texture
  21314. newTexture.wrapU = this.wrapU;
  21315. newTexture.wrapV = this.wrapV;
  21316. return newTexture;
  21317. };
  21318. return DynamicTexture;
  21319. })(BABYLON.Texture);
  21320. BABYLON.DynamicTexture = DynamicTexture;
  21321. })(BABYLON || (BABYLON = {}));
  21322. var BABYLON;
  21323. (function (BABYLON) {
  21324. var VideoTexture = (function (_super) {
  21325. __extends(VideoTexture, _super);
  21326. /**
  21327. * Creates a video texture.
  21328. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  21329. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  21330. * @param {BABYLON.Scene} scene is obviously the current scene.
  21331. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  21332. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  21333. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  21334. */
  21335. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  21336. var _this = this;
  21337. if (generateMipMaps === void 0) { generateMipMaps = false; }
  21338. if (invertY === void 0) { invertY = false; }
  21339. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21340. _super.call(this, null, scene, !generateMipMaps, invertY);
  21341. this._autoLaunch = true;
  21342. var urls;
  21343. this.name = name;
  21344. if (urlsOrVideo instanceof HTMLVideoElement) {
  21345. this.video = urlsOrVideo;
  21346. }
  21347. else {
  21348. urls = urlsOrVideo;
  21349. this.video = document.createElement("video");
  21350. this.video.autoplay = false;
  21351. this.video.loop = true;
  21352. }
  21353. this._generateMipMaps = generateMipMaps;
  21354. this._samplingMode = samplingMode;
  21355. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  21356. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21357. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21358. }
  21359. else {
  21360. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21361. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21362. this._generateMipMaps = false;
  21363. }
  21364. if (urls) {
  21365. this.video.addEventListener("canplaythrough", function () {
  21366. _this._createTexture();
  21367. });
  21368. urls.forEach(function (url) {
  21369. var source = document.createElement("source");
  21370. source.src = url;
  21371. _this.video.appendChild(source);
  21372. });
  21373. }
  21374. else {
  21375. this._createTexture();
  21376. }
  21377. this._lastUpdate = BABYLON.Tools.Now;
  21378. }
  21379. VideoTexture.prototype._createTexture = function () {
  21380. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode, false);
  21381. this._texture.isReady = true;
  21382. };
  21383. VideoTexture.prototype.update = function () {
  21384. if (this._autoLaunch) {
  21385. this._autoLaunch = false;
  21386. this.video.play();
  21387. }
  21388. var now = BABYLON.Tools.Now;
  21389. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  21390. return false;
  21391. }
  21392. this._lastUpdate = now;
  21393. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  21394. return true;
  21395. };
  21396. return VideoTexture;
  21397. })(BABYLON.Texture);
  21398. BABYLON.VideoTexture = VideoTexture;
  21399. })(BABYLON || (BABYLON = {}));
  21400. var BABYLON;
  21401. (function (BABYLON) {
  21402. var CustomProceduralTexture = (function (_super) {
  21403. __extends(CustomProceduralTexture, _super);
  21404. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  21405. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  21406. this._animate = true;
  21407. this._time = 0;
  21408. this._texturePath = texturePath;
  21409. //Try to load json
  21410. this.loadJson(texturePath);
  21411. this.refreshRate = 1;
  21412. }
  21413. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  21414. var _this = this;
  21415. var that = this;
  21416. function noConfigFile() {
  21417. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  21418. try {
  21419. that.setFragment(that._texturePath);
  21420. }
  21421. catch (ex) {
  21422. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  21423. }
  21424. }
  21425. var configFileUrl = jsonUrl + "/config.json";
  21426. var xhr = new XMLHttpRequest();
  21427. xhr.open("GET", configFileUrl, true);
  21428. xhr.addEventListener("load", function () {
  21429. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  21430. try {
  21431. _this._config = JSON.parse(xhr.response);
  21432. _this.updateShaderUniforms();
  21433. _this.updateTextures();
  21434. _this.setFragment(_this._texturePath + "/custom");
  21435. _this._animate = _this._config.animate;
  21436. _this.refreshRate = _this._config.refreshrate;
  21437. }
  21438. catch (ex) {
  21439. noConfigFile();
  21440. }
  21441. }
  21442. else {
  21443. noConfigFile();
  21444. }
  21445. }, false);
  21446. xhr.addEventListener("error", function () {
  21447. noConfigFile();
  21448. }, false);
  21449. try {
  21450. xhr.send();
  21451. }
  21452. catch (ex) {
  21453. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  21454. }
  21455. };
  21456. CustomProceduralTexture.prototype.isReady = function () {
  21457. if (!_super.prototype.isReady.call(this)) {
  21458. return false;
  21459. }
  21460. for (var name in this._textures) {
  21461. var texture = this._textures[name];
  21462. if (!texture.isReady()) {
  21463. return false;
  21464. }
  21465. }
  21466. return true;
  21467. };
  21468. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  21469. if (this._animate) {
  21470. this._time += this.getScene().getAnimationRatio() * 0.03;
  21471. this.updateShaderUniforms();
  21472. }
  21473. _super.prototype.render.call(this, useCameraPostProcess);
  21474. };
  21475. CustomProceduralTexture.prototype.updateTextures = function () {
  21476. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  21477. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  21478. }
  21479. };
  21480. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  21481. if (this._config) {
  21482. for (var j = 0; j < this._config.uniforms.length; j++) {
  21483. var uniform = this._config.uniforms[j];
  21484. switch (uniform.type) {
  21485. case "float":
  21486. this.setFloat(uniform.name, uniform.value);
  21487. break;
  21488. case "color3":
  21489. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  21490. break;
  21491. case "color4":
  21492. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  21493. break;
  21494. case "vector2":
  21495. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  21496. break;
  21497. case "vector3":
  21498. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  21499. break;
  21500. }
  21501. }
  21502. }
  21503. this.setFloat("time", this._time);
  21504. };
  21505. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  21506. get: function () {
  21507. return this._animate;
  21508. },
  21509. set: function (value) {
  21510. this._animate = value;
  21511. },
  21512. enumerable: true,
  21513. configurable: true
  21514. });
  21515. return CustomProceduralTexture;
  21516. })(BABYLON.ProceduralTexture);
  21517. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  21518. })(BABYLON || (BABYLON = {}));
  21519. var BABYLON;
  21520. (function (BABYLON) {
  21521. var EffectFallbacks = (function () {
  21522. function EffectFallbacks() {
  21523. this._defines = {};
  21524. this._currentRank = 32;
  21525. this._maxRank = -1;
  21526. }
  21527. EffectFallbacks.prototype.addFallback = function (rank, define) {
  21528. if (!this._defines[rank]) {
  21529. if (rank < this._currentRank) {
  21530. this._currentRank = rank;
  21531. }
  21532. if (rank > this._maxRank) {
  21533. this._maxRank = rank;
  21534. }
  21535. this._defines[rank] = new Array();
  21536. }
  21537. this._defines[rank].push(define);
  21538. };
  21539. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  21540. this._meshRank = rank;
  21541. this._mesh = mesh;
  21542. if (rank > this._maxRank) {
  21543. this._maxRank = rank;
  21544. }
  21545. };
  21546. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  21547. get: function () {
  21548. return this._currentRank <= this._maxRank;
  21549. },
  21550. enumerable: true,
  21551. configurable: true
  21552. });
  21553. EffectFallbacks.prototype.reduce = function (currentDefines) {
  21554. var currentFallbacks = this._defines[this._currentRank];
  21555. for (var index = 0; index < currentFallbacks.length; index++) {
  21556. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  21557. }
  21558. if (this._mesh && this._currentRank === this._meshRank) {
  21559. this._mesh.computeBonesUsingShaders = false;
  21560. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  21561. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  21562. }
  21563. this._currentRank++;
  21564. return currentDefines;
  21565. };
  21566. return EffectFallbacks;
  21567. })();
  21568. BABYLON.EffectFallbacks = EffectFallbacks;
  21569. var Effect = (function () {
  21570. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  21571. var _this = this;
  21572. this._isReady = false;
  21573. this._compilationError = "";
  21574. this._valueCache = [];
  21575. this._engine = engine;
  21576. this.name = baseName;
  21577. this.defines = defines;
  21578. this._uniformsNames = uniformsNames.concat(samplers);
  21579. this._samplers = samplers;
  21580. this._attributesNames = attributesNames;
  21581. this.onError = onError;
  21582. this.onCompiled = onCompiled;
  21583. var vertexSource;
  21584. var fragmentSource;
  21585. if (baseName.vertexElement) {
  21586. vertexSource = document.getElementById(baseName.vertexElement);
  21587. if (!vertexSource) {
  21588. vertexSource = baseName.vertexElement;
  21589. }
  21590. }
  21591. else {
  21592. vertexSource = baseName.vertex || baseName;
  21593. }
  21594. if (baseName.fragmentElement) {
  21595. fragmentSource = document.getElementById(baseName.fragmentElement);
  21596. if (!fragmentSource) {
  21597. fragmentSource = baseName.fragmentElement;
  21598. }
  21599. }
  21600. else {
  21601. fragmentSource = baseName.fragment || baseName;
  21602. }
  21603. this._loadVertexShader(vertexSource, function (vertexCode) {
  21604. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  21605. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  21606. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  21607. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  21608. });
  21609. });
  21610. });
  21611. });
  21612. }
  21613. // Properties
  21614. Effect.prototype.isReady = function () {
  21615. return this._isReady;
  21616. };
  21617. Effect.prototype.getProgram = function () {
  21618. return this._program;
  21619. };
  21620. Effect.prototype.getAttributesNames = function () {
  21621. return this._attributesNames;
  21622. };
  21623. Effect.prototype.getAttributeLocation = function (index) {
  21624. return this._attributes[index];
  21625. };
  21626. Effect.prototype.getAttributeLocationByName = function (name) {
  21627. var index = this._attributesNames.indexOf(name);
  21628. return this._attributes[index];
  21629. };
  21630. Effect.prototype.getAttributesCount = function () {
  21631. return this._attributes.length;
  21632. };
  21633. Effect.prototype.getUniformIndex = function (uniformName) {
  21634. return this._uniformsNames.indexOf(uniformName);
  21635. };
  21636. Effect.prototype.getUniform = function (uniformName) {
  21637. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  21638. };
  21639. Effect.prototype.getSamplers = function () {
  21640. return this._samplers;
  21641. };
  21642. Effect.prototype.getCompilationError = function () {
  21643. return this._compilationError;
  21644. };
  21645. // Methods
  21646. Effect.prototype._loadVertexShader = function (vertex, callback) {
  21647. // DOM element ?
  21648. if (vertex instanceof HTMLElement) {
  21649. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  21650. callback(vertexCode);
  21651. return;
  21652. }
  21653. // Is in local store ?
  21654. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  21655. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  21656. return;
  21657. }
  21658. var vertexShaderUrl;
  21659. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  21660. vertexShaderUrl = vertex;
  21661. }
  21662. else {
  21663. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  21664. }
  21665. // Vertex shader
  21666. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  21667. };
  21668. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  21669. // DOM element ?
  21670. if (fragment instanceof HTMLElement) {
  21671. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  21672. callback(fragmentCode);
  21673. return;
  21674. }
  21675. // Is in local store ?
  21676. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  21677. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  21678. return;
  21679. }
  21680. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  21681. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  21682. return;
  21683. }
  21684. var fragmentShaderUrl;
  21685. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  21686. fragmentShaderUrl = fragment;
  21687. }
  21688. else {
  21689. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  21690. }
  21691. // Fragment shader
  21692. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  21693. };
  21694. Effect.prototype._dumpShadersName = function () {
  21695. if (this.name.vertexElement) {
  21696. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  21697. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  21698. }
  21699. else if (this.name.vertex) {
  21700. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  21701. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  21702. }
  21703. else {
  21704. BABYLON.Tools.Error("Vertex shader:" + this.name);
  21705. BABYLON.Tools.Error("Fragment shader:" + this.name);
  21706. }
  21707. };
  21708. Effect.prototype._processIncludes = function (sourceCode, callback) {
  21709. var _this = this;
  21710. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  21711. var match = regex.exec(sourceCode);
  21712. var returnValue = new String(sourceCode);
  21713. while (match != null) {
  21714. var includeFile = match[1];
  21715. if (Effect.IncludesShadersStore[includeFile]) {
  21716. // Substitution
  21717. var includeContent = Effect.IncludesShadersStore[includeFile];
  21718. if (match[2]) {
  21719. var splits = match[3].split(",");
  21720. for (var index = 0; index < splits.length; index += 2) {
  21721. var source = new RegExp(splits[index], "g");
  21722. var dest = splits[index + 1];
  21723. includeContent = includeContent.replace(source, dest);
  21724. }
  21725. }
  21726. if (match[4]) {
  21727. includeContent = includeContent.replace(/\{X\}/g, match[5]);
  21728. }
  21729. // Replace
  21730. returnValue = returnValue.replace(match[0], includeContent);
  21731. }
  21732. else {
  21733. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  21734. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  21735. Effect.IncludesShadersStore[includeFile] = fileContent;
  21736. _this._processIncludes(returnValue, callback);
  21737. });
  21738. return;
  21739. }
  21740. match = regex.exec(sourceCode);
  21741. }
  21742. callback(returnValue);
  21743. };
  21744. Effect.prototype._processPrecision = function (source) {
  21745. if (source.indexOf("precision highp float") === -1) {
  21746. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21747. source = "precision mediump float;\n" + source;
  21748. }
  21749. else {
  21750. source = "precision highp float;\n" + source;
  21751. }
  21752. }
  21753. else {
  21754. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21755. source = source.replace("precision highp float", "precision mediump float");
  21756. }
  21757. }
  21758. return source;
  21759. };
  21760. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  21761. try {
  21762. var engine = this._engine;
  21763. // Precision
  21764. vertexSourceCode = this._processPrecision(vertexSourceCode);
  21765. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  21766. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  21767. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  21768. this._attributes = engine.getAttributes(this._program, attributesNames);
  21769. for (var index = 0; index < this._samplers.length; index++) {
  21770. var sampler = this.getUniform(this._samplers[index]);
  21771. if (sampler == null) {
  21772. this._samplers.splice(index, 1);
  21773. index--;
  21774. }
  21775. }
  21776. engine.bindSamplers(this);
  21777. this._isReady = true;
  21778. if (this.onCompiled) {
  21779. this.onCompiled(this);
  21780. }
  21781. }
  21782. catch (e) {
  21783. // Is it a problem with precision?
  21784. if (e.message.indexOf("highp") !== -1) {
  21785. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  21786. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  21787. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  21788. return;
  21789. }
  21790. // Let's go through fallbacks then
  21791. if (fallbacks && fallbacks.isMoreFallbacks) {
  21792. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  21793. this._dumpShadersName();
  21794. defines = fallbacks.reduce(defines);
  21795. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  21796. }
  21797. else {
  21798. BABYLON.Tools.Error("Unable to compile effect: ");
  21799. this._dumpShadersName();
  21800. BABYLON.Tools.Error("Defines: " + defines);
  21801. BABYLON.Tools.Error("Error: " + e.message);
  21802. this._compilationError = e.message;
  21803. if (this.onError) {
  21804. this.onError(this, this._compilationError);
  21805. }
  21806. }
  21807. }
  21808. };
  21809. Object.defineProperty(Effect.prototype, "isSupported", {
  21810. get: function () {
  21811. return this._compilationError === "";
  21812. },
  21813. enumerable: true,
  21814. configurable: true
  21815. });
  21816. Effect.prototype._bindTexture = function (channel, texture) {
  21817. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  21818. };
  21819. Effect.prototype.setTexture = function (channel, texture) {
  21820. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  21821. };
  21822. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  21823. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  21824. };
  21825. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  21826. if (!this._valueCache[uniformName]) {
  21827. this._valueCache[uniformName] = new BABYLON.Matrix();
  21828. }
  21829. for (var index = 0; index < 16; index++) {
  21830. this._valueCache[uniformName].m[index] = matrix.m[index];
  21831. }
  21832. };
  21833. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  21834. if (!this._valueCache[uniformName]) {
  21835. this._valueCache[uniformName] = [x, y];
  21836. return;
  21837. }
  21838. this._valueCache[uniformName][0] = x;
  21839. this._valueCache[uniformName][1] = y;
  21840. };
  21841. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  21842. if (!this._valueCache[uniformName]) {
  21843. this._valueCache[uniformName] = [x, y, z];
  21844. return;
  21845. }
  21846. this._valueCache[uniformName][0] = x;
  21847. this._valueCache[uniformName][1] = y;
  21848. this._valueCache[uniformName][2] = z;
  21849. };
  21850. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  21851. if (!this._valueCache[uniformName]) {
  21852. this._valueCache[uniformName] = [x, y, z, w];
  21853. return;
  21854. }
  21855. this._valueCache[uniformName][0] = x;
  21856. this._valueCache[uniformName][1] = y;
  21857. this._valueCache[uniformName][2] = z;
  21858. this._valueCache[uniformName][3] = w;
  21859. };
  21860. Effect.prototype.setArray = function (uniformName, array) {
  21861. this._engine.setArray(this.getUniform(uniformName), array);
  21862. return this;
  21863. };
  21864. Effect.prototype.setArray2 = function (uniformName, array) {
  21865. this._engine.setArray2(this.getUniform(uniformName), array);
  21866. return this;
  21867. };
  21868. Effect.prototype.setArray3 = function (uniformName, array) {
  21869. this._engine.setArray3(this.getUniform(uniformName), array);
  21870. return this;
  21871. };
  21872. Effect.prototype.setArray4 = function (uniformName, array) {
  21873. this._engine.setArray4(this.getUniform(uniformName), array);
  21874. return this;
  21875. };
  21876. Effect.prototype.setMatrices = function (uniformName, matrices) {
  21877. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  21878. return this;
  21879. };
  21880. Effect.prototype.setMatrix = function (uniformName, matrix) {
  21881. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  21882. // return this;
  21883. // this._cacheMatrix(uniformName, matrix);
  21884. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  21885. return this;
  21886. };
  21887. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  21888. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  21889. return this;
  21890. };
  21891. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  21892. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  21893. return this;
  21894. };
  21895. Effect.prototype.setFloat = function (uniformName, value) {
  21896. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  21897. return this;
  21898. this._valueCache[uniformName] = value;
  21899. this._engine.setFloat(this.getUniform(uniformName), value);
  21900. return this;
  21901. };
  21902. Effect.prototype.setBool = function (uniformName, bool) {
  21903. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  21904. return this;
  21905. this._valueCache[uniformName] = bool;
  21906. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  21907. return this;
  21908. };
  21909. Effect.prototype.setVector2 = function (uniformName, vector2) {
  21910. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  21911. return this;
  21912. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  21913. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  21914. return this;
  21915. };
  21916. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  21917. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  21918. return this;
  21919. this._cacheFloat2(uniformName, x, y);
  21920. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  21921. return this;
  21922. };
  21923. Effect.prototype.setVector3 = function (uniformName, vector3) {
  21924. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  21925. return this;
  21926. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  21927. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  21928. return this;
  21929. };
  21930. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  21931. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  21932. return this;
  21933. this._cacheFloat3(uniformName, x, y, z);
  21934. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  21935. return this;
  21936. };
  21937. Effect.prototype.setVector4 = function (uniformName, vector4) {
  21938. 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)
  21939. return this;
  21940. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  21941. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  21942. return this;
  21943. };
  21944. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  21945. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  21946. return this;
  21947. this._cacheFloat4(uniformName, x, y, z, w);
  21948. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  21949. return this;
  21950. };
  21951. Effect.prototype.setColor3 = function (uniformName, color3) {
  21952. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  21953. return this;
  21954. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  21955. this._engine.setColor3(this.getUniform(uniformName), color3);
  21956. return this;
  21957. };
  21958. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  21959. 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)
  21960. return this;
  21961. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  21962. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  21963. return this;
  21964. };
  21965. // Statics
  21966. Effect.ShadersStore = {};
  21967. Effect.IncludesShadersStore = {};
  21968. return Effect;
  21969. })();
  21970. BABYLON.Effect = Effect;
  21971. })(BABYLON || (BABYLON = {}));
  21972. var BABYLON;
  21973. (function (BABYLON) {
  21974. var maxSimultaneousLights = 4;
  21975. var MaterialHelper = (function () {
  21976. function MaterialHelper() {
  21977. }
  21978. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines) {
  21979. var lightIndex = 0;
  21980. var needNormals = false;
  21981. for (var index = 0; index < scene.lights.length; index++) {
  21982. var light = scene.lights[index];
  21983. if (!light.isEnabled()) {
  21984. continue;
  21985. }
  21986. // Excluded check
  21987. if (light._excludedMeshesIds.length > 0) {
  21988. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  21989. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  21990. if (excludedMesh) {
  21991. light.excludedMeshes.push(excludedMesh);
  21992. }
  21993. }
  21994. light._excludedMeshesIds = [];
  21995. }
  21996. // Included check
  21997. if (light._includedOnlyMeshesIds.length > 0) {
  21998. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  21999. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  22000. if (includedOnlyMesh) {
  22001. light.includedOnlyMeshes.push(includedOnlyMesh);
  22002. }
  22003. }
  22004. light._includedOnlyMeshesIds = [];
  22005. }
  22006. if (!light.canAffectMesh(mesh)) {
  22007. continue;
  22008. }
  22009. needNormals = true;
  22010. defines["LIGHT" + lightIndex] = true;
  22011. var type;
  22012. if (light instanceof BABYLON.SpotLight) {
  22013. type = "SPOTLIGHT" + lightIndex;
  22014. }
  22015. else if (light instanceof BABYLON.HemisphericLight) {
  22016. type = "HEMILIGHT" + lightIndex;
  22017. }
  22018. else if (light instanceof BABYLON.PointLight) {
  22019. type = "POINTLIGHT" + lightIndex;
  22020. }
  22021. else {
  22022. type = "DIRLIGHT" + lightIndex;
  22023. }
  22024. defines[type] = true;
  22025. // Specular
  22026. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  22027. defines["SPECULARTERM"] = true;
  22028. }
  22029. // Shadows
  22030. if (scene.shadowsEnabled) {
  22031. var shadowGenerator = light.getShadowGenerator();
  22032. if (mesh && mesh.receiveShadows && shadowGenerator) {
  22033. defines["SHADOW" + lightIndex] = true;
  22034. defines["SHADOWS"] = true;
  22035. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  22036. defines["SHADOWVSM" + lightIndex] = true;
  22037. }
  22038. if (shadowGenerator.usePoissonSampling) {
  22039. defines["SHADOWPCF" + lightIndex] = true;
  22040. }
  22041. }
  22042. }
  22043. lightIndex++;
  22044. if (lightIndex === maxSimultaneousLights)
  22045. break;
  22046. }
  22047. return needNormals;
  22048. };
  22049. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks) {
  22050. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22051. if (!defines["LIGHT" + lightIndex]) {
  22052. continue;
  22053. }
  22054. if (lightIndex > 0) {
  22055. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  22056. }
  22057. if (defines["SHADOW" + lightIndex]) {
  22058. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  22059. }
  22060. if (defines["SHADOWPCF" + lightIndex]) {
  22061. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  22062. }
  22063. if (defines["SHADOWVSM" + lightIndex]) {
  22064. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  22065. }
  22066. }
  22067. };
  22068. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  22069. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  22070. fallbacks.addCPUSkinningFallback(0, mesh);
  22071. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22072. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22073. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  22074. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  22075. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  22076. }
  22077. }
  22078. };
  22079. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  22080. if (defines["INSTANCES"]) {
  22081. attribs.push("world0");
  22082. attribs.push("world1");
  22083. attribs.push("world2");
  22084. attribs.push("world3");
  22085. }
  22086. };
  22087. // Bindings
  22088. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  22089. var shadowGenerator = light.getShadowGenerator();
  22090. if (mesh.receiveShadows && shadowGenerator) {
  22091. if (!light.needCube()) {
  22092. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  22093. }
  22094. else {
  22095. if (!depthValuesAlreadySet) {
  22096. depthValuesAlreadySet = true;
  22097. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  22098. }
  22099. }
  22100. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  22101. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  22102. }
  22103. return depthValuesAlreadySet;
  22104. };
  22105. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  22106. if (light instanceof BABYLON.PointLight) {
  22107. // Point Light
  22108. light.transferToEffect(effect, "vLightData" + lightIndex);
  22109. }
  22110. else if (light instanceof BABYLON.DirectionalLight) {
  22111. // Directional Light
  22112. light.transferToEffect(effect, "vLightData" + lightIndex);
  22113. }
  22114. else if (light instanceof BABYLON.SpotLight) {
  22115. // Spot Light
  22116. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  22117. }
  22118. else if (light instanceof BABYLON.HemisphericLight) {
  22119. // Hemispheric Light
  22120. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  22121. }
  22122. };
  22123. MaterialHelper.BindLights = function (scene, mesh, effect, defines) {
  22124. var lightIndex = 0;
  22125. var depthValuesAlreadySet = false;
  22126. for (var index = 0; index < scene.lights.length; index++) {
  22127. var light = scene.lights[index];
  22128. if (!light.isEnabled()) {
  22129. continue;
  22130. }
  22131. if (!light.canAffectMesh(mesh)) {
  22132. continue;
  22133. }
  22134. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  22135. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  22136. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  22137. if (defines["SPECULARTERM"]) {
  22138. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  22139. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  22140. }
  22141. // Shadows
  22142. if (scene.shadowsEnabled) {
  22143. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  22144. }
  22145. lightIndex++;
  22146. if (lightIndex === maxSimultaneousLights)
  22147. break;
  22148. }
  22149. };
  22150. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  22151. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  22152. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  22153. effect.setColor3("vFogColor", scene.fogColor);
  22154. }
  22155. };
  22156. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  22157. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  22158. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  22159. }
  22160. };
  22161. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  22162. if (defines["LOGARITHMICDEPTH"]) {
  22163. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  22164. }
  22165. };
  22166. MaterialHelper.BindClipPlane = function (effect, scene) {
  22167. if (scene.clipPlane) {
  22168. var clipPlane = scene.clipPlane;
  22169. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22170. }
  22171. };
  22172. return MaterialHelper;
  22173. })();
  22174. BABYLON.MaterialHelper = MaterialHelper;
  22175. })(BABYLON || (BABYLON = {}));
  22176. var BABYLON;
  22177. (function (BABYLON) {
  22178. var FresnelParameters = (function () {
  22179. function FresnelParameters() {
  22180. this.isEnabled = true;
  22181. this.leftColor = BABYLON.Color3.White();
  22182. this.rightColor = BABYLON.Color3.Black();
  22183. this.bias = 0;
  22184. this.power = 1;
  22185. }
  22186. FresnelParameters.prototype.clone = function () {
  22187. var newFresnelParameters = new FresnelParameters();
  22188. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  22189. return new FresnelParameters;
  22190. };
  22191. FresnelParameters.prototype.serialize = function () {
  22192. var serializationObject = {};
  22193. serializationObject.isEnabled = this.isEnabled;
  22194. serializationObject.leftColor = this.leftColor;
  22195. serializationObject.rightColor = this.rightColor;
  22196. serializationObject.bias = this.bias;
  22197. serializationObject.power = this.power;
  22198. return serializationObject;
  22199. };
  22200. FresnelParameters.Parse = function (parsedFresnelParameters) {
  22201. var fresnelParameters = new FresnelParameters();
  22202. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  22203. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  22204. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  22205. fresnelParameters.bias = parsedFresnelParameters.bias;
  22206. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  22207. return fresnelParameters;
  22208. };
  22209. return FresnelParameters;
  22210. })();
  22211. BABYLON.FresnelParameters = FresnelParameters;
  22212. })(BABYLON || (BABYLON = {}));
  22213. var BABYLON;
  22214. (function (BABYLON) {
  22215. var MaterialDefines = (function () {
  22216. function MaterialDefines() {
  22217. }
  22218. MaterialDefines.prototype.isEqual = function (other) {
  22219. for (var index = 0; index < this._keys.length; index++) {
  22220. var prop = this._keys[index];
  22221. if (this[prop] !== other[prop]) {
  22222. return false;
  22223. }
  22224. }
  22225. return true;
  22226. };
  22227. MaterialDefines.prototype.cloneTo = function (other) {
  22228. for (var index = 0; index < this._keys.length; index++) {
  22229. var prop = this._keys[index];
  22230. other[prop] = this[prop];
  22231. }
  22232. };
  22233. MaterialDefines.prototype.reset = function () {
  22234. for (var index = 0; index < this._keys.length; index++) {
  22235. var prop = this._keys[index];
  22236. if (typeof (this[prop]) === "number") {
  22237. this[prop] = 0;
  22238. }
  22239. else {
  22240. this[prop] = false;
  22241. }
  22242. }
  22243. };
  22244. MaterialDefines.prototype.toString = function () {
  22245. var result = "";
  22246. for (var index = 0; index < this._keys.length; index++) {
  22247. var prop = this._keys[index];
  22248. if (typeof (this[prop]) === "number") {
  22249. result += "#define " + prop + " " + this[prop] + "\n";
  22250. }
  22251. else if (this[prop]) {
  22252. result += "#define " + prop + "\n";
  22253. }
  22254. }
  22255. return result;
  22256. };
  22257. return MaterialDefines;
  22258. })();
  22259. BABYLON.MaterialDefines = MaterialDefines;
  22260. var Material = (function () {
  22261. function Material(name, scene, doNotAdd) {
  22262. this.name = name;
  22263. this.checkReadyOnEveryCall = false;
  22264. this.checkReadyOnlyOnce = false;
  22265. this.state = "";
  22266. this.alpha = 1.0;
  22267. this.backFaceCulling = true;
  22268. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  22269. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  22270. this.disableDepthWrite = false;
  22271. this.fogEnabled = true;
  22272. this.pointSize = 1.0;
  22273. this.zOffset = 0;
  22274. this._wasPreviouslyReady = false;
  22275. this._fillMode = Material.TriangleFillMode;
  22276. this.id = name;
  22277. this._scene = scene;
  22278. if (!doNotAdd) {
  22279. scene.materials.push(this);
  22280. }
  22281. }
  22282. Object.defineProperty(Material, "TriangleFillMode", {
  22283. get: function () {
  22284. return Material._TriangleFillMode;
  22285. },
  22286. enumerable: true,
  22287. configurable: true
  22288. });
  22289. Object.defineProperty(Material, "WireFrameFillMode", {
  22290. get: function () {
  22291. return Material._WireFrameFillMode;
  22292. },
  22293. enumerable: true,
  22294. configurable: true
  22295. });
  22296. Object.defineProperty(Material, "PointFillMode", {
  22297. get: function () {
  22298. return Material._PointFillMode;
  22299. },
  22300. enumerable: true,
  22301. configurable: true
  22302. });
  22303. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  22304. get: function () {
  22305. return Material._ClockWiseSideOrientation;
  22306. },
  22307. enumerable: true,
  22308. configurable: true
  22309. });
  22310. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  22311. get: function () {
  22312. return Material._CounterClockWiseSideOrientation;
  22313. },
  22314. enumerable: true,
  22315. configurable: true
  22316. });
  22317. Object.defineProperty(Material.prototype, "wireframe", {
  22318. get: function () {
  22319. return this._fillMode === Material.WireFrameFillMode;
  22320. },
  22321. set: function (value) {
  22322. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  22323. },
  22324. enumerable: true,
  22325. configurable: true
  22326. });
  22327. Object.defineProperty(Material.prototype, "pointsCloud", {
  22328. get: function () {
  22329. return this._fillMode === Material.PointFillMode;
  22330. },
  22331. set: function (value) {
  22332. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  22333. },
  22334. enumerable: true,
  22335. configurable: true
  22336. });
  22337. Object.defineProperty(Material.prototype, "fillMode", {
  22338. get: function () {
  22339. return this._fillMode;
  22340. },
  22341. set: function (value) {
  22342. this._fillMode = value;
  22343. },
  22344. enumerable: true,
  22345. configurable: true
  22346. });
  22347. /**
  22348. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22349. * subclasses should override adding information pertainent to themselves
  22350. */
  22351. Material.prototype.toString = function (fullDetails) {
  22352. var ret = "Name: " + this.name;
  22353. if (fullDetails) {
  22354. }
  22355. return ret;
  22356. };
  22357. Object.defineProperty(Material.prototype, "isFrozen", {
  22358. get: function () {
  22359. return this.checkReadyOnlyOnce;
  22360. },
  22361. enumerable: true,
  22362. configurable: true
  22363. });
  22364. Material.prototype.freeze = function () {
  22365. this.checkReadyOnlyOnce = true;
  22366. };
  22367. Material.prototype.unfreeze = function () {
  22368. this.checkReadyOnlyOnce = false;
  22369. };
  22370. Material.prototype.isReady = function (mesh, useInstances) {
  22371. return true;
  22372. };
  22373. Material.prototype.getEffect = function () {
  22374. return this._effect;
  22375. };
  22376. Material.prototype.getScene = function () {
  22377. return this._scene;
  22378. };
  22379. Material.prototype.needAlphaBlending = function () {
  22380. return (this.alpha < 1.0);
  22381. };
  22382. Material.prototype.needAlphaTesting = function () {
  22383. return false;
  22384. };
  22385. Material.prototype.getAlphaTestTexture = function () {
  22386. return null;
  22387. };
  22388. Material.prototype.trackCreation = function (onCompiled, onError) {
  22389. };
  22390. Material.prototype.markDirty = function () {
  22391. this._wasPreviouslyReady = false;
  22392. };
  22393. Material.prototype._preBind = function () {
  22394. var engine = this._scene.getEngine();
  22395. engine.enableEffect(this._effect);
  22396. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  22397. };
  22398. Material.prototype.bind = function (world, mesh) {
  22399. this._scene._cachedMaterial = this;
  22400. if (this.onBind) {
  22401. this.onBind(this, mesh);
  22402. }
  22403. if (this.disableDepthWrite) {
  22404. var engine = this._scene.getEngine();
  22405. this._cachedDepthWriteState = engine.getDepthWrite();
  22406. engine.setDepthWrite(false);
  22407. }
  22408. };
  22409. Material.prototype.bindOnlyWorldMatrix = function (world) {
  22410. };
  22411. Material.prototype.unbind = function () {
  22412. if (this.disableDepthWrite) {
  22413. var engine = this._scene.getEngine();
  22414. engine.setDepthWrite(this._cachedDepthWriteState);
  22415. }
  22416. };
  22417. Material.prototype.clone = function (name) {
  22418. return null;
  22419. };
  22420. Material.prototype.getBindedMeshes = function () {
  22421. var result = new Array();
  22422. for (var index = 0; index < this._scene.meshes.length; index++) {
  22423. var mesh = this._scene.meshes[index];
  22424. if (mesh.material === this) {
  22425. result.push(mesh);
  22426. }
  22427. }
  22428. return result;
  22429. };
  22430. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  22431. // Animations
  22432. this.getScene().stopAnimation(this);
  22433. // Remove from scene
  22434. var index = this._scene.materials.indexOf(this);
  22435. if (index >= 0) {
  22436. this._scene.materials.splice(index, 1);
  22437. }
  22438. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  22439. if (forceDisposeEffect && this._effect) {
  22440. this._scene.getEngine()._releaseEffect(this._effect);
  22441. this._effect = null;
  22442. }
  22443. // Remove from meshes
  22444. for (index = 0; index < this._scene.meshes.length; index++) {
  22445. var mesh = this._scene.meshes[index];
  22446. if (mesh.material === this) {
  22447. mesh.material = null;
  22448. }
  22449. }
  22450. // Callback
  22451. if (this.onDispose) {
  22452. this.onDispose();
  22453. }
  22454. };
  22455. Material.prototype.serialize = function () {
  22456. return BABYLON.SerializationHelper.Serialize(this);
  22457. };
  22458. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  22459. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  22460. multiMaterial.id = parsedMultiMaterial.id;
  22461. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  22462. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  22463. var subMatId = parsedMultiMaterial.materials[matIndex];
  22464. if (subMatId) {
  22465. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  22466. }
  22467. else {
  22468. multiMaterial.subMaterials.push(null);
  22469. }
  22470. }
  22471. return multiMaterial;
  22472. };
  22473. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  22474. if (!parsedMaterial.customType) {
  22475. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  22476. }
  22477. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  22478. return materialType.Parse(parsedMaterial, scene, rootUrl);
  22479. ;
  22480. };
  22481. Material._TriangleFillMode = 0;
  22482. Material._WireFrameFillMode = 1;
  22483. Material._PointFillMode = 2;
  22484. Material._ClockWiseSideOrientation = 0;
  22485. Material._CounterClockWiseSideOrientation = 1;
  22486. __decorate([
  22487. BABYLON.serialize()
  22488. ], Material.prototype, "id", void 0);
  22489. __decorate([
  22490. BABYLON.serialize()
  22491. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  22492. __decorate([
  22493. BABYLON.serialize()
  22494. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  22495. __decorate([
  22496. BABYLON.serialize()
  22497. ], Material.prototype, "state", void 0);
  22498. __decorate([
  22499. BABYLON.serialize()
  22500. ], Material.prototype, "alpha", void 0);
  22501. __decorate([
  22502. BABYLON.serialize()
  22503. ], Material.prototype, "backFaceCulling", void 0);
  22504. __decorate([
  22505. BABYLON.serialize()
  22506. ], Material.prototype, "sideOrientation", void 0);
  22507. __decorate([
  22508. BABYLON.serialize()
  22509. ], Material.prototype, "alphaMode", void 0);
  22510. __decorate([
  22511. BABYLON.serialize()
  22512. ], Material.prototype, "disableDepthWrite", void 0);
  22513. __decorate([
  22514. BABYLON.serialize()
  22515. ], Material.prototype, "fogEnabled", void 0);
  22516. __decorate([
  22517. BABYLON.serialize()
  22518. ], Material.prototype, "pointSize", void 0);
  22519. __decorate([
  22520. BABYLON.serialize()
  22521. ], Material.prototype, "zOffset", void 0);
  22522. __decorate([
  22523. BABYLON.serialize()
  22524. ], Material.prototype, "wireframe", null);
  22525. __decorate([
  22526. BABYLON.serialize()
  22527. ], Material.prototype, "pointsCloud", null);
  22528. __decorate([
  22529. BABYLON.serialize()
  22530. ], Material.prototype, "fillMode", null);
  22531. return Material;
  22532. })();
  22533. BABYLON.Material = Material;
  22534. })(BABYLON || (BABYLON = {}));
  22535. var BABYLON;
  22536. (function (BABYLON) {
  22537. var StandardMaterialDefines = (function (_super) {
  22538. __extends(StandardMaterialDefines, _super);
  22539. function StandardMaterialDefines() {
  22540. _super.call(this);
  22541. this.DIFFUSE = false;
  22542. this.AMBIENT = false;
  22543. this.OPACITY = false;
  22544. this.OPACITYRGB = false;
  22545. this.REFLECTION = false;
  22546. this.EMISSIVE = false;
  22547. this.SPECULAR = false;
  22548. this.BUMP = false;
  22549. this.PARALLAX = false;
  22550. this.PARALLAXOCCLUSION = false;
  22551. this.SPECULAROVERALPHA = false;
  22552. this.CLIPPLANE = false;
  22553. this.ALPHATEST = false;
  22554. this.ALPHAFROMDIFFUSE = false;
  22555. this.POINTSIZE = false;
  22556. this.FOG = false;
  22557. this.LIGHT0 = false;
  22558. this.LIGHT1 = false;
  22559. this.LIGHT2 = false;
  22560. this.LIGHT3 = false;
  22561. this.SPOTLIGHT0 = false;
  22562. this.SPOTLIGHT1 = false;
  22563. this.SPOTLIGHT2 = false;
  22564. this.SPOTLIGHT3 = false;
  22565. this.HEMILIGHT0 = false;
  22566. this.HEMILIGHT1 = false;
  22567. this.HEMILIGHT2 = false;
  22568. this.HEMILIGHT3 = false;
  22569. this.POINTLIGHT0 = false;
  22570. this.POINTLIGHT1 = false;
  22571. this.POINTLIGHT2 = false;
  22572. this.POINTLIGHT3 = false;
  22573. this.DIRLIGHT0 = false;
  22574. this.DIRLIGHT1 = false;
  22575. this.DIRLIGHT2 = false;
  22576. this.DIRLIGHT3 = false;
  22577. this.SPECULARTERM = false;
  22578. this.SHADOW0 = false;
  22579. this.SHADOW1 = false;
  22580. this.SHADOW2 = false;
  22581. this.SHADOW3 = false;
  22582. this.SHADOWS = false;
  22583. this.SHADOWVSM0 = false;
  22584. this.SHADOWVSM1 = false;
  22585. this.SHADOWVSM2 = false;
  22586. this.SHADOWVSM3 = false;
  22587. this.SHADOWPCF0 = false;
  22588. this.SHADOWPCF1 = false;
  22589. this.SHADOWPCF2 = false;
  22590. this.SHADOWPCF3 = false;
  22591. this.DIFFUSEFRESNEL = false;
  22592. this.OPACITYFRESNEL = false;
  22593. this.REFLECTIONFRESNEL = false;
  22594. this.REFRACTIONFRESNEL = false;
  22595. this.EMISSIVEFRESNEL = false;
  22596. this.FRESNEL = false;
  22597. this.NORMAL = false;
  22598. this.UV1 = false;
  22599. this.UV2 = false;
  22600. this.VERTEXCOLOR = false;
  22601. this.VERTEXALPHA = false;
  22602. this.NUM_BONE_INFLUENCERS = 0;
  22603. this.BonesPerMesh = 0;
  22604. this.INSTANCES = false;
  22605. this.GLOSSINESS = false;
  22606. this.ROUGHNESS = false;
  22607. this.EMISSIVEASILLUMINATION = false;
  22608. this.LINKEMISSIVEWITHDIFFUSE = false;
  22609. this.REFLECTIONFRESNELFROMSPECULAR = false;
  22610. this.LIGHTMAP = false;
  22611. this.USELIGHTMAPASSHADOWMAP = false;
  22612. this.REFLECTIONMAP_3D = false;
  22613. this.REFLECTIONMAP_SPHERICAL = false;
  22614. this.REFLECTIONMAP_PLANAR = false;
  22615. this.REFLECTIONMAP_CUBIC = false;
  22616. this.REFLECTIONMAP_PROJECTION = false;
  22617. this.REFLECTIONMAP_SKYBOX = false;
  22618. this.REFLECTIONMAP_EXPLICIT = false;
  22619. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  22620. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  22621. this.INVERTCUBICMAP = false;
  22622. this.LOGARITHMICDEPTH = false;
  22623. this.REFRACTION = false;
  22624. this.REFRACTIONMAP_3D = false;
  22625. this.REFLECTIONOVERALPHA = false;
  22626. this._keys = Object.keys(this);
  22627. }
  22628. return StandardMaterialDefines;
  22629. })(BABYLON.MaterialDefines);
  22630. var StandardMaterial = (function (_super) {
  22631. __extends(StandardMaterial, _super);
  22632. function StandardMaterial(name, scene) {
  22633. var _this = this;
  22634. _super.call(this, name, scene);
  22635. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  22636. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  22637. this.specularColor = new BABYLON.Color3(1, 1, 1);
  22638. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  22639. this.specularPower = 64;
  22640. this.useAlphaFromDiffuseTexture = false;
  22641. this.useEmissiveAsIllumination = false;
  22642. this.linkEmissiveWithDiffuse = false;
  22643. this.useReflectionFresnelFromSpecular = false;
  22644. this.useSpecularOverAlpha = false;
  22645. this.useReflectionOverAlpha = false;
  22646. this.disableLighting = false;
  22647. this.useParallax = false;
  22648. this.useParallaxOcclusion = false;
  22649. this.parallaxScaleBias = 0.05;
  22650. this.roughness = 0;
  22651. this.indexOfRefraction = 0.98;
  22652. this.invertRefractionY = true;
  22653. this.useLightmapAsShadowmap = false;
  22654. this.useGlossinessFromSpecularMapAlpha = false;
  22655. this._renderTargets = new BABYLON.SmartArray(16);
  22656. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  22657. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  22658. this._defines = new StandardMaterialDefines();
  22659. this._cachedDefines = new StandardMaterialDefines();
  22660. this._cachedDefines.BonesPerMesh = -1;
  22661. this.getRenderTargetTextures = function () {
  22662. _this._renderTargets.reset();
  22663. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  22664. _this._renderTargets.push(_this.reflectionTexture);
  22665. }
  22666. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  22667. _this._renderTargets.push(_this.refractionTexture);
  22668. }
  22669. return _this._renderTargets;
  22670. };
  22671. }
  22672. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  22673. get: function () {
  22674. return this._useLogarithmicDepth;
  22675. },
  22676. set: function (value) {
  22677. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  22678. },
  22679. enumerable: true,
  22680. configurable: true
  22681. });
  22682. StandardMaterial.prototype.needAlphaBlending = function () {
  22683. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  22684. };
  22685. StandardMaterial.prototype.needAlphaTesting = function () {
  22686. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  22687. };
  22688. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  22689. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  22690. };
  22691. StandardMaterial.prototype.getAlphaTestTexture = function () {
  22692. return this.diffuseTexture;
  22693. };
  22694. // Methods
  22695. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  22696. if (!mesh) {
  22697. return true;
  22698. }
  22699. if (this._defines.INSTANCES !== useInstances) {
  22700. return false;
  22701. }
  22702. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  22703. return true;
  22704. }
  22705. return false;
  22706. };
  22707. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  22708. if (this.isFrozen) {
  22709. if (this._wasPreviouslyReady) {
  22710. return true;
  22711. }
  22712. }
  22713. var scene = this.getScene();
  22714. if (!this.checkReadyOnEveryCall) {
  22715. if (this._renderId === scene.getRenderId()) {
  22716. if (this._checkCache(scene, mesh, useInstances)) {
  22717. return true;
  22718. }
  22719. }
  22720. }
  22721. var engine = scene.getEngine();
  22722. var needNormals = false;
  22723. var needUVs = false;
  22724. this._defines.reset();
  22725. // Textures
  22726. if (scene.texturesEnabled) {
  22727. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  22728. if (!this.diffuseTexture.isReady()) {
  22729. return false;
  22730. }
  22731. else {
  22732. needUVs = true;
  22733. this._defines.DIFFUSE = true;
  22734. }
  22735. }
  22736. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  22737. if (!this.ambientTexture.isReady()) {
  22738. return false;
  22739. }
  22740. else {
  22741. needUVs = true;
  22742. this._defines.AMBIENT = true;
  22743. }
  22744. }
  22745. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  22746. if (!this.opacityTexture.isReady()) {
  22747. return false;
  22748. }
  22749. else {
  22750. needUVs = true;
  22751. this._defines.OPACITY = true;
  22752. if (this.opacityTexture.getAlphaFromRGB) {
  22753. this._defines.OPACITYRGB = true;
  22754. }
  22755. }
  22756. }
  22757. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  22758. if (!this.reflectionTexture.isReady()) {
  22759. return false;
  22760. }
  22761. else {
  22762. needNormals = true;
  22763. this._defines.REFLECTION = true;
  22764. if (this.roughness > 0) {
  22765. this._defines.ROUGHNESS = true;
  22766. }
  22767. if (this.useReflectionOverAlpha) {
  22768. this._defines.REFLECTIONOVERALPHA = true;
  22769. }
  22770. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  22771. this._defines.INVERTCUBICMAP = true;
  22772. }
  22773. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  22774. switch (this.reflectionTexture.coordinatesMode) {
  22775. case BABYLON.Texture.CUBIC_MODE:
  22776. case BABYLON.Texture.INVCUBIC_MODE:
  22777. this._defines.REFLECTIONMAP_CUBIC = true;
  22778. break;
  22779. case BABYLON.Texture.EXPLICIT_MODE:
  22780. this._defines.REFLECTIONMAP_EXPLICIT = true;
  22781. break;
  22782. case BABYLON.Texture.PLANAR_MODE:
  22783. this._defines.REFLECTIONMAP_PLANAR = true;
  22784. break;
  22785. case BABYLON.Texture.PROJECTION_MODE:
  22786. this._defines.REFLECTIONMAP_PROJECTION = true;
  22787. break;
  22788. case BABYLON.Texture.SKYBOX_MODE:
  22789. this._defines.REFLECTIONMAP_SKYBOX = true;
  22790. break;
  22791. case BABYLON.Texture.SPHERICAL_MODE:
  22792. this._defines.REFLECTIONMAP_SPHERICAL = true;
  22793. break;
  22794. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  22795. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  22796. break;
  22797. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  22798. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  22799. break;
  22800. }
  22801. }
  22802. }
  22803. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  22804. if (!this.emissiveTexture.isReady()) {
  22805. return false;
  22806. }
  22807. else {
  22808. needUVs = true;
  22809. this._defines.EMISSIVE = true;
  22810. }
  22811. }
  22812. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  22813. if (!this.lightmapTexture.isReady()) {
  22814. return false;
  22815. }
  22816. else {
  22817. needUVs = true;
  22818. this._defines.LIGHTMAP = true;
  22819. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  22820. }
  22821. }
  22822. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  22823. if (!this.specularTexture.isReady()) {
  22824. return false;
  22825. }
  22826. else {
  22827. needUVs = true;
  22828. this._defines.SPECULAR = true;
  22829. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  22830. }
  22831. }
  22832. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  22833. if (!this.bumpTexture.isReady()) {
  22834. return false;
  22835. }
  22836. else {
  22837. needUVs = true;
  22838. this._defines.BUMP = true;
  22839. if (this.useParallax) {
  22840. this._defines.PARALLAX = true;
  22841. if (this.useParallaxOcclusion) {
  22842. this._defines.PARALLAXOCCLUSION = true;
  22843. }
  22844. }
  22845. }
  22846. }
  22847. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  22848. if (!this.refractionTexture.isReady()) {
  22849. return false;
  22850. }
  22851. else {
  22852. needUVs = true;
  22853. this._defines.REFRACTION = true;
  22854. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  22855. }
  22856. }
  22857. }
  22858. // Effect
  22859. if (scene.clipPlane) {
  22860. this._defines.CLIPPLANE = true;
  22861. }
  22862. if (engine.getAlphaTesting()) {
  22863. this._defines.ALPHATEST = true;
  22864. }
  22865. if (this._shouldUseAlphaFromDiffuseTexture()) {
  22866. this._defines.ALPHAFROMDIFFUSE = true;
  22867. }
  22868. if (this.useEmissiveAsIllumination) {
  22869. this._defines.EMISSIVEASILLUMINATION = true;
  22870. }
  22871. if (this.linkEmissiveWithDiffuse) {
  22872. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  22873. }
  22874. if (this.useLogarithmicDepth) {
  22875. this._defines.LOGARITHMICDEPTH = true;
  22876. }
  22877. // Point size
  22878. if (this.pointsCloud || scene.forcePointsCloud) {
  22879. this._defines.POINTSIZE = true;
  22880. }
  22881. // Fog
  22882. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  22883. this._defines.FOG = true;
  22884. }
  22885. if (scene.lightsEnabled && !this.disableLighting) {
  22886. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines);
  22887. }
  22888. if (StandardMaterial.FresnelEnabled) {
  22889. // Fresnel
  22890. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  22891. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  22892. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  22893. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  22894. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  22895. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  22896. this._defines.DIFFUSEFRESNEL = true;
  22897. }
  22898. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  22899. this._defines.OPACITYFRESNEL = true;
  22900. }
  22901. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  22902. this._defines.REFLECTIONFRESNEL = true;
  22903. if (this.useReflectionFresnelFromSpecular) {
  22904. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  22905. }
  22906. }
  22907. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  22908. this._defines.REFRACTIONFRESNEL = true;
  22909. }
  22910. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  22911. this._defines.EMISSIVEFRESNEL = true;
  22912. }
  22913. needNormals = true;
  22914. this._defines.FRESNEL = true;
  22915. }
  22916. }
  22917. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  22918. this._defines.SPECULAROVERALPHA = true;
  22919. }
  22920. // Attribs
  22921. if (mesh) {
  22922. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22923. this._defines.NORMAL = true;
  22924. }
  22925. if (needUVs) {
  22926. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22927. this._defines.UV1 = true;
  22928. }
  22929. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22930. this._defines.UV2 = true;
  22931. }
  22932. }
  22933. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22934. this._defines.VERTEXCOLOR = true;
  22935. if (mesh.hasVertexAlpha) {
  22936. this._defines.VERTEXALPHA = true;
  22937. }
  22938. }
  22939. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  22940. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  22941. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  22942. }
  22943. // Instances
  22944. if (useInstances) {
  22945. this._defines.INSTANCES = true;
  22946. }
  22947. }
  22948. // Get correct effect
  22949. if (!this._defines.isEqual(this._cachedDefines)) {
  22950. this._defines.cloneTo(this._cachedDefines);
  22951. scene.resetCachedMaterial();
  22952. // Fallbacks
  22953. var fallbacks = new BABYLON.EffectFallbacks();
  22954. if (this._defines.REFLECTION) {
  22955. fallbacks.addFallback(0, "REFLECTION");
  22956. }
  22957. if (this._defines.SPECULAR) {
  22958. fallbacks.addFallback(0, "SPECULAR");
  22959. }
  22960. if (this._defines.BUMP) {
  22961. fallbacks.addFallback(0, "BUMP");
  22962. }
  22963. if (this._defines.PARALLAX) {
  22964. fallbacks.addFallback(1, "PARALLAX");
  22965. }
  22966. if (this._defines.PARALLAXOCCLUSION) {
  22967. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  22968. }
  22969. if (this._defines.SPECULAROVERALPHA) {
  22970. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  22971. }
  22972. if (this._defines.FOG) {
  22973. fallbacks.addFallback(1, "FOG");
  22974. }
  22975. if (this._defines.POINTSIZE) {
  22976. fallbacks.addFallback(0, "POINTSIZE");
  22977. }
  22978. if (this._defines.LOGARITHMICDEPTH) {
  22979. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  22980. }
  22981. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  22982. if (this._defines.SPECULARTERM) {
  22983. fallbacks.addFallback(0, "SPECULARTERM");
  22984. }
  22985. if (this._defines.DIFFUSEFRESNEL) {
  22986. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  22987. }
  22988. if (this._defines.OPACITYFRESNEL) {
  22989. fallbacks.addFallback(2, "OPACITYFRESNEL");
  22990. }
  22991. if (this._defines.REFLECTIONFRESNEL) {
  22992. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  22993. }
  22994. if (this._defines.EMISSIVEFRESNEL) {
  22995. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  22996. }
  22997. if (this._defines.FRESNEL) {
  22998. fallbacks.addFallback(4, "FRESNEL");
  22999. }
  23000. //Attributes
  23001. var attribs = [BABYLON.VertexBuffer.PositionKind];
  23002. if (this._defines.NORMAL) {
  23003. attribs.push(BABYLON.VertexBuffer.NormalKind);
  23004. }
  23005. if (this._defines.UV1) {
  23006. attribs.push(BABYLON.VertexBuffer.UVKind);
  23007. }
  23008. if (this._defines.UV2) {
  23009. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  23010. }
  23011. if (this._defines.VERTEXCOLOR) {
  23012. attribs.push(BABYLON.VertexBuffer.ColorKind);
  23013. }
  23014. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  23015. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  23016. // Legacy browser patch
  23017. var shaderName = "default";
  23018. if (!scene.getEngine().getCaps().standardDerivatives) {
  23019. shaderName = "legacydefault";
  23020. }
  23021. var join = this._defines.toString();
  23022. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  23023. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  23024. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  23025. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  23026. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  23027. "vFogInfos", "vFogColor", "pointSize",
  23028. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  23029. "mBones",
  23030. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  23031. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  23032. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  23033. "logarithmicDepthConstant"
  23034. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  23035. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  23036. ], join, fallbacks, this.onCompiled, this.onError);
  23037. }
  23038. if (!this._effect.isReady()) {
  23039. return false;
  23040. }
  23041. this._renderId = scene.getRenderId();
  23042. this._wasPreviouslyReady = true;
  23043. if (mesh) {
  23044. if (!mesh._materialDefines) {
  23045. mesh._materialDefines = new StandardMaterialDefines();
  23046. }
  23047. this._defines.cloneTo(mesh._materialDefines);
  23048. }
  23049. return true;
  23050. };
  23051. StandardMaterial.prototype.unbind = function () {
  23052. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  23053. this._effect.setTexture("reflection2DSampler", null);
  23054. }
  23055. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  23056. this._effect.setTexture("refraction2DSampler", null);
  23057. }
  23058. _super.prototype.unbind.call(this);
  23059. };
  23060. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  23061. this._effect.setMatrix("world", world);
  23062. };
  23063. StandardMaterial.prototype.bind = function (world, mesh) {
  23064. var scene = this.getScene();
  23065. // Matrices
  23066. this.bindOnlyWorldMatrix(world);
  23067. // Bones
  23068. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  23069. if (scene.getCachedMaterial() !== this) {
  23070. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  23071. if (StandardMaterial.FresnelEnabled) {
  23072. // Fresnel
  23073. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  23074. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  23075. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  23076. }
  23077. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  23078. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  23079. }
  23080. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  23081. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  23082. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  23083. }
  23084. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  23085. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  23086. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  23087. }
  23088. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  23089. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  23090. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  23091. }
  23092. }
  23093. // Textures
  23094. if (scene.texturesEnabled) {
  23095. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  23096. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  23097. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  23098. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  23099. }
  23100. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  23101. this._effect.setTexture("ambientSampler", this.ambientTexture);
  23102. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  23103. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  23104. }
  23105. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  23106. this._effect.setTexture("opacitySampler", this.opacityTexture);
  23107. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  23108. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  23109. }
  23110. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  23111. if (this.reflectionTexture.isCube) {
  23112. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  23113. }
  23114. else {
  23115. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  23116. }
  23117. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  23118. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  23119. }
  23120. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  23121. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  23122. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  23123. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  23124. }
  23125. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  23126. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  23127. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  23128. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  23129. }
  23130. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  23131. this._effect.setTexture("specularSampler", this.specularTexture);
  23132. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  23133. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  23134. }
  23135. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  23136. this._effect.setTexture("bumpSampler", this.bumpTexture);
  23137. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  23138. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  23139. }
  23140. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  23141. var depth = 1.0;
  23142. if (this.refractionTexture.isCube) {
  23143. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  23144. }
  23145. else {
  23146. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  23147. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  23148. if (this.refractionTexture.depth) {
  23149. depth = this.refractionTexture.depth;
  23150. }
  23151. }
  23152. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  23153. }
  23154. }
  23155. // Clip plane
  23156. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  23157. // Point size
  23158. if (this.pointsCloud) {
  23159. this._effect.setFloat("pointSize", this.pointSize);
  23160. }
  23161. // Colors
  23162. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  23163. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  23164. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  23165. if (this._defines.SPECULARTERM) {
  23166. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  23167. }
  23168. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  23169. }
  23170. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  23171. // Diffuse
  23172. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  23173. // Lights
  23174. if (scene.lightsEnabled && !this.disableLighting) {
  23175. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines);
  23176. }
  23177. // View
  23178. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  23179. this._effect.setMatrix("view", scene.getViewMatrix());
  23180. }
  23181. // Fog
  23182. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  23183. // Log. depth
  23184. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  23185. }
  23186. _super.prototype.bind.call(this, world, mesh);
  23187. };
  23188. StandardMaterial.prototype.getAnimatables = function () {
  23189. var results = [];
  23190. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  23191. results.push(this.diffuseTexture);
  23192. }
  23193. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  23194. results.push(this.ambientTexture);
  23195. }
  23196. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  23197. results.push(this.opacityTexture);
  23198. }
  23199. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  23200. results.push(this.reflectionTexture);
  23201. }
  23202. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  23203. results.push(this.emissiveTexture);
  23204. }
  23205. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  23206. results.push(this.specularTexture);
  23207. }
  23208. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  23209. results.push(this.bumpTexture);
  23210. }
  23211. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  23212. results.push(this.lightmapTexture);
  23213. }
  23214. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  23215. results.push(this.refractionTexture);
  23216. }
  23217. return results;
  23218. };
  23219. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  23220. if (forceDisposeTextures) {
  23221. if (this.diffuseTexture) {
  23222. this.diffuseTexture.dispose();
  23223. }
  23224. if (this.ambientTexture) {
  23225. this.ambientTexture.dispose();
  23226. }
  23227. if (this.opacityTexture) {
  23228. this.opacityTexture.dispose();
  23229. }
  23230. if (this.reflectionTexture) {
  23231. this.reflectionTexture.dispose();
  23232. }
  23233. if (this.emissiveTexture) {
  23234. this.emissiveTexture.dispose();
  23235. }
  23236. if (this.specularTexture) {
  23237. this.specularTexture.dispose();
  23238. }
  23239. if (this.bumpTexture) {
  23240. this.bumpTexture.dispose();
  23241. }
  23242. if (this.lightmapTexture) {
  23243. this.lightmapTexture.dispose();
  23244. }
  23245. if (this.refractionTexture) {
  23246. this.refractionTexture.dispose();
  23247. }
  23248. }
  23249. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  23250. };
  23251. StandardMaterial.prototype.clone = function (name) {
  23252. var _this = this;
  23253. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  23254. };
  23255. StandardMaterial.prototype.serialize = function () {
  23256. return BABYLON.SerializationHelper.Serialize(this);
  23257. };
  23258. // Statics
  23259. StandardMaterial.Parse = function (source, scene, rootUrl) {
  23260. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  23261. };
  23262. // Flags used to enable or disable a type of texture for all Standard Materials
  23263. StandardMaterial.DiffuseTextureEnabled = true;
  23264. StandardMaterial.AmbientTextureEnabled = true;
  23265. StandardMaterial.OpacityTextureEnabled = true;
  23266. StandardMaterial.ReflectionTextureEnabled = true;
  23267. StandardMaterial.EmissiveTextureEnabled = true;
  23268. StandardMaterial.SpecularTextureEnabled = true;
  23269. StandardMaterial.BumpTextureEnabled = true;
  23270. StandardMaterial.FresnelEnabled = true;
  23271. StandardMaterial.LightmapTextureEnabled = true;
  23272. StandardMaterial.RefractionTextureEnabled = true;
  23273. __decorate([
  23274. BABYLON.serializeAsTexture()
  23275. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  23276. __decorate([
  23277. BABYLON.serializeAsTexture()
  23278. ], StandardMaterial.prototype, "ambientTexture", void 0);
  23279. __decorate([
  23280. BABYLON.serializeAsTexture()
  23281. ], StandardMaterial.prototype, "opacityTexture", void 0);
  23282. __decorate([
  23283. BABYLON.serializeAsTexture()
  23284. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  23285. __decorate([
  23286. BABYLON.serializeAsTexture()
  23287. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  23288. __decorate([
  23289. BABYLON.serializeAsTexture()
  23290. ], StandardMaterial.prototype, "specularTexture", void 0);
  23291. __decorate([
  23292. BABYLON.serializeAsTexture()
  23293. ], StandardMaterial.prototype, "bumpTexture", void 0);
  23294. __decorate([
  23295. BABYLON.serializeAsTexture()
  23296. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  23297. __decorate([
  23298. BABYLON.serializeAsTexture()
  23299. ], StandardMaterial.prototype, "refractionTexture", void 0);
  23300. __decorate([
  23301. BABYLON.serializeAsColor3("ambient")
  23302. ], StandardMaterial.prototype, "ambientColor", void 0);
  23303. __decorate([
  23304. BABYLON.serializeAsColor3("diffuse")
  23305. ], StandardMaterial.prototype, "diffuseColor", void 0);
  23306. __decorate([
  23307. BABYLON.serializeAsColor3("specular")
  23308. ], StandardMaterial.prototype, "specularColor", void 0);
  23309. __decorate([
  23310. BABYLON.serializeAsColor3("emissive")
  23311. ], StandardMaterial.prototype, "emissiveColor", void 0);
  23312. __decorate([
  23313. BABYLON.serialize()
  23314. ], StandardMaterial.prototype, "specularPower", void 0);
  23315. __decorate([
  23316. BABYLON.serialize()
  23317. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  23318. __decorate([
  23319. BABYLON.serialize()
  23320. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  23321. __decorate([
  23322. BABYLON.serialize()
  23323. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  23324. __decorate([
  23325. BABYLON.serialize()
  23326. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  23327. __decorate([
  23328. BABYLON.serialize()
  23329. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  23330. __decorate([
  23331. BABYLON.serialize()
  23332. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  23333. __decorate([
  23334. BABYLON.serialize()
  23335. ], StandardMaterial.prototype, "disableLighting", void 0);
  23336. __decorate([
  23337. BABYLON.serialize()
  23338. ], StandardMaterial.prototype, "useParallax", void 0);
  23339. __decorate([
  23340. BABYLON.serialize()
  23341. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  23342. __decorate([
  23343. BABYLON.serialize()
  23344. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  23345. __decorate([
  23346. BABYLON.serialize()
  23347. ], StandardMaterial.prototype, "roughness", void 0);
  23348. __decorate([
  23349. BABYLON.serialize()
  23350. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  23351. __decorate([
  23352. BABYLON.serialize()
  23353. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  23354. __decorate([
  23355. BABYLON.serialize()
  23356. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  23357. __decorate([
  23358. BABYLON.serializeAsFresnelParameters()
  23359. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  23360. __decorate([
  23361. BABYLON.serializeAsFresnelParameters()
  23362. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  23363. __decorate([
  23364. BABYLON.serializeAsFresnelParameters()
  23365. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  23366. __decorate([
  23367. BABYLON.serializeAsFresnelParameters()
  23368. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  23369. __decorate([
  23370. BABYLON.serializeAsFresnelParameters()
  23371. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  23372. __decorate([
  23373. BABYLON.serialize()
  23374. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  23375. __decorate([
  23376. BABYLON.serialize()
  23377. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  23378. return StandardMaterial;
  23379. })(BABYLON.Material);
  23380. BABYLON.StandardMaterial = StandardMaterial;
  23381. })(BABYLON || (BABYLON = {}));
  23382. var BABYLON;
  23383. (function (BABYLON) {
  23384. var MultiMaterial = (function (_super) {
  23385. __extends(MultiMaterial, _super);
  23386. function MultiMaterial(name, scene) {
  23387. _super.call(this, name, scene, true);
  23388. this.subMaterials = new Array();
  23389. scene.multiMaterials.push(this);
  23390. }
  23391. // Properties
  23392. MultiMaterial.prototype.getSubMaterial = function (index) {
  23393. if (index < 0 || index >= this.subMaterials.length) {
  23394. return this.getScene().defaultMaterial;
  23395. }
  23396. return this.subMaterials[index];
  23397. };
  23398. // Methods
  23399. MultiMaterial.prototype.isReady = function (mesh) {
  23400. for (var index = 0; index < this.subMaterials.length; index++) {
  23401. var subMaterial = this.subMaterials[index];
  23402. if (subMaterial) {
  23403. if (!this.subMaterials[index].isReady(mesh)) {
  23404. return false;
  23405. }
  23406. }
  23407. }
  23408. return true;
  23409. };
  23410. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  23411. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  23412. for (var index = 0; index < this.subMaterials.length; index++) {
  23413. var subMaterial = null;
  23414. if (cloneChildren) {
  23415. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  23416. }
  23417. else {
  23418. subMaterial = this.subMaterials[index];
  23419. }
  23420. newMultiMaterial.subMaterials.push(subMaterial);
  23421. }
  23422. return newMultiMaterial;
  23423. };
  23424. MultiMaterial.prototype.serialize = function () {
  23425. var serializationObject = {};
  23426. serializationObject.name = this.name;
  23427. serializationObject.id = this.id;
  23428. serializationObject.tags = BABYLON.Tags.GetTags(this);
  23429. serializationObject.materials = [];
  23430. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  23431. var subMat = this.subMaterials[matIndex];
  23432. if (subMat) {
  23433. serializationObject.materials.push(subMat.id);
  23434. }
  23435. else {
  23436. serializationObject.materials.push(null);
  23437. }
  23438. }
  23439. return serializationObject;
  23440. };
  23441. return MultiMaterial;
  23442. })(BABYLON.Material);
  23443. BABYLON.MultiMaterial = MultiMaterial;
  23444. })(BABYLON || (BABYLON = {}));
  23445. var BABYLON;
  23446. (function (BABYLON) {
  23447. var SceneLoader = (function () {
  23448. function SceneLoader() {
  23449. }
  23450. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  23451. get: function () {
  23452. return 0;
  23453. },
  23454. enumerable: true,
  23455. configurable: true
  23456. });
  23457. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  23458. get: function () {
  23459. return 1;
  23460. },
  23461. enumerable: true,
  23462. configurable: true
  23463. });
  23464. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  23465. get: function () {
  23466. return 2;
  23467. },
  23468. enumerable: true,
  23469. configurable: true
  23470. });
  23471. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  23472. get: function () {
  23473. return 3;
  23474. },
  23475. enumerable: true,
  23476. configurable: true
  23477. });
  23478. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  23479. get: function () {
  23480. return SceneLoader._ForceFullSceneLoadingForIncremental;
  23481. },
  23482. set: function (value) {
  23483. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  23484. },
  23485. enumerable: true,
  23486. configurable: true
  23487. });
  23488. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  23489. get: function () {
  23490. return SceneLoader._ShowLoadingScreen;
  23491. },
  23492. set: function (value) {
  23493. SceneLoader._ShowLoadingScreen = value;
  23494. },
  23495. enumerable: true,
  23496. configurable: true
  23497. });
  23498. Object.defineProperty(SceneLoader, "loggingLevel", {
  23499. get: function () {
  23500. return SceneLoader._loggingLevel;
  23501. },
  23502. set: function (value) {
  23503. SceneLoader._loggingLevel = value;
  23504. },
  23505. enumerable: true,
  23506. configurable: true
  23507. });
  23508. SceneLoader._getPluginForFilename = function (sceneFilename) {
  23509. var dotPosition = sceneFilename.lastIndexOf(".");
  23510. var queryStringPosition = sceneFilename.indexOf("?");
  23511. if (queryStringPosition === -1) {
  23512. queryStringPosition = sceneFilename.length;
  23513. }
  23514. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  23515. for (var index = 0; index < this._registeredPlugins.length; index++) {
  23516. var plugin = this._registeredPlugins[index];
  23517. if (plugin.extensions.indexOf(extension) !== -1) {
  23518. return plugin;
  23519. }
  23520. }
  23521. return this._registeredPlugins[this._registeredPlugins.length - 1];
  23522. };
  23523. // Public functions
  23524. SceneLoader.GetPluginForExtension = function (extension) {
  23525. for (var index = 0; index < this._registeredPlugins.length; index++) {
  23526. var plugin = this._registeredPlugins[index];
  23527. if (plugin.extensions.indexOf(extension) !== -1) {
  23528. return plugin;
  23529. }
  23530. }
  23531. return null;
  23532. };
  23533. SceneLoader.RegisterPlugin = function (plugin) {
  23534. plugin.extensions = plugin.extensions.toLowerCase();
  23535. SceneLoader._registeredPlugins.push(plugin);
  23536. };
  23537. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  23538. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  23539. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  23540. return;
  23541. }
  23542. var loadingToken = {};
  23543. scene._addPendingData(loadingToken);
  23544. var manifestChecked = function (success) {
  23545. scene.database = database;
  23546. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  23547. var importMeshFromData = function (data) {
  23548. var meshes = [];
  23549. var particleSystems = [];
  23550. var skeletons = [];
  23551. try {
  23552. if (plugin.importMesh) {
  23553. var syncedPlugin = plugin;
  23554. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  23555. if (onerror) {
  23556. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  23557. }
  23558. scene._removePendingData(loadingToken);
  23559. return;
  23560. }
  23561. if (onsuccess) {
  23562. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  23563. onsuccess(meshes, particleSystems, skeletons);
  23564. scene._removePendingData(loadingToken);
  23565. }
  23566. }
  23567. else {
  23568. var asyncedPlugin = plugin;
  23569. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  23570. if (onsuccess) {
  23571. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  23572. onsuccess(meshes, particleSystems, skeletons);
  23573. scene._removePendingData(loadingToken);
  23574. }
  23575. }, function () {
  23576. if (onerror) {
  23577. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  23578. }
  23579. scene._removePendingData(loadingToken);
  23580. });
  23581. }
  23582. }
  23583. catch (e) {
  23584. if (onerror) {
  23585. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  23586. }
  23587. scene._removePendingData(loadingToken);
  23588. }
  23589. };
  23590. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  23591. // Direct load
  23592. importMeshFromData(sceneFilename.substr(5));
  23593. return;
  23594. }
  23595. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  23596. importMeshFromData(data);
  23597. }, progressCallBack, database);
  23598. };
  23599. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  23600. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  23601. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  23602. }
  23603. else {
  23604. // If the scene is a data stream or offline support is not enabled, it's a direct load
  23605. manifestChecked(true);
  23606. }
  23607. };
  23608. /**
  23609. * Load a scene
  23610. * @param rootUrl a string that defines the root url for scene and resources
  23611. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  23612. * @param engine is the instance of BABYLON.Engine to use to create the scene
  23613. */
  23614. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  23615. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  23616. };
  23617. /**
  23618. * Append a scene
  23619. * @param rootUrl a string that defines the root url for scene and resources
  23620. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  23621. * @param scene is the instance of BABYLON.Scene to append to
  23622. */
  23623. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  23624. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  23625. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  23626. return;
  23627. }
  23628. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  23629. var database;
  23630. var loadingToken = {};
  23631. scene._addPendingData(loadingToken);
  23632. if (SceneLoader.ShowLoadingScreen) {
  23633. scene.getEngine().displayLoadingUI();
  23634. }
  23635. var loadSceneFromData = function (data) {
  23636. scene.database = database;
  23637. if (plugin.load) {
  23638. var syncedPlugin = plugin;
  23639. if (!syncedPlugin.load(scene, data, rootUrl)) {
  23640. if (onerror) {
  23641. onerror(scene);
  23642. }
  23643. scene._removePendingData(loadingToken);
  23644. scene.getEngine().hideLoadingUI();
  23645. return;
  23646. }
  23647. if (onsuccess) {
  23648. onsuccess(scene);
  23649. }
  23650. scene._removePendingData(loadingToken);
  23651. }
  23652. else {
  23653. var asyncedPlugin = plugin;
  23654. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  23655. if (onsuccess) {
  23656. onsuccess(scene);
  23657. }
  23658. }, function () {
  23659. if (onerror) {
  23660. onerror(scene);
  23661. }
  23662. scene._removePendingData(loadingToken);
  23663. scene.getEngine().hideLoadingUI();
  23664. });
  23665. }
  23666. if (SceneLoader.ShowLoadingScreen) {
  23667. scene.executeWhenReady(function () {
  23668. scene.getEngine().hideLoadingUI();
  23669. });
  23670. }
  23671. };
  23672. var manifestChecked = function (success) {
  23673. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  23674. };
  23675. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  23676. // Direct load
  23677. loadSceneFromData(sceneFilename.substr(5));
  23678. return;
  23679. }
  23680. if (rootUrl.indexOf("file:") === -1) {
  23681. if (scene.getEngine().enableOfflineSupport) {
  23682. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  23683. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  23684. }
  23685. else {
  23686. manifestChecked(true);
  23687. }
  23688. }
  23689. else {
  23690. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  23691. }
  23692. };
  23693. // Flags
  23694. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  23695. SceneLoader._ShowLoadingScreen = true;
  23696. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  23697. // Members
  23698. SceneLoader._registeredPlugins = new Array();
  23699. return SceneLoader;
  23700. })();
  23701. BABYLON.SceneLoader = SceneLoader;
  23702. ;
  23703. })(BABYLON || (BABYLON = {}));
  23704. var BABYLON;
  23705. (function (BABYLON) {
  23706. var Internals;
  23707. (function (Internals) {
  23708. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  23709. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  23710. var parsedMaterial = parsedData.materials[index];
  23711. if (parsedMaterial.id === id) {
  23712. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  23713. }
  23714. }
  23715. return null;
  23716. };
  23717. var isDescendantOf = function (mesh, names, hierarchyIds) {
  23718. names = (names instanceof Array) ? names : [names];
  23719. for (var i in names) {
  23720. if (mesh.name === names[i]) {
  23721. hierarchyIds.push(mesh.id);
  23722. return true;
  23723. }
  23724. }
  23725. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  23726. hierarchyIds.push(mesh.id);
  23727. return true;
  23728. }
  23729. return false;
  23730. };
  23731. var logOperation = function (operation, producer) {
  23732. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  23733. };
  23734. BABYLON.SceneLoader.RegisterPlugin({
  23735. extensions: ".babylon",
  23736. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  23737. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  23738. // when SceneLoader.debugLogging = true (default), or exception encountered.
  23739. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  23740. // and avoid problems with multiple concurrent .babylon loads.
  23741. var log = "importMesh has failed JSON parse";
  23742. try {
  23743. var parsedData = JSON.parse(data);
  23744. log = "";
  23745. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  23746. var loadedSkeletonsIds = [];
  23747. var loadedMaterialsIds = [];
  23748. var hierarchyIds = [];
  23749. var index;
  23750. var cache;
  23751. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  23752. var parsedMesh = parsedData.meshes[index];
  23753. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  23754. if (meshesNames instanceof Array) {
  23755. // Remove found mesh name from list.
  23756. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  23757. }
  23758. //Geometry?
  23759. if (parsedMesh.geometryId) {
  23760. //does the file contain geometries?
  23761. if (parsedData.geometries) {
  23762. //find the correct geometry and add it to the scene
  23763. var found = false;
  23764. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  23765. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  23766. return;
  23767. }
  23768. else {
  23769. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  23770. if (parsedGeometryData.id === parsedMesh.geometryId) {
  23771. switch (geometryType) {
  23772. case "boxes":
  23773. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  23774. break;
  23775. case "spheres":
  23776. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  23777. break;
  23778. case "cylinders":
  23779. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  23780. break;
  23781. case "toruses":
  23782. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  23783. break;
  23784. case "grounds":
  23785. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  23786. break;
  23787. case "planes":
  23788. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  23789. break;
  23790. case "torusKnots":
  23791. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  23792. break;
  23793. case "vertexData":
  23794. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  23795. break;
  23796. }
  23797. found = true;
  23798. }
  23799. });
  23800. }
  23801. });
  23802. if (!found) {
  23803. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  23804. }
  23805. }
  23806. }
  23807. // Material ?
  23808. if (parsedMesh.materialId) {
  23809. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  23810. if (!materialFound && parsedData.multiMaterials) {
  23811. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  23812. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  23813. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  23814. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  23815. var subMatId = parsedMultiMaterial.materials[matIndex];
  23816. loadedMaterialsIds.push(subMatId);
  23817. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  23818. log += "\n\tMaterial " + mat.toString(fullDetails);
  23819. }
  23820. loadedMaterialsIds.push(parsedMultiMaterial.id);
  23821. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  23822. materialFound = true;
  23823. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  23824. break;
  23825. }
  23826. }
  23827. }
  23828. if (!materialFound) {
  23829. loadedMaterialsIds.push(parsedMesh.materialId);
  23830. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  23831. if (!mat) {
  23832. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  23833. }
  23834. else {
  23835. log += "\n\tMaterial " + mat.toString(fullDetails);
  23836. }
  23837. }
  23838. }
  23839. // Skeleton ?
  23840. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  23841. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  23842. if (!skeletonAlreadyLoaded) {
  23843. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  23844. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  23845. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  23846. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  23847. skeletons.push(skeleton);
  23848. loadedSkeletonsIds.push(parsedSkeleton.id);
  23849. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  23850. }
  23851. }
  23852. }
  23853. }
  23854. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  23855. meshes.push(mesh);
  23856. log += "\n\tMesh " + mesh.toString(fullDetails);
  23857. }
  23858. }
  23859. // Connecting parents
  23860. var currentMesh;
  23861. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  23862. currentMesh = scene.meshes[index];
  23863. if (currentMesh._waitingParentId) {
  23864. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  23865. currentMesh._waitingParentId = undefined;
  23866. }
  23867. }
  23868. // freeze and compute world matrix application
  23869. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  23870. currentMesh = scene.meshes[index];
  23871. if (currentMesh._waitingFreezeWorldMatrix) {
  23872. currentMesh.freezeWorldMatrix();
  23873. currentMesh._waitingFreezeWorldMatrix = undefined;
  23874. }
  23875. else {
  23876. currentMesh.computeWorldMatrix(true);
  23877. }
  23878. }
  23879. // Particles
  23880. if (parsedData.particleSystems) {
  23881. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  23882. var parsedParticleSystem = parsedData.particleSystems[index];
  23883. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  23884. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  23885. }
  23886. }
  23887. }
  23888. return true;
  23889. }
  23890. catch (err) {
  23891. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + log);
  23892. log = null;
  23893. throw err;
  23894. }
  23895. finally {
  23896. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  23897. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  23898. }
  23899. }
  23900. },
  23901. load: function (scene, data, rootUrl) {
  23902. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  23903. // when SceneLoader.debugLogging = true (default), or exception encountered.
  23904. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  23905. // and avoid problems with multiple concurrent .babylon loads.
  23906. var log = "importScene has failed JSON parse";
  23907. try {
  23908. var parsedData = JSON.parse(data);
  23909. log = "";
  23910. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  23911. // Scene
  23912. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  23913. scene.autoClear = parsedData.autoClear;
  23914. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  23915. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  23916. if (parsedData.gravity) {
  23917. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  23918. }
  23919. // Fog
  23920. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  23921. scene.fogMode = parsedData.fogMode;
  23922. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  23923. scene.fogStart = parsedData.fogStart;
  23924. scene.fogEnd = parsedData.fogEnd;
  23925. scene.fogDensity = parsedData.fogDensity;
  23926. log += "\tFog mode for scene: ";
  23927. switch (scene.fogMode) {
  23928. // getters not compiling, so using hardcoded
  23929. case 1:
  23930. log += "exp\n";
  23931. break;
  23932. case 2:
  23933. log += "exp2\n";
  23934. break;
  23935. case 3:
  23936. log += "linear\n";
  23937. break;
  23938. }
  23939. }
  23940. //Physics
  23941. if (parsedData.physicsEnabled) {
  23942. var physicsPlugin;
  23943. if (parsedData.physicsEngine === "cannon") {
  23944. physicsPlugin = new BABYLON.CannonJSPlugin();
  23945. }
  23946. else if (parsedData.physicsEngine === "oimo") {
  23947. physicsPlugin = new BABYLON.OimoJSPlugin();
  23948. }
  23949. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  23950. //else - default engine, which is currently oimo
  23951. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  23952. scene.enablePhysics(physicsGravity, physicsPlugin);
  23953. }
  23954. //collisions, if defined. otherwise, default is true
  23955. if (parsedData.collisionsEnabled != undefined) {
  23956. scene.collisionsEnabled = parsedData.collisionsEnabled;
  23957. }
  23958. scene.workerCollisions = !!parsedData.workerCollisions;
  23959. var index;
  23960. var cache;
  23961. // Lights
  23962. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  23963. var parsedLight = parsedData.lights[index];
  23964. var light = BABYLON.Light.Parse(parsedLight, scene);
  23965. log += (index === 0 ? "\n\tLights:" : "");
  23966. log += "\n\t\t" + light.toString(fullDetails);
  23967. }
  23968. // Animations
  23969. if (parsedData.animations) {
  23970. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  23971. var parsedAnimation = parsedData.animations[index];
  23972. var animation = BABYLON.Animation.Parse(parsedAnimation);
  23973. scene.animations.push(animation);
  23974. log += (index === 0 ? "\n\tAnimations:" : "");
  23975. log += "\n\t\t" + animation.toString(fullDetails);
  23976. }
  23977. }
  23978. // Materials
  23979. if (parsedData.materials) {
  23980. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  23981. var parsedMaterial = parsedData.materials[index];
  23982. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  23983. log += (index === 0 ? "\n\tMaterials:" : "");
  23984. log += "\n\t\t" + mat.toString(fullDetails);
  23985. }
  23986. }
  23987. if (parsedData.multiMaterials) {
  23988. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  23989. var parsedMultiMaterial = parsedData.multiMaterials[index];
  23990. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  23991. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  23992. log += "\n\t\t" + mmat.toString(fullDetails);
  23993. }
  23994. }
  23995. // Skeletons
  23996. if (parsedData.skeletons) {
  23997. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  23998. var parsedSkeleton = parsedData.skeletons[index];
  23999. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  24000. log += (index === 0 ? "\n\tSkeletons:" : "");
  24001. log += "\n\t\t" + skeleton.toString(fullDetails);
  24002. }
  24003. }
  24004. // Geometries
  24005. var geometries = parsedData.geometries;
  24006. if (geometries) {
  24007. // Boxes
  24008. var boxes = geometries.boxes;
  24009. if (boxes) {
  24010. for (index = 0, cache = boxes.length; index < cache; index++) {
  24011. var parsedBox = boxes[index];
  24012. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  24013. }
  24014. }
  24015. // Spheres
  24016. var spheres = geometries.spheres;
  24017. if (spheres) {
  24018. for (index = 0, cache = spheres.length; index < cache; index++) {
  24019. var parsedSphere = spheres[index];
  24020. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  24021. }
  24022. }
  24023. // Cylinders
  24024. var cylinders = geometries.cylinders;
  24025. if (cylinders) {
  24026. for (index = 0, cache = cylinders.length; index < cache; index++) {
  24027. var parsedCylinder = cylinders[index];
  24028. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  24029. }
  24030. }
  24031. // Toruses
  24032. var toruses = geometries.toruses;
  24033. if (toruses) {
  24034. for (index = 0, cache = toruses.length; index < cache; index++) {
  24035. var parsedTorus = toruses[index];
  24036. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  24037. }
  24038. }
  24039. // Grounds
  24040. var grounds = geometries.grounds;
  24041. if (grounds) {
  24042. for (index = 0, cache = grounds.length; index < cache; index++) {
  24043. var parsedGround = grounds[index];
  24044. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  24045. }
  24046. }
  24047. // Planes
  24048. var planes = geometries.planes;
  24049. if (planes) {
  24050. for (index = 0, cache = planes.length; index < cache; index++) {
  24051. var parsedPlane = planes[index];
  24052. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  24053. }
  24054. }
  24055. // TorusKnots
  24056. var torusKnots = geometries.torusKnots;
  24057. if (torusKnots) {
  24058. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  24059. var parsedTorusKnot = torusKnots[index];
  24060. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  24061. }
  24062. }
  24063. // VertexData
  24064. var vertexData = geometries.vertexData;
  24065. if (vertexData) {
  24066. for (index = 0, cache = vertexData.length; index < cache; index++) {
  24067. var parsedVertexData = vertexData[index];
  24068. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  24069. }
  24070. }
  24071. }
  24072. // Meshes
  24073. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  24074. var parsedMesh = parsedData.meshes[index];
  24075. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  24076. log += (index === 0 ? "\n\tMeshes:" : "");
  24077. log += "\n\t\t" + mesh.toString(fullDetails);
  24078. }
  24079. // Cameras
  24080. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  24081. var parsedCamera = parsedData.cameras[index];
  24082. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  24083. log += (index === 0 ? "\n\tCameras:" : "");
  24084. log += "\n\t\t" + camera.toString(fullDetails);
  24085. }
  24086. if (parsedData.activeCameraID) {
  24087. scene.setActiveCameraByID(parsedData.activeCameraID);
  24088. }
  24089. // Browsing all the graph to connect the dots
  24090. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  24091. var camera = scene.cameras[index];
  24092. if (camera._waitingParentId) {
  24093. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  24094. camera._waitingParentId = undefined;
  24095. }
  24096. }
  24097. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  24098. var light = scene.lights[index];
  24099. if (light._waitingParentId) {
  24100. light.parent = scene.getLastEntryByID(light._waitingParentId);
  24101. light._waitingParentId = undefined;
  24102. }
  24103. }
  24104. // Sounds
  24105. var loadedSounds = [];
  24106. var loadedSound;
  24107. if (BABYLON.AudioEngine && parsedData.sounds) {
  24108. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  24109. var parsedSound = parsedData.sounds[index];
  24110. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  24111. if (!parsedSound.url)
  24112. parsedSound.url = parsedSound.name;
  24113. if (!loadedSounds[parsedSound.url]) {
  24114. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  24115. loadedSounds[parsedSound.url] = loadedSound;
  24116. }
  24117. else {
  24118. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  24119. }
  24120. }
  24121. else {
  24122. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  24123. }
  24124. }
  24125. }
  24126. loadedSounds = [];
  24127. // Connect parents & children and parse actions
  24128. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24129. var mesh = scene.meshes[index];
  24130. if (mesh._waitingParentId) {
  24131. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  24132. mesh._waitingParentId = undefined;
  24133. }
  24134. if (mesh._waitingActions) {
  24135. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  24136. mesh._waitingActions = undefined;
  24137. }
  24138. }
  24139. // freeze world matrix application
  24140. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24141. var currentMesh = scene.meshes[index];
  24142. if (currentMesh._waitingFreezeWorldMatrix) {
  24143. currentMesh.freezeWorldMatrix();
  24144. currentMesh._waitingFreezeWorldMatrix = undefined;
  24145. }
  24146. else {
  24147. currentMesh.computeWorldMatrix(true);
  24148. }
  24149. }
  24150. // Particles Systems
  24151. if (parsedData.particleSystems) {
  24152. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  24153. var parsedParticleSystem = parsedData.particleSystems[index];
  24154. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  24155. }
  24156. }
  24157. // Lens flares
  24158. if (parsedData.lensFlareSystems) {
  24159. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  24160. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  24161. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  24162. }
  24163. }
  24164. // Shadows
  24165. if (parsedData.shadowGenerators) {
  24166. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  24167. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  24168. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  24169. }
  24170. }
  24171. // Actions (scene)
  24172. if (parsedData.actions) {
  24173. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  24174. }
  24175. // Finish
  24176. return true;
  24177. }
  24178. catch (err) {
  24179. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + log);
  24180. log = null;
  24181. throw err;
  24182. }
  24183. finally {
  24184. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  24185. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  24186. }
  24187. }
  24188. }
  24189. });
  24190. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24191. })(BABYLON || (BABYLON = {}));
  24192. var BABYLON;
  24193. (function (BABYLON) {
  24194. var SpriteManager = (function () {
  24195. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  24196. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24197. this.name = name;
  24198. this.cellSize = cellSize;
  24199. this.sprites = new Array();
  24200. this.renderingGroupId = 0;
  24201. this.layerMask = 0x0FFFFFFF;
  24202. this.fogEnabled = true;
  24203. this.isPickable = false;
  24204. this._vertexDeclaration = [4, 4, 4, 4];
  24205. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  24206. this._capacity = capacity;
  24207. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  24208. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24209. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24210. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  24211. this._scene = scene;
  24212. this._scene.spriteManagers.push(this);
  24213. // VBO
  24214. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  24215. var indices = [];
  24216. var index = 0;
  24217. for (var count = 0; count < capacity; count++) {
  24218. indices.push(index);
  24219. indices.push(index + 1);
  24220. indices.push(index + 2);
  24221. indices.push(index);
  24222. indices.push(index + 2);
  24223. indices.push(index + 3);
  24224. index += 4;
  24225. }
  24226. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24227. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  24228. // Effects
  24229. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  24230. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  24231. }
  24232. Object.defineProperty(SpriteManager.prototype, "texture", {
  24233. get: function () {
  24234. return this._spriteTexture;
  24235. },
  24236. set: function (value) {
  24237. this._spriteTexture = value;
  24238. },
  24239. enumerable: true,
  24240. configurable: true
  24241. });
  24242. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  24243. var arrayOffset = index * 16;
  24244. if (offsetX === 0)
  24245. offsetX = this._epsilon;
  24246. else if (offsetX === 1)
  24247. offsetX = 1 - this._epsilon;
  24248. if (offsetY === 0)
  24249. offsetY = this._epsilon;
  24250. else if (offsetY === 1)
  24251. offsetY = 1 - this._epsilon;
  24252. this._vertices[arrayOffset] = sprite.position.x;
  24253. this._vertices[arrayOffset + 1] = sprite.position.y;
  24254. this._vertices[arrayOffset + 2] = sprite.position.z;
  24255. this._vertices[arrayOffset + 3] = sprite.angle;
  24256. this._vertices[arrayOffset + 4] = sprite.width;
  24257. this._vertices[arrayOffset + 5] = sprite.height;
  24258. this._vertices[arrayOffset + 6] = offsetX;
  24259. this._vertices[arrayOffset + 7] = offsetY;
  24260. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  24261. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  24262. var offset = (sprite.cellIndex / rowSize) >> 0;
  24263. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  24264. this._vertices[arrayOffset + 11] = offset;
  24265. // Color
  24266. this._vertices[arrayOffset + 12] = sprite.color.r;
  24267. this._vertices[arrayOffset + 13] = sprite.color.g;
  24268. this._vertices[arrayOffset + 14] = sprite.color.b;
  24269. this._vertices[arrayOffset + 15] = sprite.color.a;
  24270. };
  24271. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  24272. var count = Math.min(this._capacity, this.sprites.length);
  24273. var min = BABYLON.Vector3.Zero();
  24274. var max = BABYLON.Vector3.Zero();
  24275. var distance = Number.MAX_VALUE;
  24276. var currentSprite;
  24277. var cameraSpacePosition = BABYLON.Vector3.Zero();
  24278. var cameraView = camera.getViewMatrix();
  24279. for (var index = 0; index < count; index++) {
  24280. var sprite = this.sprites[index];
  24281. if (!sprite) {
  24282. continue;
  24283. }
  24284. if (predicate) {
  24285. if (!predicate(sprite)) {
  24286. continue;
  24287. }
  24288. }
  24289. else if (!sprite.isPickable) {
  24290. continue;
  24291. }
  24292. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  24293. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  24294. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  24295. if (ray.intersectsBoxMinMax(min, max)) {
  24296. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  24297. if (distance > currentDistance) {
  24298. distance = currentDistance;
  24299. currentSprite = sprite;
  24300. if (fastCheck) {
  24301. break;
  24302. }
  24303. }
  24304. }
  24305. }
  24306. if (currentSprite) {
  24307. var result = new BABYLON.PickingInfo();
  24308. result.hit = true;
  24309. result.pickedSprite = currentSprite;
  24310. result.distance = distance;
  24311. return result;
  24312. }
  24313. return null;
  24314. };
  24315. SpriteManager.prototype.render = function () {
  24316. // Check
  24317. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  24318. return;
  24319. var engine = this._scene.getEngine();
  24320. var baseSize = this._spriteTexture.getBaseSize();
  24321. // Sprites
  24322. var deltaTime = engine.getDeltaTime();
  24323. var max = Math.min(this._capacity, this.sprites.length);
  24324. var rowSize = baseSize.width / this.cellSize;
  24325. var offset = 0;
  24326. for (var index = 0; index < max; index++) {
  24327. var sprite = this.sprites[index];
  24328. if (!sprite) {
  24329. continue;
  24330. }
  24331. sprite._animate(deltaTime);
  24332. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  24333. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  24334. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  24335. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  24336. }
  24337. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  24338. // Render
  24339. var effect = this._effectBase;
  24340. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  24341. effect = this._effectFog;
  24342. }
  24343. engine.enableEffect(effect);
  24344. var viewMatrix = this._scene.getViewMatrix();
  24345. effect.setTexture("diffuseSampler", this._spriteTexture);
  24346. effect.setMatrix("view", viewMatrix);
  24347. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  24348. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  24349. // Fog
  24350. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  24351. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  24352. effect.setColor3("vFogColor", this._scene.fogColor);
  24353. }
  24354. // VBOs
  24355. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  24356. // Draw order
  24357. engine.setDepthFunctionToLessOrEqual();
  24358. effect.setBool("alphaTest", true);
  24359. engine.setColorWrite(false);
  24360. engine.draw(true, 0, max * 6);
  24361. engine.setColorWrite(true);
  24362. effect.setBool("alphaTest", false);
  24363. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24364. engine.draw(true, 0, max * 6);
  24365. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24366. };
  24367. SpriteManager.prototype.dispose = function () {
  24368. if (this._vertexBuffer) {
  24369. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  24370. this._vertexBuffer = null;
  24371. }
  24372. if (this._indexBuffer) {
  24373. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  24374. this._indexBuffer = null;
  24375. }
  24376. if (this._spriteTexture) {
  24377. this._spriteTexture.dispose();
  24378. this._spriteTexture = null;
  24379. }
  24380. // Remove from scene
  24381. var index = this._scene.spriteManagers.indexOf(this);
  24382. this._scene.spriteManagers.splice(index, 1);
  24383. // Callback
  24384. if (this.onDispose) {
  24385. this.onDispose();
  24386. }
  24387. };
  24388. return SpriteManager;
  24389. })();
  24390. BABYLON.SpriteManager = SpriteManager;
  24391. })(BABYLON || (BABYLON = {}));
  24392. var BABYLON;
  24393. (function (BABYLON) {
  24394. var Sprite = (function () {
  24395. function Sprite(name, manager) {
  24396. this.name = name;
  24397. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24398. this.width = 1.0;
  24399. this.height = 1.0;
  24400. this.angle = 0;
  24401. this.cellIndex = 0;
  24402. this.invertU = 0;
  24403. this.invertV = 0;
  24404. this.animations = new Array();
  24405. this.isPickable = false;
  24406. this._animationStarted = false;
  24407. this._loopAnimation = false;
  24408. this._fromIndex = 0;
  24409. this._toIndex = 0;
  24410. this._delay = 0;
  24411. this._direction = 1;
  24412. this._frameCount = 0;
  24413. this._time = 0;
  24414. this._manager = manager;
  24415. this._manager.sprites.push(this);
  24416. this.position = BABYLON.Vector3.Zero();
  24417. }
  24418. Object.defineProperty(Sprite.prototype, "size", {
  24419. get: function () {
  24420. return this.width;
  24421. },
  24422. set: function (value) {
  24423. this.width = value;
  24424. this.height = value;
  24425. },
  24426. enumerable: true,
  24427. configurable: true
  24428. });
  24429. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  24430. this._fromIndex = from;
  24431. this._toIndex = to;
  24432. this._loopAnimation = loop;
  24433. this._delay = delay;
  24434. this._animationStarted = true;
  24435. this._direction = from < to ? 1 : -1;
  24436. this.cellIndex = from;
  24437. this._time = 0;
  24438. };
  24439. Sprite.prototype.stopAnimation = function () {
  24440. this._animationStarted = false;
  24441. };
  24442. Sprite.prototype._animate = function (deltaTime) {
  24443. if (!this._animationStarted)
  24444. return;
  24445. this._time += deltaTime;
  24446. if (this._time > this._delay) {
  24447. this._time = this._time % this._delay;
  24448. this.cellIndex += this._direction;
  24449. if (this.cellIndex == this._toIndex) {
  24450. if (this._loopAnimation) {
  24451. this.cellIndex = this._fromIndex;
  24452. }
  24453. else {
  24454. this._animationStarted = false;
  24455. if (this.disposeWhenFinishedAnimating) {
  24456. this.dispose();
  24457. }
  24458. }
  24459. }
  24460. }
  24461. };
  24462. Sprite.prototype.dispose = function () {
  24463. for (var i = 0; i < this._manager.sprites.length; i++) {
  24464. if (this._manager.sprites[i] == this) {
  24465. this._manager.sprites.splice(i, 1);
  24466. }
  24467. }
  24468. };
  24469. return Sprite;
  24470. })();
  24471. BABYLON.Sprite = Sprite;
  24472. })(BABYLON || (BABYLON = {}));
  24473. var BABYLON;
  24474. (function (BABYLON) {
  24475. var Layer = (function () {
  24476. function Layer(name, imgUrl, scene, isBackground, color) {
  24477. this.name = name;
  24478. this.scale = new BABYLON.Vector2(1, 1);
  24479. this.offset = new BABYLON.Vector2(0, 0);
  24480. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  24481. this._vertexDeclaration = [2];
  24482. this._vertexStrideSize = 2 * 4;
  24483. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  24484. this.isBackground = isBackground === undefined ? true : isBackground;
  24485. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  24486. this._scene = scene;
  24487. this._scene.layers.push(this);
  24488. // VBO
  24489. var vertices = [];
  24490. vertices.push(1, 1);
  24491. vertices.push(-1, 1);
  24492. vertices.push(-1, -1);
  24493. vertices.push(1, -1);
  24494. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  24495. // Indices
  24496. var indices = [];
  24497. indices.push(0);
  24498. indices.push(1);
  24499. indices.push(2);
  24500. indices.push(0);
  24501. indices.push(2);
  24502. indices.push(3);
  24503. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24504. // Effects
  24505. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  24506. this._alphaTestEffect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  24507. }
  24508. Layer.prototype.render = function () {
  24509. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  24510. // Check
  24511. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  24512. return;
  24513. var engine = this._scene.getEngine();
  24514. if (this.onBeforeRender) {
  24515. this.onBeforeRender();
  24516. }
  24517. // Render
  24518. engine.enableEffect(currentEffect);
  24519. engine.setState(false);
  24520. // Texture
  24521. currentEffect.setTexture("textureSampler", this.texture);
  24522. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  24523. // Color
  24524. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  24525. // Scale / offset
  24526. currentEffect.setVector2("offset", this.offset);
  24527. currentEffect.setVector2("scale", this.scale);
  24528. // VBOs
  24529. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, currentEffect);
  24530. // Draw order
  24531. if (!this._alphaTestEffect) {
  24532. engine.setAlphaMode(this.alphaBlendingMode);
  24533. engine.draw(true, 0, 6);
  24534. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24535. }
  24536. else {
  24537. engine.draw(true, 0, 6);
  24538. }
  24539. if (this.onAfterRender) {
  24540. this.onAfterRender();
  24541. }
  24542. };
  24543. Layer.prototype.dispose = function () {
  24544. if (this._vertexBuffer) {
  24545. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  24546. this._vertexBuffer = null;
  24547. }
  24548. if (this._indexBuffer) {
  24549. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  24550. this._indexBuffer = null;
  24551. }
  24552. if (this.texture) {
  24553. this.texture.dispose();
  24554. this.texture = null;
  24555. }
  24556. // Remove from scene
  24557. var index = this._scene.layers.indexOf(this);
  24558. this._scene.layers.splice(index, 1);
  24559. // Callback
  24560. if (this.onDispose) {
  24561. this.onDispose();
  24562. }
  24563. };
  24564. return Layer;
  24565. })();
  24566. BABYLON.Layer = Layer;
  24567. })(BABYLON || (BABYLON = {}));
  24568. var BABYLON;
  24569. (function (BABYLON) {
  24570. var Particle = (function () {
  24571. function Particle() {
  24572. this.position = BABYLON.Vector3.Zero();
  24573. this.direction = BABYLON.Vector3.Zero();
  24574. this.color = new BABYLON.Color4(0, 0, 0, 0);
  24575. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  24576. this.lifeTime = 1.0;
  24577. this.age = 0;
  24578. this.size = 0;
  24579. this.angle = 0;
  24580. this.angularSpeed = 0;
  24581. }
  24582. Particle.prototype.copyTo = function (other) {
  24583. other.position.copyFrom(this.position);
  24584. other.direction.copyFrom(this.direction);
  24585. other.color.copyFrom(this.color);
  24586. other.colorStep.copyFrom(this.colorStep);
  24587. other.lifeTime = this.lifeTime;
  24588. other.age = this.age;
  24589. other.size = this.size;
  24590. other.angle = this.angle;
  24591. other.angularSpeed = this.angularSpeed;
  24592. };
  24593. return Particle;
  24594. })();
  24595. BABYLON.Particle = Particle;
  24596. })(BABYLON || (BABYLON = {}));
  24597. var BABYLON;
  24598. (function (BABYLON) {
  24599. var randomNumber = function (min, max) {
  24600. if (min === max) {
  24601. return (min);
  24602. }
  24603. var random = Math.random();
  24604. return ((random * (max - min)) + min);
  24605. };
  24606. var ParticleSystem = (function () {
  24607. function ParticleSystem(name, capacity, scene, customEffect) {
  24608. var _this = this;
  24609. this.name = name;
  24610. // Members
  24611. this.animations = [];
  24612. this.renderingGroupId = 0;
  24613. this.emitter = null;
  24614. this.emitRate = 10;
  24615. this.manualEmitCount = -1;
  24616. this.updateSpeed = 0.01;
  24617. this.targetStopDuration = 0;
  24618. this.disposeOnStop = false;
  24619. this.minEmitPower = 1;
  24620. this.maxEmitPower = 1;
  24621. this.minLifeTime = 1;
  24622. this.maxLifeTime = 1;
  24623. this.minSize = 1;
  24624. this.maxSize = 1;
  24625. this.minAngularSpeed = 0;
  24626. this.maxAngularSpeed = 0;
  24627. this.layerMask = 0x0FFFFFFF;
  24628. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  24629. this.forceDepthWrite = false;
  24630. this.gravity = BABYLON.Vector3.Zero();
  24631. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  24632. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  24633. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  24634. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  24635. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24636. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24637. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  24638. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24639. this.particles = new Array();
  24640. this._vertexDeclaration = [3, 4, 4];
  24641. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  24642. this._stockParticles = new Array();
  24643. this._newPartsExcess = 0;
  24644. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  24645. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  24646. this._scaledDirection = BABYLON.Vector3.Zero();
  24647. this._scaledGravity = BABYLON.Vector3.Zero();
  24648. this._currentRenderId = -1;
  24649. this._started = false;
  24650. this._stopped = false;
  24651. this._actualFrame = 0;
  24652. this.id = name;
  24653. this._capacity = capacity;
  24654. this._scene = scene;
  24655. this._customEffect = customEffect;
  24656. scene.particleSystems.push(this);
  24657. // VBO
  24658. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  24659. var indices = [];
  24660. var index = 0;
  24661. for (var count = 0; count < capacity; count++) {
  24662. indices.push(index);
  24663. indices.push(index + 1);
  24664. indices.push(index + 2);
  24665. indices.push(index);
  24666. indices.push(index + 2);
  24667. indices.push(index + 3);
  24668. index += 4;
  24669. }
  24670. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24671. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  24672. // Default behaviors
  24673. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  24674. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  24675. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  24676. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  24677. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  24678. };
  24679. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  24680. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  24681. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  24682. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  24683. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  24684. };
  24685. this.updateFunction = function (particles) {
  24686. for (var index = 0; index < particles.length; index++) {
  24687. var particle = particles[index];
  24688. particle.age += _this._scaledUpdateSpeed;
  24689. if (particle.age >= particle.lifeTime) {
  24690. _this.recycleParticle(particle);
  24691. index--;
  24692. continue;
  24693. }
  24694. else {
  24695. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  24696. particle.color.addInPlace(_this._scaledColorStep);
  24697. if (particle.color.a < 0)
  24698. particle.color.a = 0;
  24699. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  24700. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  24701. particle.position.addInPlace(_this._scaledDirection);
  24702. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  24703. particle.direction.addInPlace(_this._scaledGravity);
  24704. }
  24705. }
  24706. };
  24707. }
  24708. ParticleSystem.prototype.recycleParticle = function (particle) {
  24709. var lastParticle = this.particles.pop();
  24710. if (lastParticle !== particle) {
  24711. lastParticle.copyTo(particle);
  24712. this._stockParticles.push(lastParticle);
  24713. }
  24714. };
  24715. ParticleSystem.prototype.getCapacity = function () {
  24716. return this._capacity;
  24717. };
  24718. ParticleSystem.prototype.isAlive = function () {
  24719. return this._alive;
  24720. };
  24721. ParticleSystem.prototype.isStarted = function () {
  24722. return this._started;
  24723. };
  24724. ParticleSystem.prototype.start = function () {
  24725. this._started = true;
  24726. this._stopped = false;
  24727. this._actualFrame = 0;
  24728. };
  24729. ParticleSystem.prototype.stop = function () {
  24730. this._stopped = true;
  24731. };
  24732. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  24733. var offset = index * 11;
  24734. this._vertices[offset] = particle.position.x;
  24735. this._vertices[offset + 1] = particle.position.y;
  24736. this._vertices[offset + 2] = particle.position.z;
  24737. this._vertices[offset + 3] = particle.color.r;
  24738. this._vertices[offset + 4] = particle.color.g;
  24739. this._vertices[offset + 5] = particle.color.b;
  24740. this._vertices[offset + 6] = particle.color.a;
  24741. this._vertices[offset + 7] = particle.angle;
  24742. this._vertices[offset + 8] = particle.size;
  24743. this._vertices[offset + 9] = offsetX;
  24744. this._vertices[offset + 10] = offsetY;
  24745. };
  24746. ParticleSystem.prototype._update = function (newParticles) {
  24747. // Update current
  24748. this._alive = this.particles.length > 0;
  24749. this.updateFunction(this.particles);
  24750. // Add new ones
  24751. var worldMatrix;
  24752. if (this.emitter.position) {
  24753. worldMatrix = this.emitter.getWorldMatrix();
  24754. }
  24755. else {
  24756. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  24757. }
  24758. var particle;
  24759. for (var index = 0; index < newParticles; index++) {
  24760. if (this.particles.length === this._capacity) {
  24761. break;
  24762. }
  24763. if (this._stockParticles.length !== 0) {
  24764. particle = this._stockParticles.pop();
  24765. particle.age = 0;
  24766. }
  24767. else {
  24768. particle = new BABYLON.Particle();
  24769. }
  24770. this.particles.push(particle);
  24771. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  24772. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  24773. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  24774. particle.size = randomNumber(this.minSize, this.maxSize);
  24775. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  24776. this.startPositionFunction(worldMatrix, particle.position, particle);
  24777. var step = randomNumber(0, 1.0);
  24778. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  24779. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  24780. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  24781. }
  24782. };
  24783. ParticleSystem.prototype._getEffect = function () {
  24784. if (this._customEffect) {
  24785. return this._customEffect;
  24786. }
  24787. ;
  24788. var defines = [];
  24789. if (this._scene.clipPlane) {
  24790. defines.push("#define CLIPPLANE");
  24791. }
  24792. // Effect
  24793. var join = defines.join("\n");
  24794. if (this._cachedDefines !== join) {
  24795. this._cachedDefines = join;
  24796. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  24797. }
  24798. return this._effect;
  24799. };
  24800. ParticleSystem.prototype.animate = function () {
  24801. if (!this._started)
  24802. return;
  24803. var effect = this._getEffect();
  24804. // Check
  24805. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  24806. return;
  24807. if (this._currentRenderId === this._scene.getRenderId()) {
  24808. return;
  24809. }
  24810. this._currentRenderId = this._scene.getRenderId();
  24811. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  24812. // determine the number of particles we need to create
  24813. var newParticles;
  24814. if (this.manualEmitCount > -1) {
  24815. newParticles = this.manualEmitCount;
  24816. this._newPartsExcess = 0;
  24817. this.manualEmitCount = 0;
  24818. }
  24819. else {
  24820. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  24821. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  24822. }
  24823. if (this._newPartsExcess > 1.0) {
  24824. newParticles += this._newPartsExcess >> 0;
  24825. this._newPartsExcess -= this._newPartsExcess >> 0;
  24826. }
  24827. this._alive = false;
  24828. if (!this._stopped) {
  24829. this._actualFrame += this._scaledUpdateSpeed;
  24830. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  24831. this.stop();
  24832. }
  24833. else {
  24834. newParticles = 0;
  24835. }
  24836. this._update(newParticles);
  24837. // Stopped?
  24838. if (this._stopped) {
  24839. if (!this._alive) {
  24840. this._started = false;
  24841. if (this.disposeOnStop) {
  24842. this._scene._toBeDisposed.push(this);
  24843. }
  24844. }
  24845. }
  24846. // Update VBO
  24847. var offset = 0;
  24848. for (var index = 0; index < this.particles.length; index++) {
  24849. var particle = this.particles[index];
  24850. this._appendParticleVertex(offset++, particle, 0, 0);
  24851. this._appendParticleVertex(offset++, particle, 1, 0);
  24852. this._appendParticleVertex(offset++, particle, 1, 1);
  24853. this._appendParticleVertex(offset++, particle, 0, 1);
  24854. }
  24855. var engine = this._scene.getEngine();
  24856. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  24857. };
  24858. ParticleSystem.prototype.render = function () {
  24859. var effect = this._getEffect();
  24860. // Check
  24861. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  24862. return 0;
  24863. var engine = this._scene.getEngine();
  24864. // Render
  24865. engine.enableEffect(effect);
  24866. engine.setState(false);
  24867. var viewMatrix = this._scene.getViewMatrix();
  24868. effect.setTexture("diffuseSampler", this.particleTexture);
  24869. effect.setMatrix("view", viewMatrix);
  24870. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  24871. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  24872. if (this._scene.clipPlane) {
  24873. var clipPlane = this._scene.clipPlane;
  24874. var invView = viewMatrix.clone();
  24875. invView.invert();
  24876. effect.setMatrix("invView", invView);
  24877. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  24878. }
  24879. // VBOs
  24880. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  24881. // Draw order
  24882. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  24883. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  24884. }
  24885. else {
  24886. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24887. }
  24888. if (this.forceDepthWrite) {
  24889. engine.setDepthWrite(true);
  24890. }
  24891. engine.draw(true, 0, this.particles.length * 6);
  24892. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24893. return this.particles.length;
  24894. };
  24895. ParticleSystem.prototype.dispose = function () {
  24896. if (this._vertexBuffer) {
  24897. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  24898. this._vertexBuffer = null;
  24899. }
  24900. if (this._indexBuffer) {
  24901. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  24902. this._indexBuffer = null;
  24903. }
  24904. if (this.particleTexture) {
  24905. this.particleTexture.dispose();
  24906. this.particleTexture = null;
  24907. }
  24908. // Remove from scene
  24909. var index = this._scene.particleSystems.indexOf(this);
  24910. this._scene.particleSystems.splice(index, 1);
  24911. // Callback
  24912. if (this.onDispose) {
  24913. this.onDispose();
  24914. }
  24915. };
  24916. // Clone
  24917. ParticleSystem.prototype.clone = function (name, newEmitter) {
  24918. var result = new ParticleSystem(name, this._capacity, this._scene);
  24919. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  24920. if (newEmitter === undefined) {
  24921. newEmitter = this.emitter;
  24922. }
  24923. result.emitter = newEmitter;
  24924. if (this.particleTexture) {
  24925. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  24926. }
  24927. result.start();
  24928. return result;
  24929. };
  24930. ParticleSystem.prototype.serialize = function () {
  24931. var serializationObject = {};
  24932. serializationObject.name = this.name;
  24933. serializationObject.id = this.id;
  24934. // Emitter
  24935. if (this.emitter.position) {
  24936. serializationObject.emitterId = this.emitter.id;
  24937. }
  24938. else {
  24939. serializationObject.emitter = this.emitter.asArray();
  24940. }
  24941. serializationObject.capacity = this.getCapacity();
  24942. if (this.particleTexture) {
  24943. serializationObject.textureName = this.particleTexture.name;
  24944. }
  24945. // Animations
  24946. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24947. // Particle system
  24948. serializationObject.minAngularSpeed = this.minAngularSpeed;
  24949. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  24950. serializationObject.minSize = this.minSize;
  24951. serializationObject.maxSize = this.maxSize;
  24952. serializationObject.minEmitPower = this.minEmitPower;
  24953. serializationObject.maxEmitPower = this.maxEmitPower;
  24954. serializationObject.minLifeTime = this.minLifeTime;
  24955. serializationObject.maxLifeTime = this.maxLifeTime;
  24956. serializationObject.emitRate = this.emitRate;
  24957. serializationObject.minEmitBox = this.minEmitBox.asArray();
  24958. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  24959. serializationObject.gravity = this.gravity.asArray();
  24960. serializationObject.direction1 = this.direction1.asArray();
  24961. serializationObject.direction2 = this.direction2.asArray();
  24962. serializationObject.color1 = this.color1.asArray();
  24963. serializationObject.color2 = this.color2.asArray();
  24964. serializationObject.colorDead = this.colorDead.asArray();
  24965. serializationObject.updateSpeed = this.updateSpeed;
  24966. serializationObject.targetStopDuration = this.targetStopDuration;
  24967. serializationObject.textureMask = this.textureMask.asArray();
  24968. serializationObject.blendMode = this.blendMode;
  24969. return serializationObject;
  24970. };
  24971. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  24972. var name = parsedParticleSystem.name;
  24973. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  24974. if (parsedParticleSystem.id) {
  24975. particleSystem.id = parsedParticleSystem.id;
  24976. }
  24977. // Texture
  24978. if (parsedParticleSystem.textureName) {
  24979. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  24980. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  24981. }
  24982. // Emitter
  24983. if (parsedParticleSystem.emitterId) {
  24984. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  24985. }
  24986. else {
  24987. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  24988. }
  24989. // Animations
  24990. if (parsedParticleSystem.animations) {
  24991. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  24992. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  24993. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24994. }
  24995. }
  24996. if (parsedParticleSystem.autoAnimate) {
  24997. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  24998. }
  24999. // Particle system
  25000. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  25001. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  25002. particleSystem.minSize = parsedParticleSystem.minSize;
  25003. particleSystem.maxSize = parsedParticleSystem.maxSize;
  25004. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  25005. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  25006. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  25007. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  25008. particleSystem.emitRate = parsedParticleSystem.emitRate;
  25009. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  25010. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  25011. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  25012. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  25013. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  25014. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  25015. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  25016. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  25017. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  25018. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  25019. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  25020. particleSystem.blendMode = parsedParticleSystem.blendMode;
  25021. particleSystem.start();
  25022. return particleSystem;
  25023. };
  25024. // Statics
  25025. ParticleSystem.BLENDMODE_ONEONE = 0;
  25026. ParticleSystem.BLENDMODE_STANDARD = 1;
  25027. return ParticleSystem;
  25028. })();
  25029. BABYLON.ParticleSystem = ParticleSystem;
  25030. })(BABYLON || (BABYLON = {}));
  25031. var BABYLON;
  25032. (function (BABYLON) {
  25033. var AnimationRange = (function () {
  25034. function AnimationRange(name, from, to) {
  25035. this.name = name;
  25036. this.from = from;
  25037. this.to = to;
  25038. }
  25039. AnimationRange.prototype.clone = function () {
  25040. return new AnimationRange(this.name, this.from, this.to);
  25041. };
  25042. return AnimationRange;
  25043. })();
  25044. BABYLON.AnimationRange = AnimationRange;
  25045. /**
  25046. * Composed of a frame, and an action function
  25047. */
  25048. var AnimationEvent = (function () {
  25049. function AnimationEvent(frame, action, onlyOnce) {
  25050. this.frame = frame;
  25051. this.action = action;
  25052. this.onlyOnce = onlyOnce;
  25053. this.isDone = false;
  25054. }
  25055. return AnimationEvent;
  25056. })();
  25057. BABYLON.AnimationEvent = AnimationEvent;
  25058. var PathCursor = (function () {
  25059. function PathCursor(path) {
  25060. this.path = path;
  25061. this._onchange = new Array();
  25062. this.value = 0;
  25063. this.animations = new Array();
  25064. }
  25065. PathCursor.prototype.getPoint = function () {
  25066. var point = this.path.getPointAtLengthPosition(this.value);
  25067. return new BABYLON.Vector3(point.x, 0, point.y);
  25068. };
  25069. PathCursor.prototype.moveAhead = function (step) {
  25070. if (step === void 0) { step = 0.002; }
  25071. this.move(step);
  25072. return this;
  25073. };
  25074. PathCursor.prototype.moveBack = function (step) {
  25075. if (step === void 0) { step = 0.002; }
  25076. this.move(-step);
  25077. return this;
  25078. };
  25079. PathCursor.prototype.move = function (step) {
  25080. if (Math.abs(step) > 1) {
  25081. throw "step size should be less than 1.";
  25082. }
  25083. this.value += step;
  25084. this.ensureLimits();
  25085. this.raiseOnChange();
  25086. return this;
  25087. };
  25088. PathCursor.prototype.ensureLimits = function () {
  25089. while (this.value > 1) {
  25090. this.value -= 1;
  25091. }
  25092. while (this.value < 0) {
  25093. this.value += 1;
  25094. }
  25095. return this;
  25096. };
  25097. // used by animation engine
  25098. PathCursor.prototype.markAsDirty = function (propertyName) {
  25099. this.ensureLimits();
  25100. this.raiseOnChange();
  25101. return this;
  25102. };
  25103. PathCursor.prototype.raiseOnChange = function () {
  25104. var _this = this;
  25105. this._onchange.forEach(function (f) { return f(_this); });
  25106. return this;
  25107. };
  25108. PathCursor.prototype.onchange = function (f) {
  25109. this._onchange.push(f);
  25110. return this;
  25111. };
  25112. return PathCursor;
  25113. })();
  25114. BABYLON.PathCursor = PathCursor;
  25115. var Animation = (function () {
  25116. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  25117. this.name = name;
  25118. this.targetProperty = targetProperty;
  25119. this.framePerSecond = framePerSecond;
  25120. this.dataType = dataType;
  25121. this.loopMode = loopMode;
  25122. this.enableBlending = enableBlending;
  25123. this._offsetsCache = {};
  25124. this._highLimitsCache = {};
  25125. this._stopped = false;
  25126. this._blendingFactor = 0;
  25127. // The set of event that will be linked to this animation
  25128. this._events = new Array();
  25129. this.allowMatricesInterpolation = false;
  25130. this.blendingSpeed = 0.01;
  25131. this._ranges = {};
  25132. this.targetPropertyPath = targetProperty.split(".");
  25133. this.dataType = dataType;
  25134. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  25135. }
  25136. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  25137. var dataType = undefined;
  25138. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  25139. dataType = Animation.ANIMATIONTYPE_FLOAT;
  25140. }
  25141. else if (from instanceof BABYLON.Quaternion) {
  25142. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  25143. }
  25144. else if (from instanceof BABYLON.Vector3) {
  25145. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  25146. }
  25147. else if (from instanceof BABYLON.Vector2) {
  25148. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  25149. }
  25150. else if (from instanceof BABYLON.Color3) {
  25151. dataType = Animation.ANIMATIONTYPE_COLOR3;
  25152. }
  25153. if (dataType == undefined) {
  25154. return null;
  25155. }
  25156. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  25157. var keys = [];
  25158. keys.push({ frame: 0, value: from });
  25159. keys.push({ frame: totalFrame, value: to });
  25160. animation.setKeys(keys);
  25161. if (easingFunction !== undefined) {
  25162. animation.setEasingFunction(easingFunction);
  25163. }
  25164. return animation;
  25165. };
  25166. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  25167. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  25168. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  25169. };
  25170. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  25171. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  25172. node.animations.push(animation);
  25173. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  25174. };
  25175. // Methods
  25176. /**
  25177. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25178. */
  25179. Animation.prototype.toString = function (fullDetails) {
  25180. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  25181. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  25182. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  25183. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  25184. if (fullDetails) {
  25185. ret += ", Ranges: {";
  25186. var first = true;
  25187. for (var name in this._ranges) {
  25188. if (!first) {
  25189. ret + ", ";
  25190. first = false;
  25191. }
  25192. ret += name;
  25193. }
  25194. ret += "}";
  25195. }
  25196. return ret;
  25197. };
  25198. /**
  25199. * Add an event to this animation.
  25200. */
  25201. Animation.prototype.addEvent = function (event) {
  25202. this._events.push(event);
  25203. };
  25204. /**
  25205. * Remove all events found at the given frame
  25206. * @param frame
  25207. */
  25208. Animation.prototype.removeEvents = function (frame) {
  25209. for (var index = 0; index < this._events.length; index++) {
  25210. if (this._events[index].frame === frame) {
  25211. this._events.splice(index, 1);
  25212. index--;
  25213. }
  25214. }
  25215. };
  25216. Animation.prototype.createRange = function (name, from, to) {
  25217. // check name not already in use; could happen for bones after serialized
  25218. if (!this._ranges[name]) {
  25219. this._ranges[name] = new AnimationRange(name, from, to);
  25220. }
  25221. };
  25222. Animation.prototype.deleteRange = function (name, deleteFrames) {
  25223. if (deleteFrames === void 0) { deleteFrames = true; }
  25224. if (this._ranges[name]) {
  25225. if (deleteFrames) {
  25226. var from = this._ranges[name].from;
  25227. var to = this._ranges[name].to;
  25228. // this loop MUST go high to low for multiple splices to work
  25229. for (var key = this._keys.length - 1; key >= 0; key--) {
  25230. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  25231. this._keys.splice(key, 1);
  25232. }
  25233. }
  25234. }
  25235. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  25236. }
  25237. };
  25238. Animation.prototype.getRange = function (name) {
  25239. return this._ranges[name];
  25240. };
  25241. Animation.prototype.reset = function () {
  25242. this._offsetsCache = {};
  25243. this._highLimitsCache = {};
  25244. this.currentFrame = 0;
  25245. this._blendingFactor = 0;
  25246. this._originalBlendValue = null;
  25247. };
  25248. Animation.prototype.isStopped = function () {
  25249. return this._stopped;
  25250. };
  25251. Animation.prototype.getKeys = function () {
  25252. return this._keys;
  25253. };
  25254. Animation.prototype.getHighestFrame = function () {
  25255. var ret = 0;
  25256. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  25257. if (ret < this._keys[key].frame) {
  25258. ret = this._keys[key].frame;
  25259. }
  25260. }
  25261. return ret;
  25262. };
  25263. Animation.prototype.getEasingFunction = function () {
  25264. return this._easingFunction;
  25265. };
  25266. Animation.prototype.setEasingFunction = function (easingFunction) {
  25267. this._easingFunction = easingFunction;
  25268. };
  25269. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  25270. return startValue + (endValue - startValue) * gradient;
  25271. };
  25272. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  25273. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  25274. };
  25275. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  25276. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  25277. };
  25278. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  25279. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  25280. };
  25281. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  25282. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  25283. };
  25284. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  25285. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  25286. };
  25287. Animation.prototype.clone = function () {
  25288. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  25289. if (this._keys) {
  25290. clone.setKeys(this._keys);
  25291. }
  25292. if (this._ranges) {
  25293. clone._ranges = {};
  25294. for (var name in this._ranges) {
  25295. clone._ranges[name] = this._ranges[name].clone();
  25296. }
  25297. }
  25298. return clone;
  25299. };
  25300. Animation.prototype.setKeys = function (values) {
  25301. this._keys = values.slice(0);
  25302. this._offsetsCache = {};
  25303. this._highLimitsCache = {};
  25304. };
  25305. Animation.prototype._getKeyValue = function (value) {
  25306. if (typeof value === "function") {
  25307. return value();
  25308. }
  25309. return value;
  25310. };
  25311. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  25312. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  25313. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  25314. }
  25315. this.currentFrame = currentFrame;
  25316. // Try to get a hash to find the right key
  25317. 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));
  25318. if (this._keys[startKey].frame >= currentFrame) {
  25319. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  25320. startKey--;
  25321. }
  25322. }
  25323. for (var key = startKey; key < this._keys.length; key++) {
  25324. if (this._keys[key + 1].frame >= currentFrame) {
  25325. var startValue = this._getKeyValue(this._keys[key].value);
  25326. var endValue = this._getKeyValue(this._keys[key + 1].value);
  25327. // gradient : percent of currentFrame between the frame inf and the frame sup
  25328. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  25329. // check for easingFunction and correction of gradient
  25330. if (this._easingFunction != null) {
  25331. gradient = this._easingFunction.ease(gradient);
  25332. }
  25333. switch (this.dataType) {
  25334. // Float
  25335. case Animation.ANIMATIONTYPE_FLOAT:
  25336. switch (loopMode) {
  25337. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25338. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25339. return this.floatInterpolateFunction(startValue, endValue, gradient);
  25340. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25341. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  25342. }
  25343. break;
  25344. // Quaternion
  25345. case Animation.ANIMATIONTYPE_QUATERNION:
  25346. var quaternion = null;
  25347. switch (loopMode) {
  25348. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25349. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25350. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  25351. break;
  25352. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25353. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25354. break;
  25355. }
  25356. return quaternion;
  25357. // Vector3
  25358. case Animation.ANIMATIONTYPE_VECTOR3:
  25359. switch (loopMode) {
  25360. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25361. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25362. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  25363. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25364. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25365. }
  25366. // Vector2
  25367. case Animation.ANIMATIONTYPE_VECTOR2:
  25368. switch (loopMode) {
  25369. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25370. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25371. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  25372. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25373. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25374. }
  25375. // Color3
  25376. case Animation.ANIMATIONTYPE_COLOR3:
  25377. switch (loopMode) {
  25378. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25379. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25380. return this.color3InterpolateFunction(startValue, endValue, gradient);
  25381. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25382. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25383. }
  25384. // Matrix
  25385. case Animation.ANIMATIONTYPE_MATRIX:
  25386. switch (loopMode) {
  25387. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25388. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25389. if (this.allowMatricesInterpolation) {
  25390. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  25391. }
  25392. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25393. return startValue;
  25394. }
  25395. default:
  25396. break;
  25397. }
  25398. break;
  25399. }
  25400. }
  25401. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  25402. };
  25403. Animation.prototype.setValue = function (currentValue, blend) {
  25404. if (blend === void 0) { blend = false; }
  25405. // Set value
  25406. var path;
  25407. var destination;
  25408. if (this.targetPropertyPath.length > 1) {
  25409. var property = this._target[this.targetPropertyPath[0]];
  25410. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  25411. property = property[this.targetPropertyPath[index]];
  25412. }
  25413. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  25414. destination = property;
  25415. }
  25416. else {
  25417. path = this.targetPropertyPath[0];
  25418. destination = this._target;
  25419. }
  25420. // Blending
  25421. if (this.enableBlending && this._blendingFactor <= 1.0) {
  25422. if (!this._originalBlendValue) {
  25423. this._originalBlendValue = destination[path];
  25424. }
  25425. if (this._originalBlendValue.prototype) {
  25426. if (this._originalBlendValue.prototype.Lerp) {
  25427. destination[path] = this._originalBlendValue.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  25428. }
  25429. else {
  25430. destination[path] = currentValue;
  25431. }
  25432. }
  25433. else {
  25434. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  25435. }
  25436. this._blendingFactor += this.blendingSpeed;
  25437. }
  25438. else {
  25439. destination[path] = currentValue;
  25440. }
  25441. if (this._target.markAsDirty) {
  25442. this._target.markAsDirty(this.targetProperty);
  25443. }
  25444. };
  25445. Animation.prototype.goToFrame = function (frame) {
  25446. if (frame < this._keys[0].frame) {
  25447. frame = this._keys[0].frame;
  25448. }
  25449. else if (frame > this._keys[this._keys.length - 1].frame) {
  25450. frame = this._keys[this._keys.length - 1].frame;
  25451. }
  25452. var currentValue = this._interpolate(frame, 0, this.loopMode);
  25453. this.setValue(currentValue);
  25454. };
  25455. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  25456. if (blend === void 0) { blend = false; }
  25457. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  25458. this._stopped = true;
  25459. return false;
  25460. }
  25461. var returnValue = true;
  25462. // Adding a start key at frame 0 if missing
  25463. if (this._keys[0].frame !== 0) {
  25464. var newKey = { frame: 0, value: this._keys[0].value };
  25465. this._keys.splice(0, 0, newKey);
  25466. }
  25467. // Check limits
  25468. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  25469. from = this._keys[0].frame;
  25470. }
  25471. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  25472. to = this._keys[this._keys.length - 1].frame;
  25473. }
  25474. // Compute ratio
  25475. var range = to - from;
  25476. var offsetValue;
  25477. // ratio represents the frame delta between from and to
  25478. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  25479. var highLimitValue = 0;
  25480. if (ratio > range && !loop) {
  25481. returnValue = false;
  25482. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  25483. }
  25484. else {
  25485. // Get max value if required
  25486. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  25487. var keyOffset = to.toString() + from.toString();
  25488. if (!this._offsetsCache[keyOffset]) {
  25489. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  25490. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  25491. switch (this.dataType) {
  25492. // Float
  25493. case Animation.ANIMATIONTYPE_FLOAT:
  25494. this._offsetsCache[keyOffset] = toValue - fromValue;
  25495. break;
  25496. // Quaternion
  25497. case Animation.ANIMATIONTYPE_QUATERNION:
  25498. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25499. break;
  25500. // Vector3
  25501. case Animation.ANIMATIONTYPE_VECTOR3:
  25502. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25503. // Vector2
  25504. case Animation.ANIMATIONTYPE_VECTOR2:
  25505. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25506. // Color3
  25507. case Animation.ANIMATIONTYPE_COLOR3:
  25508. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25509. default:
  25510. break;
  25511. }
  25512. this._highLimitsCache[keyOffset] = toValue;
  25513. }
  25514. highLimitValue = this._highLimitsCache[keyOffset];
  25515. offsetValue = this._offsetsCache[keyOffset];
  25516. }
  25517. }
  25518. if (offsetValue === undefined) {
  25519. switch (this.dataType) {
  25520. // Float
  25521. case Animation.ANIMATIONTYPE_FLOAT:
  25522. offsetValue = 0;
  25523. break;
  25524. // Quaternion
  25525. case Animation.ANIMATIONTYPE_QUATERNION:
  25526. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  25527. break;
  25528. // Vector3
  25529. case Animation.ANIMATIONTYPE_VECTOR3:
  25530. offsetValue = BABYLON.Vector3.Zero();
  25531. break;
  25532. // Vector2
  25533. case Animation.ANIMATIONTYPE_VECTOR2:
  25534. offsetValue = BABYLON.Vector2.Zero();
  25535. break;
  25536. // Color3
  25537. case Animation.ANIMATIONTYPE_COLOR3:
  25538. offsetValue = BABYLON.Color3.Black();
  25539. }
  25540. }
  25541. // Compute value
  25542. var repeatCount = (ratio / range) >> 0;
  25543. var currentFrame = returnValue ? from + ratio % range : to;
  25544. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  25545. // Set value
  25546. this.setValue(currentValue);
  25547. // Check events
  25548. for (var index = 0; index < this._events.length; index++) {
  25549. if (currentFrame >= this._events[index].frame) {
  25550. var event = this._events[index];
  25551. if (!event.isDone) {
  25552. // If event should be done only once, remove it.
  25553. if (event.onlyOnce) {
  25554. this._events.splice(index, 1);
  25555. index--;
  25556. }
  25557. event.isDone = true;
  25558. event.action();
  25559. } // Don't do anything if the event has already be done.
  25560. }
  25561. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  25562. // reset event, the animation is looping
  25563. this._events[index].isDone = false;
  25564. }
  25565. }
  25566. if (!returnValue) {
  25567. this._stopped = true;
  25568. }
  25569. return returnValue;
  25570. };
  25571. Animation.prototype.serialize = function () {
  25572. var serializationObject = {};
  25573. serializationObject.name = this.name;
  25574. serializationObject.property = this.targetProperty;
  25575. serializationObject.framePerSecond = this.framePerSecond;
  25576. serializationObject.dataType = this.dataType;
  25577. serializationObject.loopBehavior = this.loopMode;
  25578. var dataType = this.dataType;
  25579. serializationObject.keys = [];
  25580. var keys = this.getKeys();
  25581. for (var index = 0; index < keys.length; index++) {
  25582. var animationKey = keys[index];
  25583. var key = {};
  25584. key.frame = animationKey.frame;
  25585. switch (dataType) {
  25586. case Animation.ANIMATIONTYPE_FLOAT:
  25587. key.values = [animationKey.value];
  25588. break;
  25589. case Animation.ANIMATIONTYPE_QUATERNION:
  25590. case Animation.ANIMATIONTYPE_MATRIX:
  25591. case Animation.ANIMATIONTYPE_VECTOR3:
  25592. case Animation.ANIMATIONTYPE_COLOR3:
  25593. key.values = animationKey.value.asArray();
  25594. break;
  25595. }
  25596. serializationObject.keys.push(key);
  25597. }
  25598. serializationObject.ranges = [];
  25599. for (var name in this._ranges) {
  25600. var range = {};
  25601. range.name = name;
  25602. range.from = this._ranges[name].from;
  25603. range.to = this._ranges[name].to;
  25604. serializationObject.ranges.push(range);
  25605. }
  25606. return serializationObject;
  25607. };
  25608. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  25609. get: function () {
  25610. return Animation._ANIMATIONTYPE_FLOAT;
  25611. },
  25612. enumerable: true,
  25613. configurable: true
  25614. });
  25615. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  25616. get: function () {
  25617. return Animation._ANIMATIONTYPE_VECTOR3;
  25618. },
  25619. enumerable: true,
  25620. configurable: true
  25621. });
  25622. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  25623. get: function () {
  25624. return Animation._ANIMATIONTYPE_VECTOR2;
  25625. },
  25626. enumerable: true,
  25627. configurable: true
  25628. });
  25629. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  25630. get: function () {
  25631. return Animation._ANIMATIONTYPE_QUATERNION;
  25632. },
  25633. enumerable: true,
  25634. configurable: true
  25635. });
  25636. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  25637. get: function () {
  25638. return Animation._ANIMATIONTYPE_MATRIX;
  25639. },
  25640. enumerable: true,
  25641. configurable: true
  25642. });
  25643. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  25644. get: function () {
  25645. return Animation._ANIMATIONTYPE_COLOR3;
  25646. },
  25647. enumerable: true,
  25648. configurable: true
  25649. });
  25650. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  25651. get: function () {
  25652. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  25653. },
  25654. enumerable: true,
  25655. configurable: true
  25656. });
  25657. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  25658. get: function () {
  25659. return Animation._ANIMATIONLOOPMODE_CYCLE;
  25660. },
  25661. enumerable: true,
  25662. configurable: true
  25663. });
  25664. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  25665. get: function () {
  25666. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  25667. },
  25668. enumerable: true,
  25669. configurable: true
  25670. });
  25671. Animation.Parse = function (parsedAnimation) {
  25672. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  25673. var dataType = parsedAnimation.dataType;
  25674. var keys = [];
  25675. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  25676. var key = parsedAnimation.keys[index];
  25677. var data;
  25678. switch (dataType) {
  25679. case Animation.ANIMATIONTYPE_FLOAT:
  25680. data = key.values[0];
  25681. break;
  25682. case Animation.ANIMATIONTYPE_QUATERNION:
  25683. data = BABYLON.Quaternion.FromArray(key.values);
  25684. break;
  25685. case Animation.ANIMATIONTYPE_MATRIX:
  25686. data = BABYLON.Matrix.FromArray(key.values);
  25687. break;
  25688. case Animation.ANIMATIONTYPE_COLOR3:
  25689. data = BABYLON.Color3.FromArray(key.values);
  25690. break;
  25691. case Animation.ANIMATIONTYPE_VECTOR3:
  25692. default:
  25693. data = BABYLON.Vector3.FromArray(key.values);
  25694. break;
  25695. }
  25696. keys.push({
  25697. frame: key.frame,
  25698. value: data
  25699. });
  25700. }
  25701. animation.setKeys(keys);
  25702. if (parsedAnimation.ranges) {
  25703. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  25704. data = parsedAnimation.ranges[index];
  25705. animation.createRange(data.name, data.from, data.to);
  25706. }
  25707. }
  25708. return animation;
  25709. };
  25710. Animation.AppendSerializedAnimations = function (source, destination) {
  25711. if (source.animations) {
  25712. destination.animations = [];
  25713. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  25714. var animation = source.animations[animationIndex];
  25715. destination.animations.push(animation.serialize());
  25716. }
  25717. }
  25718. };
  25719. // Statics
  25720. Animation._ANIMATIONTYPE_FLOAT = 0;
  25721. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  25722. Animation._ANIMATIONTYPE_QUATERNION = 2;
  25723. Animation._ANIMATIONTYPE_MATRIX = 3;
  25724. Animation._ANIMATIONTYPE_COLOR3 = 4;
  25725. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  25726. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  25727. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  25728. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  25729. return Animation;
  25730. })();
  25731. BABYLON.Animation = Animation;
  25732. })(BABYLON || (BABYLON = {}));
  25733. var BABYLON;
  25734. (function (BABYLON) {
  25735. var Animatable = (function () {
  25736. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  25737. if (fromFrame === void 0) { fromFrame = 0; }
  25738. if (toFrame === void 0) { toFrame = 100; }
  25739. if (loopAnimation === void 0) { loopAnimation = false; }
  25740. if (speedRatio === void 0) { speedRatio = 1.0; }
  25741. this.target = target;
  25742. this.fromFrame = fromFrame;
  25743. this.toFrame = toFrame;
  25744. this.loopAnimation = loopAnimation;
  25745. this.speedRatio = speedRatio;
  25746. this.onAnimationEnd = onAnimationEnd;
  25747. this._animations = new Array();
  25748. this._paused = false;
  25749. this.animationStarted = false;
  25750. if (animations) {
  25751. this.appendAnimations(target, animations);
  25752. }
  25753. this._scene = scene;
  25754. scene._activeAnimatables.push(this);
  25755. }
  25756. // Methods
  25757. Animatable.prototype.getAnimations = function () {
  25758. return this._animations;
  25759. };
  25760. Animatable.prototype.appendAnimations = function (target, animations) {
  25761. for (var index = 0; index < animations.length; index++) {
  25762. var animation = animations[index];
  25763. animation._target = target;
  25764. this._animations.push(animation);
  25765. }
  25766. };
  25767. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  25768. var animations = this._animations;
  25769. for (var index = 0; index < animations.length; index++) {
  25770. if (animations[index].targetProperty === property) {
  25771. return animations[index];
  25772. }
  25773. }
  25774. return null;
  25775. };
  25776. Animatable.prototype.reset = function () {
  25777. var animations = this._animations;
  25778. for (var index = 0; index < animations.length; index++) {
  25779. animations[index].reset();
  25780. }
  25781. this._localDelayOffset = null;
  25782. this._pausedDelay = null;
  25783. };
  25784. Animatable.prototype.enableBlending = function (blendingSpeed) {
  25785. var animations = this._animations;
  25786. for (var index = 0; index < animations.length; index++) {
  25787. animations[index].enableBlending = true;
  25788. animations[index].blendingSpeed = blendingSpeed;
  25789. }
  25790. };
  25791. Animatable.prototype.disableBlending = function () {
  25792. var animations = this._animations;
  25793. for (var index = 0; index < animations.length; index++) {
  25794. animations[index].enableBlending = false;
  25795. }
  25796. };
  25797. Animatable.prototype.goToFrame = function (frame) {
  25798. var animations = this._animations;
  25799. for (var index = 0; index < animations.length; index++) {
  25800. animations[index].goToFrame(frame);
  25801. }
  25802. };
  25803. Animatable.prototype.pause = function () {
  25804. if (this._paused) {
  25805. return;
  25806. }
  25807. this._paused = true;
  25808. };
  25809. Animatable.prototype.restart = function () {
  25810. this._paused = false;
  25811. };
  25812. Animatable.prototype.stop = function () {
  25813. var index = this._scene._activeAnimatables.indexOf(this);
  25814. if (index > -1) {
  25815. this._scene._activeAnimatables.splice(index, 1);
  25816. var animations = this._animations;
  25817. for (var index = 0; index < animations.length; index++) {
  25818. animations[index].reset();
  25819. }
  25820. if (this.onAnimationEnd) {
  25821. this.onAnimationEnd();
  25822. }
  25823. }
  25824. };
  25825. Animatable.prototype._animate = function (delay) {
  25826. if (this._paused) {
  25827. this.animationStarted = false;
  25828. if (!this._pausedDelay) {
  25829. this._pausedDelay = delay;
  25830. }
  25831. return true;
  25832. }
  25833. if (!this._localDelayOffset) {
  25834. this._localDelayOffset = delay;
  25835. }
  25836. else if (this._pausedDelay) {
  25837. this._localDelayOffset += delay - this._pausedDelay;
  25838. this._pausedDelay = null;
  25839. }
  25840. // Animating
  25841. var running = false;
  25842. var animations = this._animations;
  25843. var index;
  25844. for (index = 0; index < animations.length; index++) {
  25845. var animation = animations[index];
  25846. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  25847. running = running || isRunning;
  25848. }
  25849. this.animationStarted = running;
  25850. if (!running) {
  25851. // Remove from active animatables
  25852. index = this._scene._activeAnimatables.indexOf(this);
  25853. this._scene._activeAnimatables.splice(index, 1);
  25854. }
  25855. if (!running && this.onAnimationEnd) {
  25856. this.onAnimationEnd();
  25857. this.onAnimationEnd = null;
  25858. }
  25859. return running;
  25860. };
  25861. return Animatable;
  25862. })();
  25863. BABYLON.Animatable = Animatable;
  25864. })(BABYLON || (BABYLON = {}));
  25865. var BABYLON;
  25866. (function (BABYLON) {
  25867. var EasingFunction = (function () {
  25868. function EasingFunction() {
  25869. // Properties
  25870. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  25871. }
  25872. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  25873. get: function () {
  25874. return EasingFunction._EASINGMODE_EASEIN;
  25875. },
  25876. enumerable: true,
  25877. configurable: true
  25878. });
  25879. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  25880. get: function () {
  25881. return EasingFunction._EASINGMODE_EASEOUT;
  25882. },
  25883. enumerable: true,
  25884. configurable: true
  25885. });
  25886. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  25887. get: function () {
  25888. return EasingFunction._EASINGMODE_EASEINOUT;
  25889. },
  25890. enumerable: true,
  25891. configurable: true
  25892. });
  25893. EasingFunction.prototype.setEasingMode = function (easingMode) {
  25894. var n = Math.min(Math.max(easingMode, 0), 2);
  25895. this._easingMode = n;
  25896. };
  25897. EasingFunction.prototype.getEasingMode = function () {
  25898. return this._easingMode;
  25899. };
  25900. EasingFunction.prototype.easeInCore = function (gradient) {
  25901. throw new Error('You must implement this method');
  25902. };
  25903. EasingFunction.prototype.ease = function (gradient) {
  25904. switch (this._easingMode) {
  25905. case EasingFunction.EASINGMODE_EASEIN:
  25906. return this.easeInCore(gradient);
  25907. case EasingFunction.EASINGMODE_EASEOUT:
  25908. return (1 - this.easeInCore(1 - gradient));
  25909. }
  25910. if (gradient >= 0.5) {
  25911. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  25912. }
  25913. return (this.easeInCore(gradient * 2) * 0.5);
  25914. };
  25915. //Statics
  25916. EasingFunction._EASINGMODE_EASEIN = 0;
  25917. EasingFunction._EASINGMODE_EASEOUT = 1;
  25918. EasingFunction._EASINGMODE_EASEINOUT = 2;
  25919. return EasingFunction;
  25920. })();
  25921. BABYLON.EasingFunction = EasingFunction;
  25922. var CircleEase = (function (_super) {
  25923. __extends(CircleEase, _super);
  25924. function CircleEase() {
  25925. _super.apply(this, arguments);
  25926. }
  25927. CircleEase.prototype.easeInCore = function (gradient) {
  25928. gradient = Math.max(0, Math.min(1, gradient));
  25929. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  25930. };
  25931. return CircleEase;
  25932. })(EasingFunction);
  25933. BABYLON.CircleEase = CircleEase;
  25934. var BackEase = (function (_super) {
  25935. __extends(BackEase, _super);
  25936. function BackEase(amplitude) {
  25937. if (amplitude === void 0) { amplitude = 1; }
  25938. _super.call(this);
  25939. this.amplitude = amplitude;
  25940. }
  25941. BackEase.prototype.easeInCore = function (gradient) {
  25942. var num = Math.max(0, this.amplitude);
  25943. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  25944. };
  25945. return BackEase;
  25946. })(EasingFunction);
  25947. BABYLON.BackEase = BackEase;
  25948. var BounceEase = (function (_super) {
  25949. __extends(BounceEase, _super);
  25950. function BounceEase(bounces, bounciness) {
  25951. if (bounces === void 0) { bounces = 3; }
  25952. if (bounciness === void 0) { bounciness = 2; }
  25953. _super.call(this);
  25954. this.bounces = bounces;
  25955. this.bounciness = bounciness;
  25956. }
  25957. BounceEase.prototype.easeInCore = function (gradient) {
  25958. var y = Math.max(0.0, this.bounces);
  25959. var bounciness = this.bounciness;
  25960. if (bounciness <= 1.0) {
  25961. bounciness = 1.001;
  25962. }
  25963. var num9 = Math.pow(bounciness, y);
  25964. var num5 = 1.0 - bounciness;
  25965. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  25966. var num15 = gradient * num4;
  25967. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  25968. var num3 = Math.floor(num65);
  25969. var num13 = num3 + 1.0;
  25970. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  25971. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  25972. var num7 = (num8 + num12) * 0.5;
  25973. var num6 = gradient - num7;
  25974. var num2 = num7 - num8;
  25975. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  25976. };
  25977. return BounceEase;
  25978. })(EasingFunction);
  25979. BABYLON.BounceEase = BounceEase;
  25980. var CubicEase = (function (_super) {
  25981. __extends(CubicEase, _super);
  25982. function CubicEase() {
  25983. _super.apply(this, arguments);
  25984. }
  25985. CubicEase.prototype.easeInCore = function (gradient) {
  25986. return (gradient * gradient * gradient);
  25987. };
  25988. return CubicEase;
  25989. })(EasingFunction);
  25990. BABYLON.CubicEase = CubicEase;
  25991. var ElasticEase = (function (_super) {
  25992. __extends(ElasticEase, _super);
  25993. function ElasticEase(oscillations, springiness) {
  25994. if (oscillations === void 0) { oscillations = 3; }
  25995. if (springiness === void 0) { springiness = 3; }
  25996. _super.call(this);
  25997. this.oscillations = oscillations;
  25998. this.springiness = springiness;
  25999. }
  26000. ElasticEase.prototype.easeInCore = function (gradient) {
  26001. var num2;
  26002. var num3 = Math.max(0.0, this.oscillations);
  26003. var num = Math.max(0.0, this.springiness);
  26004. if (num == 0) {
  26005. num2 = gradient;
  26006. }
  26007. else {
  26008. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  26009. }
  26010. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  26011. };
  26012. return ElasticEase;
  26013. })(EasingFunction);
  26014. BABYLON.ElasticEase = ElasticEase;
  26015. var ExponentialEase = (function (_super) {
  26016. __extends(ExponentialEase, _super);
  26017. function ExponentialEase(exponent) {
  26018. if (exponent === void 0) { exponent = 2; }
  26019. _super.call(this);
  26020. this.exponent = exponent;
  26021. }
  26022. ExponentialEase.prototype.easeInCore = function (gradient) {
  26023. if (this.exponent <= 0) {
  26024. return gradient;
  26025. }
  26026. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  26027. };
  26028. return ExponentialEase;
  26029. })(EasingFunction);
  26030. BABYLON.ExponentialEase = ExponentialEase;
  26031. var PowerEase = (function (_super) {
  26032. __extends(PowerEase, _super);
  26033. function PowerEase(power) {
  26034. if (power === void 0) { power = 2; }
  26035. _super.call(this);
  26036. this.power = power;
  26037. }
  26038. PowerEase.prototype.easeInCore = function (gradient) {
  26039. var y = Math.max(0.0, this.power);
  26040. return Math.pow(gradient, y);
  26041. };
  26042. return PowerEase;
  26043. })(EasingFunction);
  26044. BABYLON.PowerEase = PowerEase;
  26045. var QuadraticEase = (function (_super) {
  26046. __extends(QuadraticEase, _super);
  26047. function QuadraticEase() {
  26048. _super.apply(this, arguments);
  26049. }
  26050. QuadraticEase.prototype.easeInCore = function (gradient) {
  26051. return (gradient * gradient);
  26052. };
  26053. return QuadraticEase;
  26054. })(EasingFunction);
  26055. BABYLON.QuadraticEase = QuadraticEase;
  26056. var QuarticEase = (function (_super) {
  26057. __extends(QuarticEase, _super);
  26058. function QuarticEase() {
  26059. _super.apply(this, arguments);
  26060. }
  26061. QuarticEase.prototype.easeInCore = function (gradient) {
  26062. return (gradient * gradient * gradient * gradient);
  26063. };
  26064. return QuarticEase;
  26065. })(EasingFunction);
  26066. BABYLON.QuarticEase = QuarticEase;
  26067. var QuinticEase = (function (_super) {
  26068. __extends(QuinticEase, _super);
  26069. function QuinticEase() {
  26070. _super.apply(this, arguments);
  26071. }
  26072. QuinticEase.prototype.easeInCore = function (gradient) {
  26073. return (gradient * gradient * gradient * gradient * gradient);
  26074. };
  26075. return QuinticEase;
  26076. })(EasingFunction);
  26077. BABYLON.QuinticEase = QuinticEase;
  26078. var SineEase = (function (_super) {
  26079. __extends(SineEase, _super);
  26080. function SineEase() {
  26081. _super.apply(this, arguments);
  26082. }
  26083. SineEase.prototype.easeInCore = function (gradient) {
  26084. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  26085. };
  26086. return SineEase;
  26087. })(EasingFunction);
  26088. BABYLON.SineEase = SineEase;
  26089. var BezierCurveEase = (function (_super) {
  26090. __extends(BezierCurveEase, _super);
  26091. function BezierCurveEase(x1, y1, x2, y2) {
  26092. if (x1 === void 0) { x1 = 0; }
  26093. if (y1 === void 0) { y1 = 0; }
  26094. if (x2 === void 0) { x2 = 1; }
  26095. if (y2 === void 0) { y2 = 1; }
  26096. _super.call(this);
  26097. this.x1 = x1;
  26098. this.y1 = y1;
  26099. this.x2 = x2;
  26100. this.y2 = y2;
  26101. }
  26102. BezierCurveEase.prototype.easeInCore = function (gradient) {
  26103. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  26104. };
  26105. return BezierCurveEase;
  26106. })(EasingFunction);
  26107. BABYLON.BezierCurveEase = BezierCurveEase;
  26108. })(BABYLON || (BABYLON = {}));
  26109. var BABYLON;
  26110. (function (BABYLON) {
  26111. var Bone = (function (_super) {
  26112. __extends(Bone, _super);
  26113. function Bone(name, skeleton, parentBone, matrix, restPose) {
  26114. _super.call(this, name, skeleton.getScene());
  26115. this.name = name;
  26116. this.children = new Array();
  26117. this.animations = new Array();
  26118. this._worldTransform = new BABYLON.Matrix();
  26119. this._absoluteTransform = new BABYLON.Matrix();
  26120. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  26121. this._skeleton = skeleton;
  26122. this._matrix = matrix;
  26123. this._baseMatrix = matrix;
  26124. this._restPose = restPose ? restPose : matrix.clone();
  26125. skeleton.bones.push(this);
  26126. if (parentBone) {
  26127. this._parent = parentBone;
  26128. parentBone.children.push(this);
  26129. }
  26130. else {
  26131. this._parent = null;
  26132. }
  26133. this._updateDifferenceMatrix();
  26134. }
  26135. // Members
  26136. Bone.prototype.getParent = function () {
  26137. return this._parent;
  26138. };
  26139. Bone.prototype.getLocalMatrix = function () {
  26140. return this._matrix;
  26141. };
  26142. Bone.prototype.getBaseMatrix = function () {
  26143. return this._baseMatrix;
  26144. };
  26145. Bone.prototype.getRestPose = function () {
  26146. return this._restPose;
  26147. };
  26148. Bone.prototype.returnToRest = function () {
  26149. this.updateMatrix(this._restPose.clone());
  26150. };
  26151. Bone.prototype.getWorldMatrix = function () {
  26152. return this._worldTransform;
  26153. };
  26154. Bone.prototype.getInvertedAbsoluteTransform = function () {
  26155. return this._invertedAbsoluteTransform;
  26156. };
  26157. Bone.prototype.getAbsoluteTransform = function () {
  26158. return this._absoluteTransform;
  26159. };
  26160. // Methods
  26161. Bone.prototype.updateMatrix = function (matrix) {
  26162. this._baseMatrix = matrix.clone();
  26163. this._matrix = matrix.clone();
  26164. this._skeleton._markAsDirty();
  26165. this._updateDifferenceMatrix();
  26166. };
  26167. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  26168. if (!rootMatrix) {
  26169. rootMatrix = this._baseMatrix;
  26170. }
  26171. if (this._parent) {
  26172. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  26173. }
  26174. else {
  26175. this._absoluteTransform.copyFrom(rootMatrix);
  26176. }
  26177. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  26178. for (var index = 0; index < this.children.length; index++) {
  26179. this.children[index]._updateDifferenceMatrix();
  26180. }
  26181. };
  26182. Bone.prototype.markAsDirty = function () {
  26183. this._currentRenderId++;
  26184. this._skeleton._markAsDirty();
  26185. };
  26186. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  26187. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  26188. // all animation may be coming from a library skeleton, so may need to create animation
  26189. if (this.animations.length === 0) {
  26190. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  26191. this.animations[0].setKeys([]);
  26192. }
  26193. // get animation info / verify there is such a range from the source bone
  26194. var sourceRange = source.animations[0].getRange(rangeName);
  26195. if (!sourceRange) {
  26196. return false;
  26197. }
  26198. var from = sourceRange.from;
  26199. var to = sourceRange.to;
  26200. var sourceKeys = source.animations[0].getKeys();
  26201. // rescaling prep
  26202. var sourceBoneLength = source.length;
  26203. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  26204. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  26205. var destKeys = this.animations[0].getKeys();
  26206. // loop vars declaration / initialization
  26207. var orig;
  26208. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  26209. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  26210. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  26211. var mat;
  26212. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  26213. orig = sourceKeys[key];
  26214. if (orig.frame >= from && orig.frame <= to) {
  26215. if (scalingReqd) {
  26216. orig.value.decompose(origScale, origRotation, origTranslation);
  26217. origTranslation.scaleInPlace(ratio);
  26218. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  26219. }
  26220. else {
  26221. mat = orig.value;
  26222. }
  26223. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  26224. }
  26225. }
  26226. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  26227. return true;
  26228. };
  26229. return Bone;
  26230. })(BABYLON.Node);
  26231. BABYLON.Bone = Bone;
  26232. })(BABYLON || (BABYLON = {}));
  26233. var BABYLON;
  26234. (function (BABYLON) {
  26235. var Skeleton = (function () {
  26236. function Skeleton(name, id, scene) {
  26237. this.name = name;
  26238. this.id = id;
  26239. this.bones = new Array();
  26240. this.needInitialSkinMatrix = false;
  26241. this._isDirty = true;
  26242. this._meshesWithPoseMatrix = new Array();
  26243. this._identity = BABYLON.Matrix.Identity();
  26244. this._ranges = {};
  26245. this.bones = [];
  26246. this._scene = scene;
  26247. scene.skeletons.push(this);
  26248. //make sure it will recalculate the matrix next time prepare is called.
  26249. this._isDirty = true;
  26250. }
  26251. // Members
  26252. Skeleton.prototype.getTransformMatrices = function (mesh) {
  26253. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  26254. return mesh._bonesTransformMatrices;
  26255. }
  26256. return this._transformMatrices;
  26257. };
  26258. Skeleton.prototype.getScene = function () {
  26259. return this._scene;
  26260. };
  26261. // Methods
  26262. /**
  26263. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26264. */
  26265. Skeleton.prototype.toString = function (fullDetails) {
  26266. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  26267. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  26268. if (fullDetails) {
  26269. ret += ", Ranges: {";
  26270. var first = true;
  26271. for (var name in this._ranges) {
  26272. if (!first) {
  26273. ret + ", ";
  26274. first = false;
  26275. }
  26276. ret += name;
  26277. }
  26278. ret += "}";
  26279. }
  26280. return ret;
  26281. };
  26282. /**
  26283. * Get bone's index searching by name
  26284. * @param {string} name is bone's name to search for
  26285. * @return {number} Indice of the bone. Returns -1 if not found
  26286. */
  26287. Skeleton.prototype.getBoneIndexByName = function (name) {
  26288. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  26289. if (this.bones[boneIndex].name === name) {
  26290. return boneIndex;
  26291. }
  26292. }
  26293. return -1;
  26294. };
  26295. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  26296. // check name not already in use
  26297. if (!this._ranges[name]) {
  26298. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  26299. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26300. if (this.bones[i].animations[0]) {
  26301. this.bones[i].animations[0].createRange(name, from, to);
  26302. }
  26303. }
  26304. }
  26305. };
  26306. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  26307. if (deleteFrames === void 0) { deleteFrames = true; }
  26308. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26309. if (this.bones[i].animations[0]) {
  26310. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  26311. }
  26312. }
  26313. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  26314. };
  26315. Skeleton.prototype.getAnimationRange = function (name) {
  26316. return this._ranges[name];
  26317. };
  26318. /**
  26319. * Returns as an Array, all AnimationRanges defined on this skeleton
  26320. */
  26321. Skeleton.prototype.getAnimationRanges = function () {
  26322. var animationRanges = [];
  26323. var name;
  26324. var i = 0;
  26325. for (name in this._ranges) {
  26326. animationRanges[i] = this._ranges[name];
  26327. i++;
  26328. }
  26329. return animationRanges;
  26330. };
  26331. /**
  26332. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  26333. */
  26334. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  26335. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  26336. if (this._ranges[name] || !source.getAnimationRange(name)) {
  26337. return false;
  26338. }
  26339. var ret = true;
  26340. var frameOffset = this._getHighestAnimationFrame() + 1;
  26341. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  26342. var boneDict = {};
  26343. var sourceBones = source.bones;
  26344. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  26345. boneDict[sourceBones[i].name] = sourceBones[i];
  26346. }
  26347. if (this.bones.length !== sourceBones.length) {
  26348. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  26349. ret = false;
  26350. }
  26351. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26352. var boneName = this.bones[i].name;
  26353. var sourceBone = boneDict[boneName];
  26354. if (sourceBone) {
  26355. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  26356. }
  26357. else {
  26358. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  26359. ret = false;
  26360. }
  26361. }
  26362. // do not call createAnimationRange(), since it also is done to bones, which was already done
  26363. var range = source.getAnimationRange(name);
  26364. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  26365. return ret;
  26366. };
  26367. Skeleton.prototype.returnToRest = function () {
  26368. for (var index = 0; index < this.bones.length; index++) {
  26369. this.bones[index].returnToRest();
  26370. }
  26371. };
  26372. Skeleton.prototype._getHighestAnimationFrame = function () {
  26373. var ret = 0;
  26374. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26375. if (this.bones[i].animations[0]) {
  26376. var highest = this.bones[i].animations[0].getHighestFrame();
  26377. if (ret < highest) {
  26378. ret = highest;
  26379. }
  26380. }
  26381. }
  26382. return ret;
  26383. };
  26384. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  26385. var range = this.getAnimationRange(name);
  26386. if (!range) {
  26387. return null;
  26388. }
  26389. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  26390. };
  26391. Skeleton.prototype._markAsDirty = function () {
  26392. this._isDirty = true;
  26393. };
  26394. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  26395. this._meshesWithPoseMatrix.push(mesh);
  26396. };
  26397. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  26398. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  26399. if (index > -1) {
  26400. this._meshesWithPoseMatrix.splice(index, 1);
  26401. }
  26402. };
  26403. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  26404. for (var index = 0; index < this.bones.length; index++) {
  26405. var bone = this.bones[index];
  26406. var parentBone = bone.getParent();
  26407. if (parentBone) {
  26408. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  26409. }
  26410. else {
  26411. if (initialSkinMatrix) {
  26412. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  26413. }
  26414. else {
  26415. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  26416. }
  26417. }
  26418. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  26419. }
  26420. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  26421. };
  26422. Skeleton.prototype.prepare = function () {
  26423. if (!this._isDirty) {
  26424. return;
  26425. }
  26426. if (this.needInitialSkinMatrix) {
  26427. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  26428. var mesh = this._meshesWithPoseMatrix[index];
  26429. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  26430. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  26431. }
  26432. var poseMatrix = mesh.getPoseMatrix();
  26433. // Prepare bones
  26434. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  26435. var bone = this.bones[boneIndex];
  26436. if (!bone.getParent()) {
  26437. var matrix = bone.getBaseMatrix();
  26438. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  26439. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  26440. }
  26441. }
  26442. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  26443. }
  26444. }
  26445. else {
  26446. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  26447. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  26448. }
  26449. this._computeTransformMatrices(this._transformMatrices, null);
  26450. }
  26451. this._isDirty = false;
  26452. this._scene._activeBones += this.bones.length;
  26453. };
  26454. Skeleton.prototype.getAnimatables = function () {
  26455. if (!this._animatables || this._animatables.length !== this.bones.length) {
  26456. this._animatables = [];
  26457. for (var index = 0; index < this.bones.length; index++) {
  26458. this._animatables.push(this.bones[index]);
  26459. }
  26460. }
  26461. return this._animatables;
  26462. };
  26463. Skeleton.prototype.clone = function (name, id) {
  26464. var result = new Skeleton(name, id || name, this._scene);
  26465. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  26466. for (var index = 0; index < this.bones.length; index++) {
  26467. var source = this.bones[index];
  26468. var parentBone = null;
  26469. if (source.getParent()) {
  26470. var parentIndex = this.bones.indexOf(source.getParent());
  26471. parentBone = result.bones[parentIndex];
  26472. }
  26473. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  26474. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  26475. }
  26476. if (this._ranges) {
  26477. result._ranges = {};
  26478. for (var rangeName in this._ranges) {
  26479. result._ranges[rangeName] = this._ranges[rangeName].clone();
  26480. }
  26481. }
  26482. this._isDirty = true;
  26483. return result;
  26484. };
  26485. Skeleton.prototype.dispose = function () {
  26486. this._meshesWithPoseMatrix = [];
  26487. // Animations
  26488. this.getScene().stopAnimation(this);
  26489. // Remove from scene
  26490. this.getScene().removeSkeleton(this);
  26491. };
  26492. Skeleton.prototype.serialize = function () {
  26493. var serializationObject = {};
  26494. serializationObject.name = this.name;
  26495. serializationObject.id = this.id;
  26496. serializationObject.bones = [];
  26497. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  26498. for (var index = 0; index < this.bones.length; index++) {
  26499. var bone = this.bones[index];
  26500. var serializedBone = {
  26501. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  26502. name: bone.name,
  26503. matrix: bone.getLocalMatrix().toArray(),
  26504. rest: bone.getRestPose().toArray()
  26505. };
  26506. serializationObject.bones.push(serializedBone);
  26507. if (bone.length) {
  26508. serializedBone.length = bone.length;
  26509. }
  26510. if (bone.animations && bone.animations.length > 0) {
  26511. serializedBone.animation = bone.animations[0].serialize();
  26512. }
  26513. serializationObject.ranges = [];
  26514. for (var name in this._ranges) {
  26515. var range = {};
  26516. range.name = name;
  26517. range.from = this._ranges[name].from;
  26518. range.to = this._ranges[name].to;
  26519. serializationObject.ranges.push(range);
  26520. }
  26521. }
  26522. return serializationObject;
  26523. };
  26524. Skeleton.Parse = function (parsedSkeleton, scene) {
  26525. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  26526. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  26527. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  26528. var parsedBone = parsedSkeleton.bones[index];
  26529. var parentBone = null;
  26530. if (parsedBone.parentBoneIndex > -1) {
  26531. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  26532. }
  26533. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  26534. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  26535. if (parsedBone.length) {
  26536. bone.length = parsedBone.length;
  26537. }
  26538. if (parsedBone.animation) {
  26539. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  26540. }
  26541. }
  26542. // placed after bones, so createAnimationRange can cascade down
  26543. if (parsedSkeleton.ranges) {
  26544. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  26545. var data = parsedSkeleton.ranges[index];
  26546. skeleton.createAnimationRange(data.name, data.from, data.to);
  26547. }
  26548. }
  26549. return skeleton;
  26550. };
  26551. return Skeleton;
  26552. })();
  26553. BABYLON.Skeleton = Skeleton;
  26554. })(BABYLON || (BABYLON = {}));
  26555. var BABYLON;
  26556. (function (BABYLON) {
  26557. var PostProcess = (function () {
  26558. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  26559. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  26560. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  26561. this.name = name;
  26562. this.width = -1;
  26563. this.height = -1;
  26564. this._reusable = false;
  26565. this._textures = new BABYLON.SmartArray(2);
  26566. this._currentRenderTextureInd = 0;
  26567. if (camera != null) {
  26568. this._camera = camera;
  26569. this._scene = camera.getScene();
  26570. camera.attachPostProcess(this);
  26571. this._engine = this._scene.getEngine();
  26572. }
  26573. else {
  26574. this._engine = engine;
  26575. }
  26576. this._renderRatio = ratio;
  26577. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  26578. this._reusable = reusable || false;
  26579. this._textureType = textureType;
  26580. this._samplers = samplers || [];
  26581. this._samplers.push("textureSampler");
  26582. this._fragmentUrl = fragmentUrl;
  26583. this._parameters = parameters || [];
  26584. this.updateEffect(defines);
  26585. }
  26586. PostProcess.prototype.updateEffect = function (defines) {
  26587. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  26588. };
  26589. PostProcess.prototype.isReusable = function () {
  26590. return this._reusable;
  26591. };
  26592. PostProcess.prototype.activate = function (camera, sourceTexture) {
  26593. camera = camera || this._camera;
  26594. var scene = camera.getScene();
  26595. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  26596. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  26597. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  26598. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  26599. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  26600. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  26601. if (this._textures.length > 0) {
  26602. for (var i = 0; i < this._textures.length; i++) {
  26603. this._engine._releaseTexture(this._textures.data[i]);
  26604. }
  26605. this._textures.reset();
  26606. }
  26607. this.width = desiredWidth;
  26608. this.height = desiredHeight;
  26609. 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 }));
  26610. if (this._reusable) {
  26611. 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 }));
  26612. }
  26613. if (this.onSizeChanged) {
  26614. this.onSizeChanged();
  26615. }
  26616. }
  26617. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  26618. if (this.onActivate) {
  26619. this.onActivate(camera);
  26620. }
  26621. // Clear
  26622. if (this.clearColor) {
  26623. this._engine.clear(this.clearColor, true, true);
  26624. }
  26625. else {
  26626. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  26627. }
  26628. if (this._reusable) {
  26629. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  26630. }
  26631. };
  26632. Object.defineProperty(PostProcess.prototype, "isSupported", {
  26633. get: function () {
  26634. return this._effect.isSupported;
  26635. },
  26636. enumerable: true,
  26637. configurable: true
  26638. });
  26639. PostProcess.prototype.apply = function () {
  26640. // Check
  26641. if (!this._effect.isReady())
  26642. return null;
  26643. // States
  26644. this._engine.enableEffect(this._effect);
  26645. this._engine.setState(false);
  26646. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26647. this._engine.setDepthBuffer(false);
  26648. this._engine.setDepthWrite(false);
  26649. // Texture
  26650. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  26651. // Parameters
  26652. if (this.onApply) {
  26653. this.onApply(this._effect);
  26654. }
  26655. return this._effect;
  26656. };
  26657. PostProcess.prototype.dispose = function (camera) {
  26658. camera = camera || this._camera;
  26659. if (this._textures.length > 0) {
  26660. for (var i = 0; i < this._textures.length; i++) {
  26661. this._engine._releaseTexture(this._textures.data[i]);
  26662. }
  26663. this._textures.reset();
  26664. }
  26665. if (!camera) {
  26666. return;
  26667. }
  26668. camera.detachPostProcess(this);
  26669. var index = camera._postProcesses.indexOf(this);
  26670. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  26671. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  26672. }
  26673. };
  26674. return PostProcess;
  26675. })();
  26676. BABYLON.PostProcess = PostProcess;
  26677. })(BABYLON || (BABYLON = {}));
  26678. var BABYLON;
  26679. (function (BABYLON) {
  26680. var PostProcessManager = (function () {
  26681. function PostProcessManager(scene) {
  26682. this._vertexDeclaration = [2];
  26683. this._vertexStrideSize = 2 * 4;
  26684. this._scene = scene;
  26685. }
  26686. PostProcessManager.prototype._prepareBuffers = function () {
  26687. if (this._vertexBuffer) {
  26688. return;
  26689. }
  26690. // VBO
  26691. var vertices = [];
  26692. vertices.push(1, 1);
  26693. vertices.push(-1, 1);
  26694. vertices.push(-1, -1);
  26695. vertices.push(1, -1);
  26696. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  26697. // Indices
  26698. var indices = [];
  26699. indices.push(0);
  26700. indices.push(1);
  26701. indices.push(2);
  26702. indices.push(0);
  26703. indices.push(2);
  26704. indices.push(3);
  26705. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  26706. };
  26707. // Methods
  26708. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  26709. var postProcesses = this._scene.activeCamera._postProcesses;
  26710. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  26711. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  26712. return false;
  26713. }
  26714. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  26715. return true;
  26716. };
  26717. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  26718. var engine = this._scene.getEngine();
  26719. for (var index = 0; index < postProcesses.length; index++) {
  26720. if (index < postProcesses.length - 1) {
  26721. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  26722. }
  26723. else {
  26724. if (targetTexture) {
  26725. engine.bindFramebuffer(targetTexture);
  26726. }
  26727. else {
  26728. engine.restoreDefaultFramebuffer();
  26729. }
  26730. }
  26731. var pp = postProcesses[index];
  26732. var effect = pp.apply();
  26733. if (effect) {
  26734. if (pp.onBeforeRender) {
  26735. pp.onBeforeRender(effect);
  26736. }
  26737. // VBOs
  26738. this._prepareBuffers();
  26739. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  26740. // Draw order
  26741. engine.draw(true, 0, 6);
  26742. if (pp.onAfterRender) {
  26743. pp.onAfterRender(effect);
  26744. }
  26745. }
  26746. }
  26747. // Restore depth buffer
  26748. engine.setDepthBuffer(true);
  26749. engine.setDepthWrite(true);
  26750. };
  26751. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  26752. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  26753. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  26754. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  26755. return;
  26756. }
  26757. var engine = this._scene.getEngine();
  26758. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  26759. if (index < postProcessesTakenIndices.length - 1) {
  26760. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  26761. }
  26762. else {
  26763. if (targetTexture) {
  26764. engine.bindFramebuffer(targetTexture, faceIndex);
  26765. }
  26766. else {
  26767. engine.restoreDefaultFramebuffer();
  26768. }
  26769. }
  26770. if (doNotPresent) {
  26771. break;
  26772. }
  26773. var pp = postProcesses[postProcessesTakenIndices[index]];
  26774. var effect = pp.apply();
  26775. if (effect) {
  26776. if (pp.onBeforeRender) {
  26777. pp.onBeforeRender(effect);
  26778. }
  26779. // VBOs
  26780. this._prepareBuffers();
  26781. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  26782. // Draw order
  26783. engine.draw(true, 0, 6);
  26784. if (pp.onAfterRender) {
  26785. pp.onAfterRender(effect);
  26786. }
  26787. }
  26788. }
  26789. // Restore depth buffer
  26790. engine.setDepthBuffer(true);
  26791. engine.setDepthWrite(true);
  26792. };
  26793. PostProcessManager.prototype.dispose = function () {
  26794. if (this._vertexBuffer) {
  26795. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  26796. this._vertexBuffer = null;
  26797. }
  26798. if (this._indexBuffer) {
  26799. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26800. this._indexBuffer = null;
  26801. }
  26802. };
  26803. return PostProcessManager;
  26804. })();
  26805. BABYLON.PostProcessManager = PostProcessManager;
  26806. })(BABYLON || (BABYLON = {}));
  26807. var BABYLON;
  26808. (function (BABYLON) {
  26809. var PassPostProcess = (function (_super) {
  26810. __extends(PassPostProcess, _super);
  26811. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  26812. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  26813. }
  26814. return PassPostProcess;
  26815. })(BABYLON.PostProcess);
  26816. BABYLON.PassPostProcess = PassPostProcess;
  26817. })(BABYLON || (BABYLON = {}));
  26818. var BABYLON;
  26819. (function (BABYLON) {
  26820. /**
  26821. * This is a holder class for the physics joint created by the physics plugin.
  26822. * It holds a set of functions to control the underlying joint.
  26823. */
  26824. var PhysicsJoint = (function () {
  26825. function PhysicsJoint(type, jointData) {
  26826. this.type = type;
  26827. this.jointData = jointData;
  26828. jointData.nativeParams = jointData.nativeParams || {};
  26829. }
  26830. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  26831. get: function () {
  26832. return this._physicsJoint;
  26833. },
  26834. set: function (newJoint) {
  26835. if (this._physicsJoint) {
  26836. }
  26837. this._physicsJoint = newJoint;
  26838. },
  26839. enumerable: true,
  26840. configurable: true
  26841. });
  26842. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  26843. set: function (physicsPlugin) {
  26844. this._physicsPlugin = physicsPlugin;
  26845. },
  26846. enumerable: true,
  26847. configurable: true
  26848. });
  26849. /**
  26850. * Execute a function that is physics-plugin specific.
  26851. * @param {Function} func the function that will be executed.
  26852. * It accepts two parameters: the physics world and the physics joint.
  26853. */
  26854. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  26855. func(this._physicsPlugin.world, this._physicsJoint);
  26856. };
  26857. //TODO check if the native joints are the same
  26858. //Joint Types
  26859. PhysicsJoint.DistanceJoint = 0;
  26860. PhysicsJoint.HingeJoint = 1;
  26861. PhysicsJoint.BallAndSocketJoint = 2;
  26862. PhysicsJoint.WheelJoint = 3;
  26863. PhysicsJoint.SliderJoint = 4;
  26864. //OIMO
  26865. PhysicsJoint.PrismaticJoint = 5;
  26866. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  26867. PhysicsJoint.UniversalJoint = 6;
  26868. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  26869. //Cannon
  26870. //Similar to a Ball-Joint. Different in params
  26871. PhysicsJoint.PointToPointJoint = 8;
  26872. //Cannon only at the moment
  26873. PhysicsJoint.SpringJoint = 9;
  26874. return PhysicsJoint;
  26875. })();
  26876. BABYLON.PhysicsJoint = PhysicsJoint;
  26877. /**
  26878. * A class representing a physics distance joint.
  26879. */
  26880. var DistanceJoint = (function (_super) {
  26881. __extends(DistanceJoint, _super);
  26882. function DistanceJoint(jointData) {
  26883. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  26884. }
  26885. /**
  26886. * Update the predefined distance.
  26887. */
  26888. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  26889. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  26890. };
  26891. return DistanceJoint;
  26892. })(PhysicsJoint);
  26893. BABYLON.DistanceJoint = DistanceJoint;
  26894. /**
  26895. * This class represents a single hinge physics joint
  26896. */
  26897. var HingeJoint = (function (_super) {
  26898. __extends(HingeJoint, _super);
  26899. function HingeJoint(jointData) {
  26900. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  26901. }
  26902. /**
  26903. * Set the motor values.
  26904. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26905. * @param {number} force the force to apply
  26906. * @param {number} maxForce max force for this motor.
  26907. */
  26908. HingeJoint.prototype.setMotor = function (force, maxForce) {
  26909. this._physicsPlugin.setMotor(this, force, maxForce);
  26910. };
  26911. /**
  26912. * Set the motor's limits.
  26913. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26914. */
  26915. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  26916. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  26917. };
  26918. return HingeJoint;
  26919. })(PhysicsJoint);
  26920. BABYLON.HingeJoint = HingeJoint;
  26921. /**
  26922. * This class represents a dual hinge physics joint (same as wheel joint)
  26923. */
  26924. var Hinge2Joint = (function (_super) {
  26925. __extends(Hinge2Joint, _super);
  26926. function Hinge2Joint(jointData) {
  26927. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  26928. }
  26929. /**
  26930. * Set the motor values.
  26931. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26932. * @param {number} force the force to apply
  26933. * @param {number} maxForce max force for this motor.
  26934. * @param {motorIndex} the motor's index, 0 or 1.
  26935. */
  26936. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  26937. if (motorIndex === void 0) { motorIndex = 0; }
  26938. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  26939. };
  26940. /**
  26941. * Set the motor limits.
  26942. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26943. * @param {number} upperLimit the upper limit
  26944. * @param {number} lowerLimit lower limit
  26945. * @param {motorIndex} the motor's index, 0 or 1.
  26946. */
  26947. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  26948. if (motorIndex === void 0) { motorIndex = 0; }
  26949. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  26950. };
  26951. return Hinge2Joint;
  26952. })(PhysicsJoint);
  26953. BABYLON.Hinge2Joint = Hinge2Joint;
  26954. })(BABYLON || (BABYLON = {}));
  26955. var BABYLON;
  26956. (function (BABYLON) {
  26957. var PhysicsImpostor = (function () {
  26958. function PhysicsImpostor(object, type, _options, _scene) {
  26959. var _this = this;
  26960. if (_options === void 0) { _options = { mass: 0 }; }
  26961. this.object = object;
  26962. this.type = type;
  26963. this._options = _options;
  26964. this._scene = _scene;
  26965. this._bodyUpdateRequired = false;
  26966. this._onBeforePhysicsStepCallbacks = new Array();
  26967. this._onAfterPhysicsStepCallbacks = new Array();
  26968. this._onPhysicsCollideCallbacks = [];
  26969. this._deltaPosition = BABYLON.Vector3.Zero();
  26970. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  26971. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  26972. /**
  26973. * this function is executed by the physics engine.
  26974. */
  26975. this.beforeStep = function () {
  26976. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  26977. //conjugate deltaRotation
  26978. if (_this._deltaRotationConjugated) {
  26979. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  26980. }
  26981. else {
  26982. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  26983. }
  26984. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  26985. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  26986. func(_this);
  26987. });
  26988. };
  26989. /**
  26990. * this function is executed by the physics engine.
  26991. */
  26992. this.afterStep = function () {
  26993. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  26994. func(_this);
  26995. });
  26996. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  26997. _this.object.position.addInPlace(_this._deltaPosition);
  26998. if (_this._deltaRotation) {
  26999. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  27000. }
  27001. };
  27002. //event and body object due to cannon's event-based architecture.
  27003. this.onCollide = function (e) {
  27004. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  27005. if (otherImpostor) {
  27006. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  27007. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  27008. }).forEach(function (obj) {
  27009. obj.callback(_this, otherImpostor);
  27010. });
  27011. }
  27012. };
  27013. //sanity check!
  27014. if (!this.object) {
  27015. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  27016. return;
  27017. }
  27018. //legacy support for old syntax.
  27019. if (!this._scene && object.getScene) {
  27020. this._scene = object.getScene();
  27021. }
  27022. this._physicsEngine = this._scene.getPhysicsEngine();
  27023. if (!this._physicsEngine) {
  27024. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  27025. }
  27026. else {
  27027. //set the object's quaternion, if not set
  27028. if (!this.object.rotationQuaternion) {
  27029. if (this.object.rotation) {
  27030. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  27031. }
  27032. else {
  27033. this.object.rotationQuaternion = new BABYLON.Quaternion();
  27034. }
  27035. }
  27036. //default options params
  27037. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  27038. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  27039. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  27040. this._joints = [];
  27041. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  27042. if (!this.object.parent) {
  27043. this._init();
  27044. }
  27045. }
  27046. }
  27047. /**
  27048. * This function will completly initialize this impostor.
  27049. * It will create a new body - but only if this mesh has no parent.
  27050. * If it has, this impostor will not be used other than to define the impostor
  27051. * of the child mesh.
  27052. */
  27053. PhysicsImpostor.prototype._init = function () {
  27054. this._physicsEngine.removeImpostor(this);
  27055. this.physicsBody = null;
  27056. this._parent = this._parent || this._getPhysicsParent();
  27057. if (!this.parent) {
  27058. this._physicsEngine.addImpostor(this);
  27059. }
  27060. };
  27061. PhysicsImpostor.prototype._getPhysicsParent = function () {
  27062. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  27063. var parentMesh = this.object.parent;
  27064. return parentMesh.physicsImpostor;
  27065. }
  27066. return;
  27067. };
  27068. /**
  27069. * Should a new body be generated.
  27070. */
  27071. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  27072. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  27073. };
  27074. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  27075. this.forceUpdate();
  27076. };
  27077. /**
  27078. * Force a regeneration of this or the parent's impostor's body.
  27079. * Use under cautious - This will remove all joints already implemented.
  27080. */
  27081. PhysicsImpostor.prototype.forceUpdate = function () {
  27082. this._init();
  27083. if (this.parent) {
  27084. this.parent.forceUpdate();
  27085. }
  27086. };
  27087. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  27088. /*public get mesh(): AbstractMesh {
  27089. return this._mesh;
  27090. }*/
  27091. /**
  27092. * Gets the body that holds this impostor. Either its own, or its parent.
  27093. */
  27094. get: function () {
  27095. return this._parent ? this._parent.physicsBody : this._physicsBody;
  27096. },
  27097. /**
  27098. * Set the physics body. Used mainly by the physics engine/plugin
  27099. */
  27100. set: function (physicsBody) {
  27101. if (this._physicsBody) {
  27102. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  27103. }
  27104. this._physicsBody = physicsBody;
  27105. this.resetUpdateFlags();
  27106. },
  27107. enumerable: true,
  27108. configurable: true
  27109. });
  27110. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  27111. get: function () {
  27112. return this._parent;
  27113. },
  27114. enumerable: true,
  27115. configurable: true
  27116. });
  27117. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  27118. this._bodyUpdateRequired = false;
  27119. };
  27120. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  27121. if (this.object.getBoundingInfo) {
  27122. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  27123. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  27124. }
  27125. else {
  27126. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  27127. }
  27128. };
  27129. PhysicsImpostor.prototype.getObjectCenter = function () {
  27130. if (this.object.getBoundingInfo) {
  27131. return this.object.getBoundingInfo().boundingBox.center;
  27132. }
  27133. else {
  27134. return this.object.position;
  27135. }
  27136. };
  27137. /**
  27138. * Get a specific parametes from the options parameter.
  27139. */
  27140. PhysicsImpostor.prototype.getParam = function (paramName) {
  27141. return this._options[paramName];
  27142. };
  27143. /**
  27144. * Sets a specific parameter in the options given to the physics plugin
  27145. */
  27146. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  27147. this._options[paramName] = value;
  27148. this._bodyUpdateRequired = true;
  27149. };
  27150. /**
  27151. * Specifically change the body's mass option. Won't recreate the physics body object
  27152. */
  27153. PhysicsImpostor.prototype.setMass = function (mass) {
  27154. if (this.getParam("mass") !== mass) {
  27155. this.setParam("mass", mass);
  27156. }
  27157. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  27158. };
  27159. PhysicsImpostor.prototype.getLinearVelocity = function () {
  27160. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  27161. };
  27162. /**
  27163. * Set the body's linear velocity.
  27164. */
  27165. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  27166. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  27167. };
  27168. PhysicsImpostor.prototype.getAngularVelocity = function () {
  27169. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  27170. };
  27171. /**
  27172. * Set the body's linear velocity.
  27173. */
  27174. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  27175. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  27176. };
  27177. /**
  27178. * Execute a function with the physics plugin native code.
  27179. * Provide a function the will have two variables - the world object and the physics body object.
  27180. */
  27181. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  27182. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  27183. };
  27184. /**
  27185. * Register a function that will be executed before the physics world is stepping forward.
  27186. */
  27187. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  27188. this._onBeforePhysicsStepCallbacks.push(func);
  27189. };
  27190. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  27191. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  27192. if (index > -1) {
  27193. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  27194. }
  27195. else {
  27196. BABYLON.Tools.Warn("Function to remove was not found");
  27197. }
  27198. };
  27199. /**
  27200. * Register a function that will be executed after the physics step
  27201. */
  27202. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  27203. this._onAfterPhysicsStepCallbacks.push(func);
  27204. };
  27205. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  27206. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  27207. if (index > -1) {
  27208. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  27209. }
  27210. else {
  27211. BABYLON.Tools.Warn("Function to remove was not found");
  27212. }
  27213. };
  27214. /**
  27215. * register a function that will be executed when this impostor collides against a different body.
  27216. */
  27217. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  27218. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  27219. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  27220. };
  27221. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  27222. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  27223. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  27224. if (index > -1) {
  27225. this._onPhysicsCollideCallbacks.splice(index, 1);
  27226. }
  27227. else {
  27228. BABYLON.Tools.Warn("Function to remove was not found");
  27229. }
  27230. };
  27231. /**
  27232. * Apply a force
  27233. */
  27234. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  27235. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  27236. };
  27237. /**
  27238. * Apply an impulse
  27239. */
  27240. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  27241. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  27242. };
  27243. /**
  27244. * A help function to create a joint.
  27245. */
  27246. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  27247. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  27248. this.addJoint(otherImpostor, joint);
  27249. };
  27250. /**
  27251. * Add a joint to this impostor with a different impostor.
  27252. */
  27253. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  27254. this._joints.push({
  27255. otherImpostor: otherImpostor,
  27256. joint: joint
  27257. });
  27258. this._physicsEngine.addJoint(this, otherImpostor, joint);
  27259. };
  27260. /**
  27261. * Will keep this body still, in a sleep mode.
  27262. */
  27263. PhysicsImpostor.prototype.sleep = function () {
  27264. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  27265. };
  27266. /**
  27267. * Wake the body up.
  27268. */
  27269. PhysicsImpostor.prototype.wakeUp = function () {
  27270. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  27271. };
  27272. PhysicsImpostor.prototype.clone = function (newObject) {
  27273. if (!newObject)
  27274. return null;
  27275. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  27276. };
  27277. PhysicsImpostor.prototype.dispose = function () {
  27278. var _this = this;
  27279. this._joints.forEach(function (j) {
  27280. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  27281. });
  27282. //dispose the physics body
  27283. this._physicsEngine.removeImpostor(this);
  27284. if (this.parent) {
  27285. this.parent.forceUpdate();
  27286. }
  27287. else {
  27288. }
  27289. };
  27290. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  27291. this._deltaPosition.copyFrom(position);
  27292. };
  27293. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  27294. if (!this._deltaRotation) {
  27295. this._deltaRotation = new BABYLON.Quaternion();
  27296. }
  27297. this._deltaRotation.copyFrom(rotation);
  27298. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  27299. };
  27300. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  27301. //Impostor types
  27302. PhysicsImpostor.NoImpostor = 0;
  27303. PhysicsImpostor.SphereImpostor = 1;
  27304. PhysicsImpostor.BoxImpostor = 2;
  27305. PhysicsImpostor.PlaneImpostor = 3;
  27306. PhysicsImpostor.MeshImpostor = 4;
  27307. PhysicsImpostor.CylinderImpostor = 7;
  27308. PhysicsImpostor.ParticleImpostor = 8;
  27309. PhysicsImpostor.HeightmapImpostor = 9;
  27310. return PhysicsImpostor;
  27311. })();
  27312. BABYLON.PhysicsImpostor = PhysicsImpostor;
  27313. })(BABYLON || (BABYLON = {}));
  27314. var BABYLON;
  27315. (function (BABYLON) {
  27316. var PhysicsEngine = (function () {
  27317. function PhysicsEngine(gravity, _physicsPlugin) {
  27318. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  27319. this._physicsPlugin = _physicsPlugin;
  27320. //new methods and parameters
  27321. this._impostors = [];
  27322. this._joints = [];
  27323. if (!this._physicsPlugin.isSupported()) {
  27324. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  27325. + "Please make sure it is included.");
  27326. }
  27327. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  27328. this.setGravity(gravity);
  27329. this.setTimeStep();
  27330. }
  27331. PhysicsEngine.prototype.setGravity = function (gravity) {
  27332. this.gravity = gravity;
  27333. this._physicsPlugin.setGravity(this.gravity);
  27334. };
  27335. /**
  27336. * Set the time step of the physics engine.
  27337. * default is 1/60.
  27338. * To slow it down, enter 1/600 for example.
  27339. * To speed it up, 1/30
  27340. * @param {number} newTimeStep the new timestep to apply to this world.
  27341. */
  27342. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  27343. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  27344. this._physicsPlugin.setTimeStep(newTimeStep);
  27345. };
  27346. PhysicsEngine.prototype.dispose = function () {
  27347. this._impostors.forEach(function (impostor) {
  27348. impostor.dispose();
  27349. });
  27350. this._physicsPlugin.dispose();
  27351. };
  27352. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  27353. return this._physicsPlugin.name;
  27354. };
  27355. /**
  27356. * Adding a new impostor for the impostor tracking.
  27357. * This will be done by the impostor itself.
  27358. * @param {PhysicsImpostor} impostor the impostor to add
  27359. */
  27360. PhysicsEngine.prototype.addImpostor = function (impostor) {
  27361. impostor.uniqueId = this._impostors.push(impostor);
  27362. //if no parent, generate the body
  27363. if (!impostor.parent) {
  27364. this._physicsPlugin.generatePhysicsBody(impostor);
  27365. }
  27366. };
  27367. /**
  27368. * Remove an impostor from the engine.
  27369. * This impostor and its mesh will not longer be updated by the physics engine.
  27370. * @param {PhysicsImpostor} impostor the impostor to remove
  27371. */
  27372. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  27373. var index = this._impostors.indexOf(impostor);
  27374. if (index > -1) {
  27375. var removed = this._impostors.splice(index, 1);
  27376. //Is it needed?
  27377. if (removed.length) {
  27378. //this will also remove it from the world.
  27379. removed[0].physicsBody = null;
  27380. }
  27381. }
  27382. };
  27383. /**
  27384. * Add a joint to the physics engine
  27385. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  27386. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  27387. * @param {PhysicsJoint} the joint that will connect both impostors.
  27388. */
  27389. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  27390. var impostorJoint = {
  27391. mainImpostor: mainImpostor,
  27392. connectedImpostor: connectedImpostor,
  27393. joint: joint
  27394. };
  27395. joint.physicsPlugin = this._physicsPlugin;
  27396. this._joints.push(impostorJoint);
  27397. this._physicsPlugin.generateJoint(impostorJoint);
  27398. };
  27399. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  27400. var matchingJoints = this._joints.filter(function (impostorJoint) {
  27401. return (impostorJoint.connectedImpostor === connectedImpostor
  27402. && impostorJoint.joint === joint
  27403. && impostorJoint.mainImpostor === mainImpostor);
  27404. });
  27405. if (matchingJoints.length) {
  27406. this._physicsPlugin.removeJoint(matchingJoints[0]);
  27407. }
  27408. };
  27409. /**
  27410. * Called by the scene. no need to call it.
  27411. */
  27412. PhysicsEngine.prototype._step = function (delta) {
  27413. var _this = this;
  27414. //check if any mesh has no body / requires an update
  27415. this._impostors.forEach(function (impostor) {
  27416. if (impostor.isBodyInitRequired()) {
  27417. _this._physicsPlugin.generatePhysicsBody(impostor);
  27418. }
  27419. });
  27420. if (delta > 0.1) {
  27421. delta = 0.1;
  27422. }
  27423. else if (delta <= 0) {
  27424. delta = 1.0 / 60.0;
  27425. }
  27426. this._physicsPlugin.executeStep(delta, this._impostors);
  27427. };
  27428. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  27429. return this._physicsPlugin;
  27430. };
  27431. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  27432. for (var i = 0; i < this._impostors.length; ++i) {
  27433. if (this._impostors[i].object === object) {
  27434. return this._impostors[i];
  27435. }
  27436. }
  27437. };
  27438. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  27439. for (var i = 0; i < this._impostors.length; ++i) {
  27440. if (this._impostors[i].physicsBody === body) {
  27441. return this._impostors[i];
  27442. }
  27443. }
  27444. };
  27445. // Statics, Legacy support.
  27446. /**
  27447. * @Deprecated
  27448. *
  27449. */
  27450. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  27451. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  27452. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  27453. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  27454. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  27455. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  27456. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  27457. PhysicsEngine.CapsuleImpostor = -1;
  27458. PhysicsEngine.ConeImpostor = -1;
  27459. PhysicsEngine.ConvexHullImpostor = -1;
  27460. PhysicsEngine.Epsilon = 0.001;
  27461. return PhysicsEngine;
  27462. })();
  27463. BABYLON.PhysicsEngine = PhysicsEngine;
  27464. })(BABYLON || (BABYLON = {}));
  27465. var BABYLON;
  27466. (function (BABYLON) {
  27467. var VertexData = (function () {
  27468. function VertexData() {
  27469. }
  27470. VertexData.prototype.set = function (data, kind) {
  27471. switch (kind) {
  27472. case BABYLON.VertexBuffer.PositionKind:
  27473. this.positions = data;
  27474. break;
  27475. case BABYLON.VertexBuffer.NormalKind:
  27476. this.normals = data;
  27477. break;
  27478. case BABYLON.VertexBuffer.UVKind:
  27479. this.uvs = data;
  27480. break;
  27481. case BABYLON.VertexBuffer.UV2Kind:
  27482. this.uvs2 = data;
  27483. break;
  27484. case BABYLON.VertexBuffer.UV3Kind:
  27485. this.uvs3 = data;
  27486. break;
  27487. case BABYLON.VertexBuffer.UV4Kind:
  27488. this.uvs4 = data;
  27489. break;
  27490. case BABYLON.VertexBuffer.UV5Kind:
  27491. this.uvs5 = data;
  27492. break;
  27493. case BABYLON.VertexBuffer.UV6Kind:
  27494. this.uvs6 = data;
  27495. break;
  27496. case BABYLON.VertexBuffer.ColorKind:
  27497. this.colors = data;
  27498. break;
  27499. case BABYLON.VertexBuffer.MatricesIndicesKind:
  27500. this.matricesIndices = data;
  27501. break;
  27502. case BABYLON.VertexBuffer.MatricesWeightsKind:
  27503. this.matricesWeights = data;
  27504. break;
  27505. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  27506. this.matricesIndicesExtra = data;
  27507. break;
  27508. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  27509. this.matricesWeightsExtra = data;
  27510. break;
  27511. }
  27512. };
  27513. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  27514. this._applyTo(mesh, updatable);
  27515. };
  27516. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  27517. this._applyTo(geometry, updatable);
  27518. };
  27519. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  27520. this._update(mesh);
  27521. };
  27522. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  27523. this._update(geometry);
  27524. };
  27525. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  27526. if (this.positions) {
  27527. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  27528. }
  27529. if (this.normals) {
  27530. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  27531. }
  27532. if (this.uvs) {
  27533. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  27534. }
  27535. if (this.uvs2) {
  27536. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  27537. }
  27538. if (this.uvs3) {
  27539. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  27540. }
  27541. if (this.uvs4) {
  27542. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  27543. }
  27544. if (this.uvs5) {
  27545. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  27546. }
  27547. if (this.uvs6) {
  27548. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  27549. }
  27550. if (this.colors) {
  27551. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  27552. }
  27553. if (this.matricesIndices) {
  27554. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  27555. }
  27556. if (this.matricesWeights) {
  27557. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  27558. }
  27559. if (this.matricesIndicesExtra) {
  27560. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  27561. }
  27562. if (this.matricesWeightsExtra) {
  27563. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  27564. }
  27565. if (this.indices) {
  27566. meshOrGeometry.setIndices(this.indices);
  27567. }
  27568. };
  27569. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  27570. if (this.positions) {
  27571. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  27572. }
  27573. if (this.normals) {
  27574. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  27575. }
  27576. if (this.uvs) {
  27577. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  27578. }
  27579. if (this.uvs2) {
  27580. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  27581. }
  27582. if (this.uvs3) {
  27583. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  27584. }
  27585. if (this.uvs4) {
  27586. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  27587. }
  27588. if (this.uvs5) {
  27589. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  27590. }
  27591. if (this.uvs6) {
  27592. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  27593. }
  27594. if (this.colors) {
  27595. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  27596. }
  27597. if (this.matricesIndices) {
  27598. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  27599. }
  27600. if (this.matricesWeights) {
  27601. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  27602. }
  27603. if (this.matricesIndicesExtra) {
  27604. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  27605. }
  27606. if (this.matricesWeightsExtra) {
  27607. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  27608. }
  27609. if (this.indices) {
  27610. meshOrGeometry.setIndices(this.indices);
  27611. }
  27612. };
  27613. VertexData.prototype.transform = function (matrix) {
  27614. var transformed = BABYLON.Vector3.Zero();
  27615. var index;
  27616. if (this.positions) {
  27617. var position = BABYLON.Vector3.Zero();
  27618. for (index = 0; index < this.positions.length; index += 3) {
  27619. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  27620. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  27621. this.positions[index] = transformed.x;
  27622. this.positions[index + 1] = transformed.y;
  27623. this.positions[index + 2] = transformed.z;
  27624. }
  27625. }
  27626. if (this.normals) {
  27627. var normal = BABYLON.Vector3.Zero();
  27628. for (index = 0; index < this.normals.length; index += 3) {
  27629. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  27630. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  27631. this.normals[index] = transformed.x;
  27632. this.normals[index + 1] = transformed.y;
  27633. this.normals[index + 2] = transformed.z;
  27634. }
  27635. }
  27636. };
  27637. VertexData.prototype.merge = function (other) {
  27638. if (other.indices) {
  27639. if (!this.indices) {
  27640. this.indices = [];
  27641. }
  27642. var offset = this.positions ? this.positions.length / 3 : 0;
  27643. for (var index = 0; index < other.indices.length; index++) {
  27644. //TODO check type - if Int32Array!
  27645. this.indices.push(other.indices[index] + offset);
  27646. }
  27647. }
  27648. this.positions = this._mergeElement(this.positions, other.positions);
  27649. this.normals = this._mergeElement(this.normals, other.normals);
  27650. this.uvs = this._mergeElement(this.uvs, other.uvs);
  27651. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  27652. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  27653. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  27654. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  27655. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  27656. this.colors = this._mergeElement(this.colors, other.colors);
  27657. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  27658. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  27659. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  27660. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  27661. };
  27662. VertexData.prototype._mergeElement = function (source, other) {
  27663. if (!other)
  27664. return source;
  27665. if (!source)
  27666. return other;
  27667. var len = other.length + source.length;
  27668. var isSrcTypedArray = source instanceof Float32Array;
  27669. var isOthTypedArray = other instanceof Float32Array;
  27670. // use non-loop method when the source is Float32Array
  27671. if (isSrcTypedArray) {
  27672. var ret32 = new Float32Array(len);
  27673. ret32.set(source);
  27674. ret32.set(other, source.length);
  27675. return ret32;
  27676. }
  27677. else if (!isOthTypedArray) {
  27678. return source.concat(other);
  27679. }
  27680. else {
  27681. var ret = source.slice(0); // copy source to a separate array
  27682. for (var i = 0, len = other.length; i < len; i++) {
  27683. ret.push(other[i]);
  27684. }
  27685. return ret;
  27686. }
  27687. };
  27688. VertexData.prototype.serialize = function () {
  27689. var serializationObject = this.serialize();
  27690. if (this.positions) {
  27691. serializationObject.positions = this.positions;
  27692. }
  27693. if (this.normals) {
  27694. serializationObject.normals = this.normals;
  27695. }
  27696. if (this.uvs) {
  27697. serializationObject.uvs = this.uvs;
  27698. }
  27699. if (this.uvs2) {
  27700. serializationObject.uvs2 = this.uvs2;
  27701. }
  27702. if (this.uvs3) {
  27703. serializationObject.uvs3 = this.uvs3;
  27704. }
  27705. if (this.uvs4) {
  27706. serializationObject.uvs4 = this.uvs4;
  27707. }
  27708. if (this.uvs5) {
  27709. serializationObject.uvs5 = this.uvs5;
  27710. }
  27711. if (this.uvs6) {
  27712. serializationObject.uvs6 = this.uvs6;
  27713. }
  27714. if (this.colors) {
  27715. serializationObject.colors = this.colors;
  27716. }
  27717. if (this.matricesIndices) {
  27718. serializationObject.matricesIndices = this.matricesIndices;
  27719. serializationObject.matricesIndices._isExpanded = true;
  27720. }
  27721. if (this.matricesWeights) {
  27722. serializationObject.matricesWeights = this.matricesWeights;
  27723. }
  27724. if (this.matricesIndicesExtra) {
  27725. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  27726. serializationObject.matricesIndicesExtra._isExpanded = true;
  27727. }
  27728. if (this.matricesWeightsExtra) {
  27729. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  27730. }
  27731. serializationObject.indices = this.indices;
  27732. return serializationObject;
  27733. };
  27734. // Statics
  27735. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  27736. return VertexData._ExtractFrom(mesh, copyWhenShared);
  27737. };
  27738. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  27739. return VertexData._ExtractFrom(geometry, copyWhenShared);
  27740. };
  27741. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  27742. var result = new VertexData();
  27743. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27744. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  27745. }
  27746. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27747. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  27748. }
  27749. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27750. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  27751. }
  27752. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27753. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  27754. }
  27755. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27756. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  27757. }
  27758. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27759. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  27760. }
  27761. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27762. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  27763. }
  27764. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27765. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  27766. }
  27767. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27768. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  27769. }
  27770. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27771. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  27772. }
  27773. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27774. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  27775. }
  27776. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  27777. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  27778. }
  27779. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  27780. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  27781. }
  27782. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  27783. return result;
  27784. };
  27785. VertexData.CreateRibbon = function (options) {
  27786. var pathArray = options.pathArray;
  27787. var closeArray = options.closeArray || false;
  27788. var closePath = options.closePath || false;
  27789. var defaultOffset = Math.floor(pathArray[0].length / 2);
  27790. var offset = options.offset || defaultOffset;
  27791. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  27792. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27793. var positions = [];
  27794. var indices = [];
  27795. var normals = [];
  27796. var uvs = [];
  27797. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  27798. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  27799. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  27800. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  27801. var minlg; // minimal length among all paths from pathArray
  27802. var lg = []; // array of path lengths : nb of vertex per path
  27803. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  27804. var p; // path iterator
  27805. var i; // point iterator
  27806. var j; // point iterator
  27807. // if single path in pathArray
  27808. if (pathArray.length < 2) {
  27809. var ar1 = [];
  27810. var ar2 = [];
  27811. for (i = 0; i < pathArray[0].length - offset; i++) {
  27812. ar1.push(pathArray[0][i]);
  27813. ar2.push(pathArray[0][i + offset]);
  27814. }
  27815. pathArray = [ar1, ar2];
  27816. }
  27817. // positions and horizontal distances (u)
  27818. var idc = 0;
  27819. var closePathCorr = (closePath) ? 1 : 0;
  27820. var path;
  27821. var l;
  27822. minlg = pathArray[0].length;
  27823. var vectlg;
  27824. var dist;
  27825. for (p = 0; p < pathArray.length; p++) {
  27826. uTotalDistance[p] = 0;
  27827. us[p] = [0];
  27828. path = pathArray[p];
  27829. l = path.length;
  27830. minlg = (minlg < l) ? minlg : l;
  27831. j = 0;
  27832. while (j < l) {
  27833. positions.push(path[j].x, path[j].y, path[j].z);
  27834. if (j > 0) {
  27835. vectlg = path[j].subtract(path[j - 1]).length();
  27836. dist = vectlg + uTotalDistance[p];
  27837. us[p].push(dist);
  27838. uTotalDistance[p] = dist;
  27839. }
  27840. j++;
  27841. }
  27842. if (closePath) {
  27843. j--;
  27844. positions.push(path[0].x, path[0].y, path[0].z);
  27845. vectlg = path[j].subtract(path[0]).length();
  27846. dist = vectlg + uTotalDistance[p];
  27847. us[p].push(dist);
  27848. uTotalDistance[p] = dist;
  27849. }
  27850. lg[p] = l + closePathCorr;
  27851. idx[p] = idc;
  27852. idc += (l + closePathCorr);
  27853. }
  27854. // vertical distances (v)
  27855. var path1;
  27856. var path2;
  27857. var vertex1;
  27858. var vertex2;
  27859. for (i = 0; i < minlg + closePathCorr; i++) {
  27860. vTotalDistance[i] = 0;
  27861. vs[i] = [0];
  27862. for (p = 0; p < pathArray.length - 1; p++) {
  27863. path1 = pathArray[p];
  27864. path2 = pathArray[p + 1];
  27865. if (i === minlg) {
  27866. vertex1 = path1[0];
  27867. vertex2 = path2[0];
  27868. }
  27869. else {
  27870. vertex1 = path1[i];
  27871. vertex2 = path2[i];
  27872. }
  27873. vectlg = vertex2.subtract(vertex1).length();
  27874. dist = vectlg + vTotalDistance[i];
  27875. vs[i].push(dist);
  27876. vTotalDistance[i] = dist;
  27877. }
  27878. if (closeArray) {
  27879. path1 = pathArray[p];
  27880. path2 = pathArray[0];
  27881. if (i === minlg) {
  27882. vertex2 = path2[0];
  27883. }
  27884. vectlg = vertex2.subtract(vertex1).length();
  27885. dist = vectlg + vTotalDistance[i];
  27886. vTotalDistance[i] = dist;
  27887. }
  27888. }
  27889. // uvs
  27890. var u;
  27891. var v;
  27892. for (p = 0; p < pathArray.length; p++) {
  27893. for (i = 0; i < minlg + closePathCorr; i++) {
  27894. u = us[p][i] / uTotalDistance[p];
  27895. v = vs[i][p] / vTotalDistance[i];
  27896. uvs.push(u, v);
  27897. }
  27898. }
  27899. // indices
  27900. p = 0; // path index
  27901. var pi = 0; // positions array index
  27902. var l1 = lg[p] - 1; // path1 length
  27903. var l2 = lg[p + 1] - 1; // path2 length
  27904. var min = (l1 < l2) ? l1 : l2; // current path stop index
  27905. var shft = idx[1] - idx[0]; // shift
  27906. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  27907. while (pi <= min && p < path1nb) {
  27908. // 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
  27909. indices.push(pi, pi + shft, pi + 1);
  27910. indices.push(pi + shft + 1, pi + 1, pi + shft);
  27911. pi += 1;
  27912. if (pi === min) {
  27913. p++;
  27914. if (p === lg.length - 1) {
  27915. shft = idx[0] - idx[p];
  27916. l1 = lg[p] - 1;
  27917. l2 = lg[0] - 1;
  27918. }
  27919. else {
  27920. shft = idx[p + 1] - idx[p];
  27921. l1 = lg[p] - 1;
  27922. l2 = lg[p + 1] - 1;
  27923. }
  27924. pi = idx[p];
  27925. min = (l1 < l2) ? l1 + pi : l2 + pi;
  27926. }
  27927. }
  27928. // normals
  27929. VertexData.ComputeNormals(positions, indices, normals);
  27930. if (closePath) {
  27931. var indexFirst = 0;
  27932. var indexLast = 0;
  27933. for (p = 0; p < pathArray.length; p++) {
  27934. indexFirst = idx[p] * 3;
  27935. if (p + 1 < pathArray.length) {
  27936. indexLast = (idx[p + 1] - 1) * 3;
  27937. }
  27938. else {
  27939. indexLast = normals.length - 3;
  27940. }
  27941. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  27942. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  27943. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  27944. normals[indexLast] = normals[indexFirst];
  27945. normals[indexLast + 1] = normals[indexFirst + 1];
  27946. normals[indexLast + 2] = normals[indexFirst + 2];
  27947. }
  27948. }
  27949. // sides
  27950. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27951. // Result
  27952. var vertexData = new VertexData();
  27953. vertexData.indices = indices;
  27954. vertexData.positions = positions;
  27955. vertexData.normals = normals;
  27956. vertexData.uvs = uvs;
  27957. if (closePath) {
  27958. vertexData._idx = idx;
  27959. }
  27960. return vertexData;
  27961. };
  27962. VertexData.CreateBox = function (options) {
  27963. var normalsSource = [
  27964. new BABYLON.Vector3(0, 0, 1),
  27965. new BABYLON.Vector3(0, 0, -1),
  27966. new BABYLON.Vector3(1, 0, 0),
  27967. new BABYLON.Vector3(-1, 0, 0),
  27968. new BABYLON.Vector3(0, 1, 0),
  27969. new BABYLON.Vector3(0, -1, 0)
  27970. ];
  27971. var indices = [];
  27972. var positions = [];
  27973. var normals = [];
  27974. var uvs = [];
  27975. var width = options.width || options.size || 1;
  27976. var height = options.height || options.size || 1;
  27977. var depth = options.depth || options.size || 1;
  27978. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27979. var faceUV = options.faceUV || new Array(6);
  27980. var faceColors = options.faceColors;
  27981. var colors = [];
  27982. // default face colors and UV if undefined
  27983. for (var f = 0; f < 6; f++) {
  27984. if (faceUV[f] === undefined) {
  27985. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27986. }
  27987. if (faceColors && faceColors[f] === undefined) {
  27988. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27989. }
  27990. }
  27991. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  27992. // Create each face in turn.
  27993. for (var index = 0; index < normalsSource.length; index++) {
  27994. var normal = normalsSource[index];
  27995. // Get two vectors perpendicular to the face normal and to each other.
  27996. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  27997. var side2 = BABYLON.Vector3.Cross(normal, side1);
  27998. // Six indices (two triangles) per face.
  27999. var verticesLength = positions.length / 3;
  28000. indices.push(verticesLength);
  28001. indices.push(verticesLength + 1);
  28002. indices.push(verticesLength + 2);
  28003. indices.push(verticesLength);
  28004. indices.push(verticesLength + 2);
  28005. indices.push(verticesLength + 3);
  28006. // Four vertices per face.
  28007. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  28008. positions.push(vertex.x, vertex.y, vertex.z);
  28009. normals.push(normal.x, normal.y, normal.z);
  28010. uvs.push(faceUV[index].z, faceUV[index].w);
  28011. if (faceColors) {
  28012. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28013. }
  28014. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  28015. positions.push(vertex.x, vertex.y, vertex.z);
  28016. normals.push(normal.x, normal.y, normal.z);
  28017. uvs.push(faceUV[index].x, faceUV[index].w);
  28018. if (faceColors) {
  28019. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28020. }
  28021. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  28022. positions.push(vertex.x, vertex.y, vertex.z);
  28023. normals.push(normal.x, normal.y, normal.z);
  28024. uvs.push(faceUV[index].x, faceUV[index].y);
  28025. if (faceColors) {
  28026. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28027. }
  28028. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  28029. positions.push(vertex.x, vertex.y, vertex.z);
  28030. normals.push(normal.x, normal.y, normal.z);
  28031. uvs.push(faceUV[index].z, faceUV[index].y);
  28032. if (faceColors) {
  28033. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28034. }
  28035. }
  28036. // sides
  28037. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28038. // Result
  28039. var vertexData = new VertexData();
  28040. vertexData.indices = indices;
  28041. vertexData.positions = positions;
  28042. vertexData.normals = normals;
  28043. vertexData.uvs = uvs;
  28044. if (faceColors) {
  28045. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28046. vertexData.colors = totalColors;
  28047. }
  28048. return vertexData;
  28049. };
  28050. VertexData.CreateSphere = function (options) {
  28051. var segments = options.segments || 32;
  28052. var diameterX = options.diameterX || options.diameter || 1;
  28053. var diameterY = options.diameterY || options.diameter || 1;
  28054. var diameterZ = options.diameterZ || options.diameter || 1;
  28055. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28056. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  28057. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28058. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  28059. var totalZRotationSteps = 2 + segments;
  28060. var totalYRotationSteps = 2 * totalZRotationSteps;
  28061. var indices = [];
  28062. var positions = [];
  28063. var normals = [];
  28064. var uvs = [];
  28065. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  28066. var normalizedZ = zRotationStep / totalZRotationSteps;
  28067. var angleZ = normalizedZ * Math.PI * slice;
  28068. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  28069. var normalizedY = yRotationStep / totalYRotationSteps;
  28070. var angleY = normalizedY * Math.PI * 2 * arc;
  28071. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  28072. var rotationY = BABYLON.Matrix.RotationY(angleY);
  28073. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  28074. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  28075. var vertex = complete.multiply(radius);
  28076. var normal = complete.divide(radius).normalize();
  28077. positions.push(vertex.x, vertex.y, vertex.z);
  28078. normals.push(normal.x, normal.y, normal.z);
  28079. uvs.push(normalizedY, normalizedZ);
  28080. }
  28081. if (zRotationStep > 0) {
  28082. var verticesCount = positions.length / 3;
  28083. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  28084. indices.push((firstIndex));
  28085. indices.push((firstIndex + 1));
  28086. indices.push(firstIndex + totalYRotationSteps + 1);
  28087. indices.push((firstIndex + totalYRotationSteps + 1));
  28088. indices.push((firstIndex + 1));
  28089. indices.push((firstIndex + totalYRotationSteps + 2));
  28090. }
  28091. }
  28092. }
  28093. // Sides
  28094. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28095. // Result
  28096. var vertexData = new VertexData();
  28097. vertexData.indices = indices;
  28098. vertexData.positions = positions;
  28099. vertexData.normals = normals;
  28100. vertexData.uvs = uvs;
  28101. return vertexData;
  28102. };
  28103. // Cylinder and cone
  28104. VertexData.CreateCylinder = function (options) {
  28105. var height = options.height || 2;
  28106. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  28107. var diameterBottom = options.diameterBottom || options.diameter || 1;
  28108. var tessellation = options.tessellation || 24;
  28109. var subdivisions = options.subdivisions || 1;
  28110. var hasRings = options.hasRings;
  28111. var enclose = options.enclose;
  28112. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28113. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28114. var faceUV = options.faceUV || new Array(3);
  28115. var faceColors = options.faceColors;
  28116. // default face colors and UV if undefined
  28117. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  28118. var ringNb = (hasRings) ? subdivisions : 1;
  28119. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  28120. var f;
  28121. for (f = 0; f < surfaceNb; f++) {
  28122. if (faceColors && faceColors[f] === undefined) {
  28123. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28124. }
  28125. }
  28126. for (f = 0; f < surfaceNb; f++) {
  28127. if (faceUV && faceUV[f] === undefined) {
  28128. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28129. }
  28130. }
  28131. var indices = [];
  28132. var positions = [];
  28133. var normals = [];
  28134. var uvs = [];
  28135. var colors = [];
  28136. var angle_step = Math.PI * 2 * arc / tessellation;
  28137. var angle;
  28138. var h;
  28139. var radius;
  28140. var tan = (diameterBottom - diameterTop) / 2 / height;
  28141. var ringVertex = BABYLON.Vector3.Zero();
  28142. var ringNormal = BABYLON.Vector3.Zero();
  28143. var ringFirstVertex = BABYLON.Vector3.Zero();
  28144. var ringFirstNormal = BABYLON.Vector3.Zero();
  28145. var quadNormal = BABYLON.Vector3.Zero();
  28146. var Y = BABYLON.Axis.Y;
  28147. // positions, normals, uvs
  28148. var i;
  28149. var j;
  28150. var r;
  28151. var ringIdx = 1;
  28152. var s = 1; // surface index
  28153. var cs = 0;
  28154. var v = 0;
  28155. for (i = 0; i <= subdivisions; i++) {
  28156. h = i / subdivisions;
  28157. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  28158. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  28159. for (r = 0; r < ringIdx; r++) {
  28160. if (hasRings) {
  28161. s += r;
  28162. }
  28163. if (enclose) {
  28164. s += 2 * r;
  28165. }
  28166. for (j = 0; j <= tessellation; j++) {
  28167. angle = j * angle_step;
  28168. // position
  28169. ringVertex.x = Math.cos(-angle) * radius;
  28170. ringVertex.y = -height / 2 + h * height;
  28171. ringVertex.z = Math.sin(-angle) * radius;
  28172. // normal
  28173. if (diameterTop === 0 && i === subdivisions) {
  28174. // if no top cap, reuse former normals
  28175. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  28176. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  28177. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  28178. }
  28179. else {
  28180. ringNormal.x = ringVertex.x;
  28181. ringNormal.z = ringVertex.z;
  28182. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  28183. ringNormal.normalize();
  28184. }
  28185. // keep first ring vertex values for enclose
  28186. if (j === 0) {
  28187. ringFirstVertex.copyFrom(ringVertex);
  28188. ringFirstNormal.copyFrom(ringNormal);
  28189. }
  28190. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28191. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  28192. if (hasRings) {
  28193. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  28194. }
  28195. else {
  28196. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  28197. }
  28198. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  28199. if (faceColors) {
  28200. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  28201. }
  28202. }
  28203. // if enclose, add four vertices and their dedicated normals
  28204. if (arc !== 1 && enclose) {
  28205. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28206. positions.push(0, ringVertex.y, 0);
  28207. positions.push(0, ringVertex.y, 0);
  28208. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  28209. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  28210. quadNormal.normalize();
  28211. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28212. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  28213. quadNormal.normalize();
  28214. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28215. if (hasRings) {
  28216. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  28217. }
  28218. else {
  28219. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  28220. }
  28221. uvs.push(faceUV[s + 1].x, v);
  28222. uvs.push(faceUV[s + 1].z, v);
  28223. if (hasRings) {
  28224. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  28225. }
  28226. else {
  28227. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  28228. }
  28229. uvs.push(faceUV[s + 2].x, v);
  28230. uvs.push(faceUV[s + 2].z, v);
  28231. if (faceColors) {
  28232. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28233. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28234. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28235. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28236. }
  28237. }
  28238. if (cs !== s) {
  28239. cs = s;
  28240. }
  28241. }
  28242. }
  28243. // indices
  28244. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  28245. var s;
  28246. i = 0;
  28247. for (s = 0; s < subdivisions; s++) {
  28248. for (j = 0; j < tessellation; j++) {
  28249. var i0 = i * (e + 1) + j;
  28250. var i1 = (i + 1) * (e + 1) + j;
  28251. var i2 = i * (e + 1) + (j + 1);
  28252. var i3 = (i + 1) * (e + 1) + (j + 1);
  28253. indices.push(i0, i1, i2);
  28254. indices.push(i3, i2, i1);
  28255. }
  28256. if (arc !== 1 && enclose) {
  28257. indices.push(i0 + 2, i1 + 2, i2 + 2);
  28258. indices.push(i3 + 2, i2 + 2, i1 + 2);
  28259. indices.push(i0 + 4, i1 + 4, i2 + 4);
  28260. indices.push(i3 + 4, i2 + 4, i1 + 4);
  28261. }
  28262. i = (hasRings) ? (i + 2) : (i + 1);
  28263. }
  28264. // Caps
  28265. var createCylinderCap = function (isTop) {
  28266. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  28267. if (radius === 0) {
  28268. return;
  28269. }
  28270. // Cap positions, normals & uvs
  28271. var angle;
  28272. var circleVector;
  28273. var i;
  28274. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  28275. var c;
  28276. if (faceColors) {
  28277. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  28278. }
  28279. // cap center
  28280. var vbase = positions.length / 3;
  28281. var offset = isTop ? height / 2 : -height / 2;
  28282. var center = new BABYLON.Vector3(0, offset, 0);
  28283. positions.push(center.x, center.y, center.z);
  28284. normals.push(0, isTop ? 1 : -1, 0);
  28285. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  28286. if (faceColors) {
  28287. colors.push(c.r, c.g, c.b, c.a);
  28288. }
  28289. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  28290. for (i = 0; i <= tessellation; i++) {
  28291. angle = Math.PI * 2 * i * arc / tessellation;
  28292. var cos = Math.cos(-angle);
  28293. var sin = Math.sin(-angle);
  28294. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  28295. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  28296. positions.push(circleVector.x, circleVector.y, circleVector.z);
  28297. normals.push(0, isTop ? 1 : -1, 0);
  28298. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  28299. if (faceColors) {
  28300. colors.push(c.r, c.g, c.b, c.a);
  28301. }
  28302. }
  28303. // Cap indices
  28304. for (i = 0; i < tessellation; i++) {
  28305. if (!isTop) {
  28306. indices.push(vbase);
  28307. indices.push(vbase + (i + 1));
  28308. indices.push(vbase + (i + 2));
  28309. }
  28310. else {
  28311. indices.push(vbase);
  28312. indices.push(vbase + (i + 2));
  28313. indices.push(vbase + (i + 1));
  28314. }
  28315. }
  28316. };
  28317. // add caps to geometry
  28318. createCylinderCap(false);
  28319. createCylinderCap(true);
  28320. // Sides
  28321. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28322. var vertexData = new VertexData();
  28323. vertexData.indices = indices;
  28324. vertexData.positions = positions;
  28325. vertexData.normals = normals;
  28326. vertexData.uvs = uvs;
  28327. if (faceColors) {
  28328. vertexData.colors = colors;
  28329. }
  28330. return vertexData;
  28331. };
  28332. VertexData.CreateTorus = function (options) {
  28333. var indices = [];
  28334. var positions = [];
  28335. var normals = [];
  28336. var uvs = [];
  28337. var diameter = options.diameter || 1;
  28338. var thickness = options.thickness || 0.5;
  28339. var tessellation = options.tessellation || 16;
  28340. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28341. var stride = tessellation + 1;
  28342. for (var i = 0; i <= tessellation; i++) {
  28343. var u = i / tessellation;
  28344. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  28345. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  28346. for (var j = 0; j <= tessellation; j++) {
  28347. var v = 1 - j / tessellation;
  28348. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  28349. var dx = Math.cos(innerAngle);
  28350. var dy = Math.sin(innerAngle);
  28351. // Create a vertex.
  28352. var normal = new BABYLON.Vector3(dx, dy, 0);
  28353. var position = normal.scale(thickness / 2);
  28354. var textureCoordinate = new BABYLON.Vector2(u, v);
  28355. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  28356. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  28357. positions.push(position.x, position.y, position.z);
  28358. normals.push(normal.x, normal.y, normal.z);
  28359. uvs.push(textureCoordinate.x, textureCoordinate.y);
  28360. // And create indices for two triangles.
  28361. var nextI = (i + 1) % stride;
  28362. var nextJ = (j + 1) % stride;
  28363. indices.push(i * stride + j);
  28364. indices.push(i * stride + nextJ);
  28365. indices.push(nextI * stride + j);
  28366. indices.push(i * stride + nextJ);
  28367. indices.push(nextI * stride + nextJ);
  28368. indices.push(nextI * stride + j);
  28369. }
  28370. }
  28371. // Sides
  28372. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28373. // Result
  28374. var vertexData = new VertexData();
  28375. vertexData.indices = indices;
  28376. vertexData.positions = positions;
  28377. vertexData.normals = normals;
  28378. vertexData.uvs = uvs;
  28379. return vertexData;
  28380. };
  28381. VertexData.CreateLineSystem = function (options) {
  28382. var indices = [];
  28383. var positions = [];
  28384. var lines = options.lines;
  28385. var idx = 0;
  28386. for (var l = 0; l < lines.length; l++) {
  28387. var points = lines[l];
  28388. for (var index = 0; index < points.length; index++) {
  28389. positions.push(points[index].x, points[index].y, points[index].z);
  28390. if (index > 0) {
  28391. indices.push(idx - 1);
  28392. indices.push(idx);
  28393. }
  28394. idx++;
  28395. }
  28396. }
  28397. var vertexData = new VertexData();
  28398. vertexData.indices = indices;
  28399. vertexData.positions = positions;
  28400. return vertexData;
  28401. };
  28402. VertexData.CreateDashedLines = function (options) {
  28403. var dashSize = options.dashSize || 3;
  28404. var gapSize = options.gapSize || 1;
  28405. var dashNb = options.dashNb || 200;
  28406. var points = options.points;
  28407. var positions = new Array();
  28408. var indices = new Array();
  28409. var curvect = BABYLON.Vector3.Zero();
  28410. var lg = 0;
  28411. var nb = 0;
  28412. var shft = 0;
  28413. var dashshft = 0;
  28414. var curshft = 0;
  28415. var idx = 0;
  28416. var i = 0;
  28417. for (i = 0; i < points.length - 1; i++) {
  28418. points[i + 1].subtractToRef(points[i], curvect);
  28419. lg += curvect.length();
  28420. }
  28421. shft = lg / dashNb;
  28422. dashshft = dashSize * shft / (dashSize + gapSize);
  28423. for (i = 0; i < points.length - 1; i++) {
  28424. points[i + 1].subtractToRef(points[i], curvect);
  28425. nb = Math.floor(curvect.length() / shft);
  28426. curvect.normalize();
  28427. for (var j = 0; j < nb; j++) {
  28428. curshft = shft * j;
  28429. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  28430. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  28431. indices.push(idx, idx + 1);
  28432. idx += 2;
  28433. }
  28434. }
  28435. // Result
  28436. var vertexData = new VertexData();
  28437. vertexData.positions = positions;
  28438. vertexData.indices = indices;
  28439. return vertexData;
  28440. };
  28441. VertexData.CreateGround = function (options) {
  28442. var indices = [];
  28443. var positions = [];
  28444. var normals = [];
  28445. var uvs = [];
  28446. var row, col;
  28447. var width = options.width || 1;
  28448. var height = options.height || 1;
  28449. var subdivisions = options.subdivisions || 1;
  28450. for (row = 0; row <= subdivisions; row++) {
  28451. for (col = 0; col <= subdivisions; col++) {
  28452. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  28453. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28454. positions.push(position.x, position.y, position.z);
  28455. normals.push(normal.x, normal.y, normal.z);
  28456. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  28457. }
  28458. }
  28459. for (row = 0; row < subdivisions; row++) {
  28460. for (col = 0; col < subdivisions; col++) {
  28461. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  28462. indices.push(col + 1 + row * (subdivisions + 1));
  28463. indices.push(col + row * (subdivisions + 1));
  28464. indices.push(col + (row + 1) * (subdivisions + 1));
  28465. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  28466. indices.push(col + row * (subdivisions + 1));
  28467. }
  28468. }
  28469. // Result
  28470. var vertexData = new VertexData();
  28471. vertexData.indices = indices;
  28472. vertexData.positions = positions;
  28473. vertexData.normals = normals;
  28474. vertexData.uvs = uvs;
  28475. return vertexData;
  28476. };
  28477. VertexData.CreateTiledGround = function (options) {
  28478. var xmin = options.xmin;
  28479. var zmin = options.zmin;
  28480. var xmax = options.xmax;
  28481. var zmax = options.zmax;
  28482. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  28483. var precision = options.precision || { w: 1, h: 1 };
  28484. var indices = [];
  28485. var positions = [];
  28486. var normals = [];
  28487. var uvs = [];
  28488. var row, col, tileRow, tileCol;
  28489. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  28490. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  28491. precision.w = (precision.w < 1) ? 1 : precision.w;
  28492. precision.h = (precision.h < 1) ? 1 : precision.h;
  28493. var tileSize = {
  28494. 'w': (xmax - xmin) / subdivisions.w,
  28495. 'h': (zmax - zmin) / subdivisions.h
  28496. };
  28497. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  28498. // Indices
  28499. var base = positions.length / 3;
  28500. var rowLength = precision.w + 1;
  28501. for (row = 0; row < precision.h; row++) {
  28502. for (col = 0; col < precision.w; col++) {
  28503. var square = [
  28504. base + col + row * rowLength,
  28505. base + (col + 1) + row * rowLength,
  28506. base + (col + 1) + (row + 1) * rowLength,
  28507. base + col + (row + 1) * rowLength
  28508. ];
  28509. indices.push(square[1]);
  28510. indices.push(square[2]);
  28511. indices.push(square[3]);
  28512. indices.push(square[0]);
  28513. indices.push(square[1]);
  28514. indices.push(square[3]);
  28515. }
  28516. }
  28517. // Position, normals and uvs
  28518. var position = BABYLON.Vector3.Zero();
  28519. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28520. for (row = 0; row <= precision.h; row++) {
  28521. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  28522. for (col = 0; col <= precision.w; col++) {
  28523. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  28524. position.y = 0;
  28525. positions.push(position.x, position.y, position.z);
  28526. normals.push(normal.x, normal.y, normal.z);
  28527. uvs.push(col / precision.w, row / precision.h);
  28528. }
  28529. }
  28530. }
  28531. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  28532. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  28533. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  28534. }
  28535. }
  28536. // Result
  28537. var vertexData = new VertexData();
  28538. vertexData.indices = indices;
  28539. vertexData.positions = positions;
  28540. vertexData.normals = normals;
  28541. vertexData.uvs = uvs;
  28542. return vertexData;
  28543. };
  28544. VertexData.CreateGroundFromHeightMap = function (options) {
  28545. var indices = [];
  28546. var positions = [];
  28547. var normals = [];
  28548. var uvs = [];
  28549. var row, col;
  28550. // Vertices
  28551. for (row = 0; row <= options.subdivisions; row++) {
  28552. for (col = 0; col <= options.subdivisions; col++) {
  28553. 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));
  28554. // Compute height
  28555. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  28556. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  28557. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  28558. var r = options.buffer[pos] / 255.0;
  28559. var g = options.buffer[pos + 1] / 255.0;
  28560. var b = options.buffer[pos + 2] / 255.0;
  28561. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28562. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  28563. // Add vertex
  28564. positions.push(position.x, position.y, position.z);
  28565. normals.push(0, 0, 0);
  28566. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  28567. }
  28568. }
  28569. // Indices
  28570. for (row = 0; row < options.subdivisions; row++) {
  28571. for (col = 0; col < options.subdivisions; col++) {
  28572. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28573. indices.push(col + 1 + row * (options.subdivisions + 1));
  28574. indices.push(col + row * (options.subdivisions + 1));
  28575. indices.push(col + (row + 1) * (options.subdivisions + 1));
  28576. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28577. indices.push(col + row * (options.subdivisions + 1));
  28578. }
  28579. }
  28580. // Normals
  28581. VertexData.ComputeNormals(positions, indices, normals);
  28582. // Result
  28583. var vertexData = new VertexData();
  28584. vertexData.indices = indices;
  28585. vertexData.positions = positions;
  28586. vertexData.normals = normals;
  28587. vertexData.uvs = uvs;
  28588. return vertexData;
  28589. };
  28590. VertexData.CreatePlane = function (options) {
  28591. var indices = [];
  28592. var positions = [];
  28593. var normals = [];
  28594. var uvs = [];
  28595. var width = options.width || options.size || 1;
  28596. var height = options.height || options.size || 1;
  28597. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28598. // Vertices
  28599. var halfWidth = width / 2.0;
  28600. var halfHeight = height / 2.0;
  28601. positions.push(-halfWidth, -halfHeight, 0);
  28602. normals.push(0, 0, -1.0);
  28603. uvs.push(0.0, 0.0);
  28604. positions.push(halfWidth, -halfHeight, 0);
  28605. normals.push(0, 0, -1.0);
  28606. uvs.push(1.0, 0.0);
  28607. positions.push(halfWidth, halfHeight, 0);
  28608. normals.push(0, 0, -1.0);
  28609. uvs.push(1.0, 1.0);
  28610. positions.push(-halfWidth, halfHeight, 0);
  28611. normals.push(0, 0, -1.0);
  28612. uvs.push(0.0, 1.0);
  28613. // Indices
  28614. indices.push(0);
  28615. indices.push(1);
  28616. indices.push(2);
  28617. indices.push(0);
  28618. indices.push(2);
  28619. indices.push(3);
  28620. // Sides
  28621. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28622. // Result
  28623. var vertexData = new VertexData();
  28624. vertexData.indices = indices;
  28625. vertexData.positions = positions;
  28626. vertexData.normals = normals;
  28627. vertexData.uvs = uvs;
  28628. return vertexData;
  28629. };
  28630. VertexData.CreateDisc = function (options) {
  28631. var positions = [];
  28632. var indices = [];
  28633. var normals = [];
  28634. var uvs = [];
  28635. var radius = options.radius || 0.5;
  28636. var tessellation = options.tessellation || 64;
  28637. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28638. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28639. // positions and uvs
  28640. positions.push(0, 0, 0); // disc center first
  28641. uvs.push(0.5, 0.5);
  28642. var theta = Math.PI * 2 * arc;
  28643. var step = theta / tessellation;
  28644. for (var a = 0; a < theta; a += step) {
  28645. var x = Math.cos(a);
  28646. var y = Math.sin(a);
  28647. var u = (x + 1) / 2;
  28648. var v = (1 - y) / 2;
  28649. positions.push(radius * x, radius * y, 0);
  28650. uvs.push(u, v);
  28651. }
  28652. if (arc === 1) {
  28653. positions.push(positions[3], positions[4], positions[5]); // close the circle
  28654. uvs.push(uvs[2], uvs[3]);
  28655. }
  28656. //indices
  28657. var vertexNb = positions.length / 3;
  28658. for (var i = 1; i < vertexNb - 1; i++) {
  28659. indices.push(i + 1, 0, i);
  28660. }
  28661. // result
  28662. VertexData.ComputeNormals(positions, indices, normals);
  28663. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28664. var vertexData = new VertexData();
  28665. vertexData.indices = indices;
  28666. vertexData.positions = positions;
  28667. vertexData.normals = normals;
  28668. vertexData.uvs = uvs;
  28669. return vertexData;
  28670. };
  28671. VertexData.CreateIcoSphere = function (options) {
  28672. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28673. var radius = options.radius || 1;
  28674. var flat = (options.flat === undefined) ? true : options.flat;
  28675. var subdivisions = options.subdivisions || 4;
  28676. var radiusX = options.radiusX || radius;
  28677. var radiusY = options.radiusY || radius;
  28678. var radiusZ = options.radiusZ || radius;
  28679. var t = (1 + Math.sqrt(5)) / 2;
  28680. // 12 vertex x,y,z
  28681. var ico_vertices = [
  28682. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  28683. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  28684. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  28685. ];
  28686. // index of 3 vertex makes a face of icopshere
  28687. var ico_indices = [
  28688. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  28689. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  28690. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  28691. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  28692. ];
  28693. // vertex for uv have aliased position, not for UV
  28694. var vertices_unalias_id = [
  28695. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  28696. // vertex alias
  28697. 0,
  28698. 2,
  28699. 3,
  28700. 3,
  28701. 3,
  28702. 4,
  28703. 7,
  28704. 8,
  28705. 9,
  28706. 9,
  28707. 10,
  28708. 11 // 23: B + 12
  28709. ];
  28710. // uv as integer step (not pixels !)
  28711. var ico_vertexuv = [
  28712. 5, 1, 3, 1, 6, 4, 0, 0,
  28713. 5, 3, 4, 2, 2, 2, 4, 0,
  28714. 2, 0, 1, 1, 6, 0, 6, 2,
  28715. // vertex alias (for same vertex on different faces)
  28716. 0, 4,
  28717. 3, 3,
  28718. 4, 4,
  28719. 3, 1,
  28720. 4, 2,
  28721. 4, 4,
  28722. 0, 2,
  28723. 1, 1,
  28724. 2, 2,
  28725. 3, 3,
  28726. 1, 3,
  28727. 2, 4 // 23: B + 12
  28728. ];
  28729. // Vertices[0, 1, ...9, A, B] : position on UV plane
  28730. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  28731. // First island of uv mapping
  28732. // v = 4h 3+ 2
  28733. // v = 3h 9+ 4
  28734. // v = 2h 9+ 5 B
  28735. // v = 1h 9 1 0
  28736. // v = 0h 3 8 7 A
  28737. // u = 0 1 2 3 4 5 6 *a
  28738. // Second island of uv mapping
  28739. // v = 4h 0+ B+ 4+
  28740. // v = 3h A+ 2+
  28741. // v = 2h 7+ 6 3+
  28742. // v = 1h 8+ 3+
  28743. // v = 0h
  28744. // u = 0 1 2 3 4 5 6 *a
  28745. // Face layout on texture UV mapping
  28746. // ============
  28747. // \ 4 /\ 16 / ======
  28748. // \ / \ / /\ 11 /
  28749. // \/ 7 \/ / \ /
  28750. // ======= / 10 \/
  28751. // /\ 17 /\ =======
  28752. // / \ / \ \ 15 /\
  28753. // / 8 \/ 12 \ \ / \
  28754. // ============ \/ 6 \
  28755. // \ 18 /\ ============
  28756. // \ / \ \ 5 /\ 0 /
  28757. // \/ 13 \ \ / \ /
  28758. // ======= \/ 1 \/
  28759. // =============
  28760. // /\ 19 /\ 2 /\
  28761. // / \ / \ / \
  28762. // / 14 \/ 9 \/ 3 \
  28763. // ===================
  28764. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  28765. var ustep = 138 / 1024;
  28766. var vstep = 239 / 1024;
  28767. var uoffset = 60 / 1024;
  28768. var voffset = 26 / 1024;
  28769. // Second island should have margin, not to touch the first island
  28770. // avoid any borderline artefact in pixel rounding
  28771. var island_u_offset = -40 / 1024;
  28772. var island_v_offset = +20 / 1024;
  28773. // face is either island 0 or 1 :
  28774. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  28775. var island = [
  28776. 0, 0, 0, 0, 1,
  28777. 0, 0, 1, 1, 0,
  28778. 0, 0, 1, 1, 0,
  28779. 0, 1, 1, 1, 0 // 15 - 19
  28780. ];
  28781. var indices = [];
  28782. var positions = [];
  28783. var normals = [];
  28784. var uvs = [];
  28785. var current_indice = 0;
  28786. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  28787. var face_vertex_pos = new Array(3);
  28788. var face_vertex_uv = new Array(3);
  28789. var v012;
  28790. for (v012 = 0; v012 < 3; v012++) {
  28791. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  28792. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  28793. }
  28794. // create all with normals
  28795. for (var face = 0; face < 20; face++) {
  28796. // 3 vertex per face
  28797. for (v012 = 0; v012 < 3; v012++) {
  28798. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  28799. var v_id = ico_indices[3 * face + v012];
  28800. // vertex have 3D position (x,y,z)
  28801. 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]);
  28802. // Normalize to get normal, then scale to radius
  28803. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  28804. // uv Coordinates from vertex ID
  28805. 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);
  28806. }
  28807. // Subdivide the face (interpolate pos, norm, uv)
  28808. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  28809. // - norm is linear interpolation of vertex corner normal
  28810. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  28811. // - uv is linear interpolation
  28812. //
  28813. // Topology is as below for sub-divide by 2
  28814. // vertex shown as v0,v1,v2
  28815. // interp index is i1 to progress in range [v0,v1[
  28816. // interp index is i2 to progress in range [v0,v2[
  28817. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  28818. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28819. //
  28820. //
  28821. // i2 v2
  28822. // ^ ^
  28823. // / / \
  28824. // / / \
  28825. // / / \
  28826. // / / (0,1) \
  28827. // / #---------\
  28828. // / / \ (0,0)'/ \
  28829. // / / \ / \
  28830. // / / \ / \
  28831. // / / (0,0) \ / (1,0) \
  28832. // / #---------#---------\
  28833. // v0 v1
  28834. //
  28835. // --------------------> i1
  28836. //
  28837. // interp of (i1,i2):
  28838. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  28839. // along i1 : lerp(x0,x1, i1/(S-i2))
  28840. //
  28841. // centroid of triangle is needed to get help normal computation
  28842. // (c1,c2) are used for centroid location
  28843. var interp_vertex = function (i1, i2, c1, c2) {
  28844. // vertex is interpolated from
  28845. // - face_vertex_pos[0..2]
  28846. // - face_vertex_uv[0..2]
  28847. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  28848. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  28849. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  28850. pos_interp.normalize();
  28851. var vertex_normal;
  28852. if (flat) {
  28853. // in flat mode, recalculate normal as face centroid normal
  28854. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  28855. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  28856. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  28857. }
  28858. else {
  28859. // in smooth mode, recalculate normal from each single vertex position
  28860. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  28861. }
  28862. // Vertex normal need correction due to X,Y,Z radius scaling
  28863. vertex_normal.x /= radiusX;
  28864. vertex_normal.y /= radiusY;
  28865. vertex_normal.z /= radiusZ;
  28866. vertex_normal.normalize();
  28867. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  28868. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  28869. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  28870. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  28871. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  28872. uvs.push(uv_interp.x, uv_interp.y);
  28873. // push each vertex has member of a face
  28874. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  28875. indices.push(current_indice);
  28876. current_indice++;
  28877. };
  28878. for (var i2 = 0; i2 < subdivisions; i2++) {
  28879. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  28880. // face : (i1,i2) for /\ :
  28881. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  28882. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28883. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28884. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28885. if (i1 + i2 + 1 < subdivisions) {
  28886. // face : (i1,i2)' for \/ :
  28887. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28888. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28889. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28890. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28891. }
  28892. }
  28893. }
  28894. }
  28895. // Sides
  28896. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28897. // Result
  28898. var vertexData = new VertexData();
  28899. vertexData.indices = indices;
  28900. vertexData.positions = positions;
  28901. vertexData.normals = normals;
  28902. vertexData.uvs = uvs;
  28903. return vertexData;
  28904. };
  28905. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  28906. VertexData.CreatePolyhedron = function (options) {
  28907. // provided polyhedron types :
  28908. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  28909. // 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)
  28910. var polyhedra = [];
  28911. 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]] };
  28912. 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]] };
  28913. polyhedra[2] = {
  28914. 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]],
  28915. 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]]
  28916. };
  28917. polyhedra[3] = {
  28918. 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]],
  28919. 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]]
  28920. };
  28921. polyhedra[4] = {
  28922. 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]],
  28923. 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]]
  28924. };
  28925. 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]] };
  28926. 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]] };
  28927. 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]] };
  28928. 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]] };
  28929. 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]] };
  28930. 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]] };
  28931. 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]] };
  28932. 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]] };
  28933. 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]] };
  28934. polyhedra[14] = {
  28935. 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]],
  28936. 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]]
  28937. };
  28938. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  28939. var size = options.size;
  28940. var sizeX = options.sizeX || size || 1;
  28941. var sizeY = options.sizeY || size || 1;
  28942. var sizeZ = options.sizeZ || size || 1;
  28943. var data = options.custom || polyhedra[type];
  28944. var nbfaces = data.face.length;
  28945. var faceUV = options.faceUV || new Array(nbfaces);
  28946. var faceColors = options.faceColors;
  28947. var flat = (options.flat === undefined) ? true : options.flat;
  28948. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28949. var positions = [];
  28950. var indices = [];
  28951. var normals = [];
  28952. var uvs = [];
  28953. var colors = [];
  28954. var index = 0;
  28955. var faceIdx = 0; // face cursor in the array "indexes"
  28956. var indexes = [];
  28957. var i = 0;
  28958. var f = 0;
  28959. var u, v, ang, x, y, tmp;
  28960. // default face colors and UV if undefined
  28961. if (flat) {
  28962. for (f = 0; f < nbfaces; f++) {
  28963. if (faceColors && faceColors[f] === undefined) {
  28964. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28965. }
  28966. if (faceUV && faceUV[f] === undefined) {
  28967. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28968. }
  28969. }
  28970. }
  28971. if (!flat) {
  28972. for (i = 0; i < data.vertex.length; i++) {
  28973. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  28974. uvs.push(0, 0);
  28975. }
  28976. for (f = 0; f < nbfaces; f++) {
  28977. for (i = 0; i < data.face[f].length - 2; i++) {
  28978. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  28979. }
  28980. }
  28981. }
  28982. else {
  28983. for (f = 0; f < nbfaces; f++) {
  28984. var fl = data.face[f].length; // number of vertices of the current face
  28985. ang = 2 * Math.PI / fl;
  28986. x = 0.5 * Math.tan(ang / 2);
  28987. y = 0.5;
  28988. // positions, uvs, colors
  28989. for (i = 0; i < fl; i++) {
  28990. // positions
  28991. 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);
  28992. indexes.push(index);
  28993. index++;
  28994. // uvs
  28995. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  28996. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  28997. uvs.push(u, v);
  28998. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  28999. y = x * Math.sin(ang) + y * Math.cos(ang);
  29000. x = tmp;
  29001. // colors
  29002. if (faceColors) {
  29003. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  29004. }
  29005. }
  29006. // indices from indexes
  29007. for (i = 0; i < fl - 2; i++) {
  29008. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  29009. }
  29010. faceIdx += fl;
  29011. }
  29012. }
  29013. VertexData.ComputeNormals(positions, indices, normals);
  29014. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29015. var vertexData = new VertexData();
  29016. vertexData.positions = positions;
  29017. vertexData.indices = indices;
  29018. vertexData.normals = normals;
  29019. vertexData.uvs = uvs;
  29020. if (faceColors && flat) {
  29021. vertexData.colors = colors;
  29022. }
  29023. return vertexData;
  29024. };
  29025. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  29026. VertexData.CreateTorusKnot = function (options) {
  29027. var indices = [];
  29028. var positions = [];
  29029. var normals = [];
  29030. var uvs = [];
  29031. var radius = options.radius || 2;
  29032. var tube = options.tube || 0.5;
  29033. var radialSegments = options.radialSegments || 32;
  29034. var tubularSegments = options.tubularSegments || 32;
  29035. var p = options.p || 2;
  29036. var q = options.q || 3;
  29037. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29038. // Helper
  29039. var getPos = function (angle) {
  29040. var cu = Math.cos(angle);
  29041. var su = Math.sin(angle);
  29042. var quOverP = q / p * angle;
  29043. var cs = Math.cos(quOverP);
  29044. var tx = radius * (2 + cs) * 0.5 * cu;
  29045. var ty = radius * (2 + cs) * su * 0.5;
  29046. var tz = radius * Math.sin(quOverP) * 0.5;
  29047. return new BABYLON.Vector3(tx, ty, tz);
  29048. };
  29049. // Vertices
  29050. var i;
  29051. var j;
  29052. for (i = 0; i <= radialSegments; i++) {
  29053. var modI = i % radialSegments;
  29054. var u = modI / radialSegments * 2 * p * Math.PI;
  29055. var p1 = getPos(u);
  29056. var p2 = getPos(u + 0.01);
  29057. var tang = p2.subtract(p1);
  29058. var n = p2.add(p1);
  29059. var bitan = BABYLON.Vector3.Cross(tang, n);
  29060. n = BABYLON.Vector3.Cross(bitan, tang);
  29061. bitan.normalize();
  29062. n.normalize();
  29063. for (j = 0; j < tubularSegments; j++) {
  29064. var modJ = j % tubularSegments;
  29065. var v = modJ / tubularSegments * 2 * Math.PI;
  29066. var cx = -tube * Math.cos(v);
  29067. var cy = tube * Math.sin(v);
  29068. positions.push(p1.x + cx * n.x + cy * bitan.x);
  29069. positions.push(p1.y + cx * n.y + cy * bitan.y);
  29070. positions.push(p1.z + cx * n.z + cy * bitan.z);
  29071. uvs.push(i / radialSegments);
  29072. uvs.push(j / tubularSegments);
  29073. }
  29074. }
  29075. for (i = 0; i < radialSegments; i++) {
  29076. for (j = 0; j < tubularSegments; j++) {
  29077. var jNext = (j + 1) % tubularSegments;
  29078. var a = i * tubularSegments + j;
  29079. var b = (i + 1) * tubularSegments + j;
  29080. var c = (i + 1) * tubularSegments + jNext;
  29081. var d = i * tubularSegments + jNext;
  29082. indices.push(d);
  29083. indices.push(b);
  29084. indices.push(a);
  29085. indices.push(d);
  29086. indices.push(c);
  29087. indices.push(b);
  29088. }
  29089. }
  29090. // Normals
  29091. VertexData.ComputeNormals(positions, indices, normals);
  29092. // Sides
  29093. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29094. // Result
  29095. var vertexData = new VertexData();
  29096. vertexData.indices = indices;
  29097. vertexData.positions = positions;
  29098. vertexData.normals = normals;
  29099. vertexData.uvs = uvs;
  29100. return vertexData;
  29101. };
  29102. // Tools
  29103. /**
  29104. * @param {any} - positions (number[] or Float32Array)
  29105. * @param {any} - indices (number[] or Uint16Array)
  29106. * @param {any} - normals (number[] or Float32Array)
  29107. */
  29108. VertexData.ComputeNormals = function (positions, indices, normals) {
  29109. var index = 0;
  29110. var p1p2x = 0.0;
  29111. var p1p2y = 0.0;
  29112. var p1p2z = 0.0;
  29113. var p3p2x = 0.0;
  29114. var p3p2y = 0.0;
  29115. var p3p2z = 0.0;
  29116. var faceNormalx = 0.0;
  29117. var faceNormaly = 0.0;
  29118. var faceNormalz = 0.0;
  29119. var length = 0.0;
  29120. var i1 = 0;
  29121. var i2 = 0;
  29122. var i3 = 0;
  29123. for (index = 0; index < positions.length; index++) {
  29124. normals[index] = 0.0;
  29125. }
  29126. // indice triplet = 1 face
  29127. var nbFaces = indices.length / 3;
  29128. for (index = 0; index < nbFaces; index++) {
  29129. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  29130. i2 = indices[index * 3 + 1];
  29131. i3 = indices[index * 3 + 2];
  29132. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  29133. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  29134. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  29135. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  29136. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  29137. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  29138. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  29139. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  29140. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  29141. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29142. length = (length === 0) ? 1.0 : length;
  29143. faceNormalx /= length; // normalize this normal
  29144. faceNormaly /= length;
  29145. faceNormalz /= length;
  29146. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  29147. normals[i1 * 3 + 1] += faceNormaly;
  29148. normals[i1 * 3 + 2] += faceNormalz;
  29149. normals[i2 * 3] += faceNormalx;
  29150. normals[i2 * 3 + 1] += faceNormaly;
  29151. normals[i2 * 3 + 2] += faceNormalz;
  29152. normals[i3 * 3] += faceNormalx;
  29153. normals[i3 * 3 + 1] += faceNormaly;
  29154. normals[i3 * 3 + 2] += faceNormalz;
  29155. }
  29156. // last normalization of each normal
  29157. for (index = 0; index < normals.length / 3; index++) {
  29158. faceNormalx = normals[index * 3];
  29159. faceNormaly = normals[index * 3 + 1];
  29160. faceNormalz = normals[index * 3 + 2];
  29161. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29162. length = (length === 0) ? 1.0 : length;
  29163. faceNormalx /= length;
  29164. faceNormaly /= length;
  29165. faceNormalz /= length;
  29166. normals[index * 3] = faceNormalx;
  29167. normals[index * 3 + 1] = faceNormaly;
  29168. normals[index * 3 + 2] = faceNormalz;
  29169. }
  29170. };
  29171. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  29172. var li = indices.length;
  29173. var ln = normals.length;
  29174. var i;
  29175. var n;
  29176. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29177. switch (sideOrientation) {
  29178. case BABYLON.Mesh.FRONTSIDE:
  29179. // nothing changed
  29180. break;
  29181. case BABYLON.Mesh.BACKSIDE:
  29182. var tmp;
  29183. // indices
  29184. for (i = 0; i < li; i += 3) {
  29185. tmp = indices[i];
  29186. indices[i] = indices[i + 2];
  29187. indices[i + 2] = tmp;
  29188. }
  29189. // normals
  29190. for (n = 0; n < ln; n++) {
  29191. normals[n] = -normals[n];
  29192. }
  29193. break;
  29194. case BABYLON.Mesh.DOUBLESIDE:
  29195. // positions
  29196. var lp = positions.length;
  29197. var l = lp / 3;
  29198. for (var p = 0; p < lp; p++) {
  29199. positions[lp + p] = positions[p];
  29200. }
  29201. // indices
  29202. for (i = 0; i < li; i += 3) {
  29203. indices[i + li] = indices[i + 2] + l;
  29204. indices[i + 1 + li] = indices[i + 1] + l;
  29205. indices[i + 2 + li] = indices[i] + l;
  29206. }
  29207. // normals
  29208. for (n = 0; n < ln; n++) {
  29209. normals[ln + n] = -normals[n];
  29210. }
  29211. // uvs
  29212. var lu = uvs.length;
  29213. for (var u = 0; u < lu; u++) {
  29214. uvs[u + lu] = uvs[u];
  29215. }
  29216. break;
  29217. }
  29218. };
  29219. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  29220. var vertexData = new VertexData();
  29221. // positions
  29222. var positions = parsedVertexData.positions;
  29223. if (positions) {
  29224. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  29225. }
  29226. // normals
  29227. var normals = parsedVertexData.normals;
  29228. if (normals) {
  29229. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  29230. }
  29231. // uvs
  29232. var uvs = parsedVertexData.uvs;
  29233. if (uvs) {
  29234. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  29235. }
  29236. // uv2s
  29237. var uv2s = parsedVertexData.uv2s;
  29238. if (uv2s) {
  29239. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  29240. }
  29241. // uv3s
  29242. var uv3s = parsedVertexData.uv3s;
  29243. if (uv3s) {
  29244. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  29245. }
  29246. // uv4s
  29247. var uv4s = parsedVertexData.uv4s;
  29248. if (uv4s) {
  29249. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  29250. }
  29251. // uv5s
  29252. var uv5s = parsedVertexData.uv5s;
  29253. if (uv5s) {
  29254. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  29255. }
  29256. // uv6s
  29257. var uv6s = parsedVertexData.uv6s;
  29258. if (uv6s) {
  29259. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  29260. }
  29261. // colors
  29262. var colors = parsedVertexData.colors;
  29263. if (colors) {
  29264. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  29265. }
  29266. // matricesIndices
  29267. var matricesIndices = parsedVertexData.matricesIndices;
  29268. if (matricesIndices) {
  29269. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  29270. }
  29271. // matricesWeights
  29272. var matricesWeights = parsedVertexData.matricesWeights;
  29273. if (matricesWeights) {
  29274. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  29275. }
  29276. // indices
  29277. var indices = parsedVertexData.indices;
  29278. if (indices) {
  29279. vertexData.indices = indices;
  29280. }
  29281. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  29282. };
  29283. return VertexData;
  29284. })();
  29285. BABYLON.VertexData = VertexData;
  29286. })(BABYLON || (BABYLON = {}));
  29287. var BABYLON;
  29288. (function (BABYLON) {
  29289. var Tags = (function () {
  29290. function Tags() {
  29291. }
  29292. Tags.EnableFor = function (obj) {
  29293. obj._tags = obj._tags || {};
  29294. obj.hasTags = function () {
  29295. return Tags.HasTags(obj);
  29296. };
  29297. obj.addTags = function (tagsString) {
  29298. return Tags.AddTagsTo(obj, tagsString);
  29299. };
  29300. obj.removeTags = function (tagsString) {
  29301. return Tags.RemoveTagsFrom(obj, tagsString);
  29302. };
  29303. obj.matchesTagsQuery = function (tagsQuery) {
  29304. return Tags.MatchesQuery(obj, tagsQuery);
  29305. };
  29306. };
  29307. Tags.DisableFor = function (obj) {
  29308. delete obj._tags;
  29309. delete obj.hasTags;
  29310. delete obj.addTags;
  29311. delete obj.removeTags;
  29312. delete obj.matchesTagsQuery;
  29313. };
  29314. Tags.HasTags = function (obj) {
  29315. if (!obj._tags) {
  29316. return false;
  29317. }
  29318. return !BABYLON.Tools.IsEmpty(obj._tags);
  29319. };
  29320. Tags.GetTags = function (obj, asString) {
  29321. if (asString === void 0) { asString = true; }
  29322. if (!obj._tags) {
  29323. return null;
  29324. }
  29325. if (asString) {
  29326. var tagsArray = [];
  29327. for (var tag in obj._tags) {
  29328. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  29329. tagsArray.push(tag);
  29330. }
  29331. }
  29332. return tagsArray.join(" ");
  29333. }
  29334. else {
  29335. return obj._tags;
  29336. }
  29337. };
  29338. // the tags 'true' and 'false' are reserved and cannot be used as tags
  29339. // a tag cannot start with '||', '&&', and '!'
  29340. // it cannot contain whitespaces
  29341. Tags.AddTagsTo = function (obj, tagsString) {
  29342. if (!tagsString) {
  29343. return;
  29344. }
  29345. if (typeof tagsString !== "string") {
  29346. return;
  29347. }
  29348. var tags = tagsString.split(" ");
  29349. for (var t in tags) {
  29350. Tags._AddTagTo(obj, tags[t]);
  29351. }
  29352. };
  29353. Tags._AddTagTo = function (obj, tag) {
  29354. tag = tag.trim();
  29355. if (tag === "" || tag === "true" || tag === "false") {
  29356. return;
  29357. }
  29358. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  29359. return;
  29360. }
  29361. Tags.EnableFor(obj);
  29362. obj._tags[tag] = true;
  29363. };
  29364. Tags.RemoveTagsFrom = function (obj, tagsString) {
  29365. if (!Tags.HasTags(obj)) {
  29366. return;
  29367. }
  29368. var tags = tagsString.split(" ");
  29369. for (var t in tags) {
  29370. Tags._RemoveTagFrom(obj, tags[t]);
  29371. }
  29372. };
  29373. Tags._RemoveTagFrom = function (obj, tag) {
  29374. delete obj._tags[tag];
  29375. };
  29376. Tags.MatchesQuery = function (obj, tagsQuery) {
  29377. if (tagsQuery === undefined) {
  29378. return true;
  29379. }
  29380. if (tagsQuery === "") {
  29381. return Tags.HasTags(obj);
  29382. }
  29383. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  29384. };
  29385. return Tags;
  29386. })();
  29387. BABYLON.Tags = Tags;
  29388. })(BABYLON || (BABYLON = {}));
  29389. var BABYLON;
  29390. (function (BABYLON) {
  29391. var Internals;
  29392. (function (Internals) {
  29393. var AndOrNotEvaluator = (function () {
  29394. function AndOrNotEvaluator() {
  29395. }
  29396. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  29397. if (!query.match(/\([^\(\)]*\)/g)) {
  29398. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  29399. }
  29400. else {
  29401. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  29402. // remove parenthesis
  29403. r = r.slice(1, r.length - 1);
  29404. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  29405. });
  29406. }
  29407. if (query === "true") {
  29408. return true;
  29409. }
  29410. if (query === "false") {
  29411. return false;
  29412. }
  29413. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  29414. };
  29415. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  29416. evaluateCallback = evaluateCallback || (function (r) {
  29417. return r === "true" ? true : false;
  29418. });
  29419. var result;
  29420. var or = parenthesisContent.split("||");
  29421. for (var i in or) {
  29422. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  29423. var and = ori.split("&&");
  29424. if (and.length > 1) {
  29425. for (var j = 0; j < and.length; ++j) {
  29426. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  29427. if (andj !== "true" && andj !== "false") {
  29428. if (andj[0] === "!") {
  29429. result = !evaluateCallback(andj.substring(1));
  29430. }
  29431. else {
  29432. result = evaluateCallback(andj);
  29433. }
  29434. }
  29435. else {
  29436. result = andj === "true" ? true : false;
  29437. }
  29438. if (!result) {
  29439. ori = "false";
  29440. break;
  29441. }
  29442. }
  29443. }
  29444. if (result || ori === "true") {
  29445. result = true;
  29446. break;
  29447. }
  29448. // result equals false (or undefined)
  29449. if (ori !== "true" && ori !== "false") {
  29450. if (ori[0] === "!") {
  29451. result = !evaluateCallback(ori.substring(1));
  29452. }
  29453. else {
  29454. result = evaluateCallback(ori);
  29455. }
  29456. }
  29457. else {
  29458. result = ori === "true" ? true : false;
  29459. }
  29460. }
  29461. // the whole parenthesis scope is replaced by 'true' or 'false'
  29462. return result ? "true" : "false";
  29463. };
  29464. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  29465. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  29466. // remove whitespaces
  29467. r = r.replace(/[\s]/g, function () { return ""; });
  29468. return r.length % 2 ? "!" : "";
  29469. });
  29470. booleanString = booleanString.trim();
  29471. if (booleanString === "!true") {
  29472. booleanString = "false";
  29473. }
  29474. else if (booleanString === "!false") {
  29475. booleanString = "true";
  29476. }
  29477. return booleanString;
  29478. };
  29479. return AndOrNotEvaluator;
  29480. })();
  29481. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  29482. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  29483. })(BABYLON || (BABYLON = {}));
  29484. var BABYLON;
  29485. (function (BABYLON) {
  29486. var PostProcessRenderPass = (function () {
  29487. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  29488. this._enabled = true;
  29489. this._refCount = 0;
  29490. this._name = name;
  29491. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  29492. this.setRenderList(renderList);
  29493. this._renderTexture.onBeforeRender = beforeRender;
  29494. this._renderTexture.onAfterRender = afterRender;
  29495. this._scene = scene;
  29496. this._renderList = renderList;
  29497. }
  29498. // private
  29499. PostProcessRenderPass.prototype._incRefCount = function () {
  29500. if (this._refCount === 0) {
  29501. this._scene.customRenderTargets.push(this._renderTexture);
  29502. }
  29503. return ++this._refCount;
  29504. };
  29505. PostProcessRenderPass.prototype._decRefCount = function () {
  29506. this._refCount--;
  29507. if (this._refCount <= 0) {
  29508. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  29509. }
  29510. return this._refCount;
  29511. };
  29512. PostProcessRenderPass.prototype._update = function () {
  29513. this.setRenderList(this._renderList);
  29514. };
  29515. // public
  29516. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  29517. this._renderTexture.renderList = renderList;
  29518. };
  29519. PostProcessRenderPass.prototype.getRenderTexture = function () {
  29520. return this._renderTexture;
  29521. };
  29522. return PostProcessRenderPass;
  29523. })();
  29524. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  29525. })(BABYLON || (BABYLON = {}));
  29526. var BABYLON;
  29527. (function (BABYLON) {
  29528. var PostProcessRenderEffect = (function () {
  29529. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  29530. this._engine = engine;
  29531. this._name = name;
  29532. this._singleInstance = singleInstance || true;
  29533. this._getPostProcess = getPostProcess;
  29534. this._cameras = [];
  29535. this._indicesForCamera = [];
  29536. this._postProcesses = {};
  29537. this._renderPasses = {};
  29538. this._renderEffectAsPasses = {};
  29539. }
  29540. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  29541. get: function () {
  29542. for (var index in this._postProcesses) {
  29543. if (!this._postProcesses[index].isSupported) {
  29544. return false;
  29545. }
  29546. }
  29547. return true;
  29548. },
  29549. enumerable: true,
  29550. configurable: true
  29551. });
  29552. PostProcessRenderEffect.prototype._update = function () {
  29553. for (var renderPassName in this._renderPasses) {
  29554. this._renderPasses[renderPassName]._update();
  29555. }
  29556. };
  29557. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  29558. this._renderPasses[renderPass._name] = renderPass;
  29559. this._linkParameters();
  29560. };
  29561. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  29562. delete this._renderPasses[renderPass._name];
  29563. this._linkParameters();
  29564. };
  29565. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  29566. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  29567. this._linkParameters();
  29568. };
  29569. PostProcessRenderEffect.prototype.getPass = function (passName) {
  29570. for (var renderPassName in this._renderPasses) {
  29571. if (renderPassName === passName) {
  29572. return this._renderPasses[passName];
  29573. }
  29574. }
  29575. };
  29576. PostProcessRenderEffect.prototype.emptyPasses = function () {
  29577. this._renderPasses = {};
  29578. this._linkParameters();
  29579. };
  29580. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  29581. var cameraKey;
  29582. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29583. for (var i = 0; i < _cam.length; i++) {
  29584. var camera = _cam[i];
  29585. var cameraName = camera.name;
  29586. if (this._singleInstance) {
  29587. cameraKey = 0;
  29588. }
  29589. else {
  29590. cameraKey = cameraName;
  29591. }
  29592. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  29593. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  29594. if (!this._indicesForCamera[cameraName]) {
  29595. this._indicesForCamera[cameraName] = [];
  29596. }
  29597. this._indicesForCamera[cameraName].push(index);
  29598. if (this._cameras.indexOf(camera) === -1) {
  29599. this._cameras[cameraName] = camera;
  29600. }
  29601. for (var passName in this._renderPasses) {
  29602. this._renderPasses[passName]._incRefCount();
  29603. }
  29604. }
  29605. this._linkParameters();
  29606. };
  29607. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  29608. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29609. for (var i = 0; i < _cam.length; i++) {
  29610. var camera = _cam[i];
  29611. var cameraName = camera.name;
  29612. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  29613. var index = this._cameras.indexOf(cameraName);
  29614. this._indicesForCamera.splice(index, 1);
  29615. this._cameras.splice(index, 1);
  29616. for (var passName in this._renderPasses) {
  29617. this._renderPasses[passName]._decRefCount();
  29618. }
  29619. }
  29620. };
  29621. PostProcessRenderEffect.prototype._enable = function (cameras) {
  29622. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29623. for (var i = 0; i < _cam.length; i++) {
  29624. var camera = _cam[i];
  29625. var cameraName = camera.name;
  29626. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  29627. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  29628. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  29629. }
  29630. }
  29631. for (var passName in this._renderPasses) {
  29632. this._renderPasses[passName]._incRefCount();
  29633. }
  29634. }
  29635. };
  29636. PostProcessRenderEffect.prototype._disable = function (cameras) {
  29637. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29638. for (var i = 0; i < _cam.length; i++) {
  29639. var camera = _cam[i];
  29640. var cameraName = camera.Name;
  29641. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  29642. for (var passName in this._renderPasses) {
  29643. this._renderPasses[passName]._decRefCount();
  29644. }
  29645. }
  29646. };
  29647. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  29648. if (this._singleInstance) {
  29649. return this._postProcesses[0];
  29650. }
  29651. else {
  29652. return this._postProcesses[camera.name];
  29653. }
  29654. };
  29655. PostProcessRenderEffect.prototype._linkParameters = function () {
  29656. var _this = this;
  29657. for (var index in this._postProcesses) {
  29658. if (this.applyParameters) {
  29659. this.applyParameters(this._postProcesses[index]);
  29660. }
  29661. this._postProcesses[index].onBeforeRender = function (effect) {
  29662. _this._linkTextures(effect);
  29663. };
  29664. }
  29665. };
  29666. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  29667. for (var renderPassName in this._renderPasses) {
  29668. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  29669. }
  29670. for (var renderEffectName in this._renderEffectAsPasses) {
  29671. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  29672. }
  29673. };
  29674. return PostProcessRenderEffect;
  29675. })();
  29676. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  29677. })(BABYLON || (BABYLON = {}));
  29678. var BABYLON;
  29679. (function (BABYLON) {
  29680. var PostProcessRenderPipeline = (function () {
  29681. function PostProcessRenderPipeline(engine, name) {
  29682. this._engine = engine;
  29683. this._name = name;
  29684. this._renderEffects = {};
  29685. this._renderEffectsForIsolatedPass = {};
  29686. this._cameras = [];
  29687. }
  29688. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  29689. get: function () {
  29690. for (var renderEffectName in this._renderEffects) {
  29691. if (!this._renderEffects[renderEffectName].isSupported) {
  29692. return false;
  29693. }
  29694. }
  29695. return true;
  29696. },
  29697. enumerable: true,
  29698. configurable: true
  29699. });
  29700. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  29701. this._renderEffects[renderEffect._name] = renderEffect;
  29702. };
  29703. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  29704. var renderEffects = this._renderEffects[renderEffectName];
  29705. if (!renderEffects) {
  29706. return;
  29707. }
  29708. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  29709. };
  29710. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  29711. var renderEffects = this._renderEffects[renderEffectName];
  29712. if (!renderEffects) {
  29713. return;
  29714. }
  29715. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  29716. };
  29717. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  29718. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29719. var indicesToDelete = [];
  29720. var i;
  29721. for (i = 0; i < _cam.length; i++) {
  29722. var camera = _cam[i];
  29723. var cameraName = camera.name;
  29724. if (this._cameras.indexOf(camera) === -1) {
  29725. this._cameras[cameraName] = camera;
  29726. }
  29727. else if (unique) {
  29728. indicesToDelete.push(i);
  29729. }
  29730. }
  29731. for (i = 0; i < indicesToDelete.length; i++) {
  29732. cameras.splice(indicesToDelete[i], 1);
  29733. }
  29734. for (var renderEffectName in this._renderEffects) {
  29735. this._renderEffects[renderEffectName]._attachCameras(_cam);
  29736. }
  29737. };
  29738. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  29739. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29740. for (var renderEffectName in this._renderEffects) {
  29741. this._renderEffects[renderEffectName]._detachCameras(_cam);
  29742. }
  29743. for (var i = 0; i < _cam.length; i++) {
  29744. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  29745. }
  29746. };
  29747. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  29748. var _this = this;
  29749. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29750. var pass = null;
  29751. var renderEffectName;
  29752. for (renderEffectName in this._renderEffects) {
  29753. pass = this._renderEffects[renderEffectName].getPass(passName);
  29754. if (pass != null) {
  29755. break;
  29756. }
  29757. }
  29758. if (pass === null) {
  29759. return;
  29760. }
  29761. for (renderEffectName in this._renderEffects) {
  29762. this._renderEffects[renderEffectName]._disable(_cam);
  29763. }
  29764. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  29765. for (var i = 0; i < _cam.length; i++) {
  29766. var camera = _cam[i];
  29767. var cameraName = camera.name;
  29768. 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); });
  29769. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  29770. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  29771. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  29772. }
  29773. };
  29774. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  29775. var _this = this;
  29776. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29777. for (var i = 0; i < _cam.length; i++) {
  29778. var camera = _cam[i];
  29779. var cameraName = camera.name;
  29780. 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); });
  29781. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  29782. }
  29783. for (var renderEffectName in this._renderEffects) {
  29784. this._renderEffects[renderEffectName]._enable(_cam);
  29785. }
  29786. };
  29787. PostProcessRenderPipeline.prototype._update = function () {
  29788. for (var renderEffectName in this._renderEffects) {
  29789. this._renderEffects[renderEffectName]._update();
  29790. }
  29791. for (var i = 0; i < this._cameras.length; i++) {
  29792. var cameraName = this._cameras[i].name;
  29793. if (this._renderEffectsForIsolatedPass[cameraName]) {
  29794. this._renderEffectsForIsolatedPass[cameraName]._update();
  29795. }
  29796. }
  29797. };
  29798. PostProcessRenderPipeline.prototype.dispose = function () {
  29799. // Must be implemented by children
  29800. };
  29801. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  29802. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  29803. return PostProcessRenderPipeline;
  29804. })();
  29805. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  29806. })(BABYLON || (BABYLON = {}));
  29807. var BABYLON;
  29808. (function (BABYLON) {
  29809. var PostProcessRenderPipelineManager = (function () {
  29810. function PostProcessRenderPipelineManager() {
  29811. this._renderPipelines = {};
  29812. }
  29813. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  29814. this._renderPipelines[renderPipeline._name] = renderPipeline;
  29815. };
  29816. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  29817. var renderPipeline = this._renderPipelines[renderPipelineName];
  29818. if (!renderPipeline) {
  29819. return;
  29820. }
  29821. renderPipeline._attachCameras(cameras, unique);
  29822. };
  29823. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  29824. var renderPipeline = this._renderPipelines[renderPipelineName];
  29825. if (!renderPipeline) {
  29826. return;
  29827. }
  29828. renderPipeline._detachCameras(cameras);
  29829. };
  29830. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  29831. var renderPipeline = this._renderPipelines[renderPipelineName];
  29832. if (!renderPipeline) {
  29833. return;
  29834. }
  29835. renderPipeline._enableEffect(renderEffectName, cameras);
  29836. };
  29837. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  29838. var renderPipeline = this._renderPipelines[renderPipelineName];
  29839. if (!renderPipeline) {
  29840. return;
  29841. }
  29842. renderPipeline._disableEffect(renderEffectName, cameras);
  29843. };
  29844. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  29845. var renderPipeline = this._renderPipelines[renderPipelineName];
  29846. if (!renderPipeline) {
  29847. return;
  29848. }
  29849. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  29850. };
  29851. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  29852. var renderPipeline = this._renderPipelines[renderPipelineName];
  29853. if (!renderPipeline) {
  29854. return;
  29855. }
  29856. renderPipeline._disableDisplayOnlyPass(cameras);
  29857. };
  29858. PostProcessRenderPipelineManager.prototype.update = function () {
  29859. for (var renderPipelineName in this._renderPipelines) {
  29860. var pipeline = this._renderPipelines[renderPipelineName];
  29861. if (!pipeline.isSupported) {
  29862. pipeline.dispose();
  29863. delete this._renderPipelines[renderPipelineName];
  29864. }
  29865. else {
  29866. pipeline._update();
  29867. }
  29868. }
  29869. };
  29870. return PostProcessRenderPipelineManager;
  29871. })();
  29872. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  29873. })(BABYLON || (BABYLON = {}));
  29874. var BABYLON;
  29875. (function (BABYLON) {
  29876. var BoundingBoxRenderer = (function () {
  29877. function BoundingBoxRenderer(scene) {
  29878. this.frontColor = new BABYLON.Color3(1, 1, 1);
  29879. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  29880. this.showBackLines = true;
  29881. this.renderList = new BABYLON.SmartArray(32);
  29882. this._scene = scene;
  29883. }
  29884. BoundingBoxRenderer.prototype._prepareRessources = function () {
  29885. if (this._colorShader) {
  29886. return;
  29887. }
  29888. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  29889. attributes: ["position"],
  29890. uniforms: ["worldViewProjection", "color"]
  29891. });
  29892. var engine = this._scene.getEngine();
  29893. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  29894. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  29895. 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]);
  29896. };
  29897. BoundingBoxRenderer.prototype.reset = function () {
  29898. this.renderList.reset();
  29899. };
  29900. BoundingBoxRenderer.prototype.render = function () {
  29901. if (this.renderList.length === 0) {
  29902. return;
  29903. }
  29904. this._prepareRessources();
  29905. if (!this._colorShader.isReady()) {
  29906. return;
  29907. }
  29908. var engine = this._scene.getEngine();
  29909. engine.setDepthWrite(false);
  29910. this._colorShader._preBind();
  29911. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  29912. var boundingBox = this.renderList.data[boundingBoxIndex];
  29913. var min = boundingBox.minimum;
  29914. var max = boundingBox.maximum;
  29915. var diff = max.subtract(min);
  29916. var median = min.add(diff.scale(0.5));
  29917. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  29918. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  29919. .multiply(boundingBox.getWorldMatrix());
  29920. // VBOs
  29921. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  29922. if (this.showBackLines) {
  29923. // Back
  29924. engine.setDepthFunctionToGreaterOrEqual();
  29925. this._scene.resetCachedMaterial();
  29926. this._colorShader.setColor4("color", this.backColor.toColor4());
  29927. this._colorShader.bind(worldMatrix);
  29928. // Draw order
  29929. engine.draw(false, 0, 24);
  29930. }
  29931. // Front
  29932. engine.setDepthFunctionToLess();
  29933. this._scene.resetCachedMaterial();
  29934. this._colorShader.setColor4("color", this.frontColor.toColor4());
  29935. this._colorShader.bind(worldMatrix);
  29936. // Draw order
  29937. engine.draw(false, 0, 24);
  29938. }
  29939. this._colorShader.unbind();
  29940. engine.setDepthFunctionToLessOrEqual();
  29941. engine.setDepthWrite(true);
  29942. };
  29943. BoundingBoxRenderer.prototype.dispose = function () {
  29944. if (!this._colorShader) {
  29945. return;
  29946. }
  29947. this._colorShader.dispose();
  29948. this._vb.dispose();
  29949. this._scene.getEngine()._releaseBuffer(this._ib);
  29950. };
  29951. return BoundingBoxRenderer;
  29952. })();
  29953. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  29954. })(BABYLON || (BABYLON = {}));
  29955. var BABYLON;
  29956. (function (BABYLON) {
  29957. var Condition = (function () {
  29958. function Condition(actionManager) {
  29959. this._actionManager = actionManager;
  29960. }
  29961. Condition.prototype.isValid = function () {
  29962. return true;
  29963. };
  29964. Condition.prototype._getProperty = function (propertyPath) {
  29965. return this._actionManager._getProperty(propertyPath);
  29966. };
  29967. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  29968. return this._actionManager._getEffectiveTarget(target, propertyPath);
  29969. };
  29970. return Condition;
  29971. })();
  29972. BABYLON.Condition = Condition;
  29973. var ValueCondition = (function (_super) {
  29974. __extends(ValueCondition, _super);
  29975. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  29976. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  29977. _super.call(this, actionManager);
  29978. this.propertyPath = propertyPath;
  29979. this.value = value;
  29980. this.operator = operator;
  29981. this._target = this._getEffectiveTarget(target, this.propertyPath);
  29982. this._property = this._getProperty(this.propertyPath);
  29983. }
  29984. Object.defineProperty(ValueCondition, "IsEqual", {
  29985. get: function () {
  29986. return ValueCondition._IsEqual;
  29987. },
  29988. enumerable: true,
  29989. configurable: true
  29990. });
  29991. Object.defineProperty(ValueCondition, "IsDifferent", {
  29992. get: function () {
  29993. return ValueCondition._IsDifferent;
  29994. },
  29995. enumerable: true,
  29996. configurable: true
  29997. });
  29998. Object.defineProperty(ValueCondition, "IsGreater", {
  29999. get: function () {
  30000. return ValueCondition._IsGreater;
  30001. },
  30002. enumerable: true,
  30003. configurable: true
  30004. });
  30005. Object.defineProperty(ValueCondition, "IsLesser", {
  30006. get: function () {
  30007. return ValueCondition._IsLesser;
  30008. },
  30009. enumerable: true,
  30010. configurable: true
  30011. });
  30012. // Methods
  30013. ValueCondition.prototype.isValid = function () {
  30014. switch (this.operator) {
  30015. case ValueCondition.IsGreater:
  30016. return this._target[this._property] > this.value;
  30017. case ValueCondition.IsLesser:
  30018. return this._target[this._property] < this.value;
  30019. case ValueCondition.IsEqual:
  30020. case ValueCondition.IsDifferent:
  30021. var check;
  30022. if (this.value.equals) {
  30023. check = this.value.equals(this._target[this._property]);
  30024. }
  30025. else {
  30026. check = this.value === this._target[this._property];
  30027. }
  30028. return this.operator === ValueCondition.IsEqual ? check : !check;
  30029. }
  30030. return false;
  30031. };
  30032. // Statics
  30033. ValueCondition._IsEqual = 0;
  30034. ValueCondition._IsDifferent = 1;
  30035. ValueCondition._IsGreater = 2;
  30036. ValueCondition._IsLesser = 3;
  30037. return ValueCondition;
  30038. })(Condition);
  30039. BABYLON.ValueCondition = ValueCondition;
  30040. var PredicateCondition = (function (_super) {
  30041. __extends(PredicateCondition, _super);
  30042. function PredicateCondition(actionManager, predicate) {
  30043. _super.call(this, actionManager);
  30044. this.predicate = predicate;
  30045. }
  30046. PredicateCondition.prototype.isValid = function () {
  30047. return this.predicate();
  30048. };
  30049. return PredicateCondition;
  30050. })(Condition);
  30051. BABYLON.PredicateCondition = PredicateCondition;
  30052. var StateCondition = (function (_super) {
  30053. __extends(StateCondition, _super);
  30054. function StateCondition(actionManager, target, value) {
  30055. _super.call(this, actionManager);
  30056. this.value = value;
  30057. this._target = target;
  30058. }
  30059. // Methods
  30060. StateCondition.prototype.isValid = function () {
  30061. return this._target.state === this.value;
  30062. };
  30063. return StateCondition;
  30064. })(Condition);
  30065. BABYLON.StateCondition = StateCondition;
  30066. })(BABYLON || (BABYLON = {}));
  30067. var BABYLON;
  30068. (function (BABYLON) {
  30069. var Action = (function () {
  30070. function Action(triggerOptions, condition) {
  30071. this.triggerOptions = triggerOptions;
  30072. if (triggerOptions.parameter) {
  30073. this.trigger = triggerOptions.trigger;
  30074. this._triggerParameter = triggerOptions.parameter;
  30075. }
  30076. else {
  30077. this.trigger = triggerOptions;
  30078. }
  30079. this._nextActiveAction = this;
  30080. this._condition = condition;
  30081. }
  30082. // Methods
  30083. Action.prototype._prepare = function () {
  30084. };
  30085. Action.prototype.getTriggerParameter = function () {
  30086. return this._triggerParameter;
  30087. };
  30088. Action.prototype._executeCurrent = function (evt) {
  30089. if (this._nextActiveAction._condition) {
  30090. var condition = this._nextActiveAction._condition;
  30091. var currentRenderId = this._actionManager.getScene().getRenderId();
  30092. // We cache the current evaluation for the current frame
  30093. if (condition._evaluationId === currentRenderId) {
  30094. if (!condition._currentResult) {
  30095. return;
  30096. }
  30097. }
  30098. else {
  30099. condition._evaluationId = currentRenderId;
  30100. if (!condition.isValid()) {
  30101. condition._currentResult = false;
  30102. return;
  30103. }
  30104. condition._currentResult = true;
  30105. }
  30106. }
  30107. this._nextActiveAction.execute(evt);
  30108. this.skipToNextActiveAction();
  30109. };
  30110. Action.prototype.execute = function (evt) {
  30111. };
  30112. Action.prototype.skipToNextActiveAction = function () {
  30113. if (this._nextActiveAction._child) {
  30114. if (!this._nextActiveAction._child._actionManager) {
  30115. this._nextActiveAction._child._actionManager = this._actionManager;
  30116. }
  30117. this._nextActiveAction = this._nextActiveAction._child;
  30118. }
  30119. else {
  30120. this._nextActiveAction = this;
  30121. }
  30122. };
  30123. Action.prototype.then = function (action) {
  30124. this._child = action;
  30125. action._actionManager = this._actionManager;
  30126. action._prepare();
  30127. return action;
  30128. };
  30129. Action.prototype._getProperty = function (propertyPath) {
  30130. return this._actionManager._getProperty(propertyPath);
  30131. };
  30132. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  30133. return this._actionManager._getEffectiveTarget(target, propertyPath);
  30134. };
  30135. return Action;
  30136. })();
  30137. BABYLON.Action = Action;
  30138. })(BABYLON || (BABYLON = {}));
  30139. var BABYLON;
  30140. (function (BABYLON) {
  30141. /**
  30142. * ActionEvent is the event beint sent when an action is triggered.
  30143. */
  30144. var ActionEvent = (function () {
  30145. /**
  30146. * @constructor
  30147. * @param source The mesh or sprite that triggered the action.
  30148. * @param pointerX The X mouse cursor position at the time of the event
  30149. * @param pointerY The Y mouse cursor position at the time of the event
  30150. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  30151. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  30152. */
  30153. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  30154. this.source = source;
  30155. this.pointerX = pointerX;
  30156. this.pointerY = pointerY;
  30157. this.meshUnderPointer = meshUnderPointer;
  30158. this.sourceEvent = sourceEvent;
  30159. this.additionalData = additionalData;
  30160. }
  30161. /**
  30162. * Helper function to auto-create an ActionEvent from a source mesh.
  30163. * @param source The source mesh that triggered the event
  30164. * @param evt {Event} The original (browser) event
  30165. */
  30166. ActionEvent.CreateNew = function (source, evt, additionalData) {
  30167. var scene = source.getScene();
  30168. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  30169. };
  30170. /**
  30171. * Helper function to auto-create an ActionEvent from a source mesh.
  30172. * @param source The source sprite that triggered the event
  30173. * @param scene Scene associated with the sprite
  30174. * @param evt {Event} The original (browser) event
  30175. */
  30176. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  30177. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  30178. };
  30179. /**
  30180. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  30181. * @param scene the scene where the event occurred
  30182. * @param evt {Event} The original (browser) event
  30183. */
  30184. ActionEvent.CreateNewFromScene = function (scene, evt) {
  30185. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  30186. };
  30187. return ActionEvent;
  30188. })();
  30189. BABYLON.ActionEvent = ActionEvent;
  30190. /**
  30191. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  30192. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  30193. */
  30194. var ActionManager = (function () {
  30195. function ActionManager(scene) {
  30196. // Members
  30197. this.actions = new Array();
  30198. this._scene = scene;
  30199. scene._actionManagers.push(this);
  30200. }
  30201. Object.defineProperty(ActionManager, "NothingTrigger", {
  30202. get: function () {
  30203. return ActionManager._NothingTrigger;
  30204. },
  30205. enumerable: true,
  30206. configurable: true
  30207. });
  30208. Object.defineProperty(ActionManager, "OnPickTrigger", {
  30209. get: function () {
  30210. return ActionManager._OnPickTrigger;
  30211. },
  30212. enumerable: true,
  30213. configurable: true
  30214. });
  30215. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  30216. get: function () {
  30217. return ActionManager._OnLeftPickTrigger;
  30218. },
  30219. enumerable: true,
  30220. configurable: true
  30221. });
  30222. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  30223. get: function () {
  30224. return ActionManager._OnRightPickTrigger;
  30225. },
  30226. enumerable: true,
  30227. configurable: true
  30228. });
  30229. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  30230. get: function () {
  30231. return ActionManager._OnCenterPickTrigger;
  30232. },
  30233. enumerable: true,
  30234. configurable: true
  30235. });
  30236. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  30237. get: function () {
  30238. return ActionManager._OnPickDownTrigger;
  30239. },
  30240. enumerable: true,
  30241. configurable: true
  30242. });
  30243. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  30244. get: function () {
  30245. return ActionManager._OnPickUpTrigger;
  30246. },
  30247. enumerable: true,
  30248. configurable: true
  30249. });
  30250. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  30251. /// This trigger will only be raised if you also declared a OnPickDown
  30252. get: function () {
  30253. return ActionManager._OnPickOutTrigger;
  30254. },
  30255. enumerable: true,
  30256. configurable: true
  30257. });
  30258. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  30259. get: function () {
  30260. return ActionManager._OnLongPressTrigger;
  30261. },
  30262. enumerable: true,
  30263. configurable: true
  30264. });
  30265. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  30266. get: function () {
  30267. return ActionManager._OnPointerOverTrigger;
  30268. },
  30269. enumerable: true,
  30270. configurable: true
  30271. });
  30272. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  30273. get: function () {
  30274. return ActionManager._OnPointerOutTrigger;
  30275. },
  30276. enumerable: true,
  30277. configurable: true
  30278. });
  30279. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  30280. get: function () {
  30281. return ActionManager._OnEveryFrameTrigger;
  30282. },
  30283. enumerable: true,
  30284. configurable: true
  30285. });
  30286. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  30287. get: function () {
  30288. return ActionManager._OnIntersectionEnterTrigger;
  30289. },
  30290. enumerable: true,
  30291. configurable: true
  30292. });
  30293. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  30294. get: function () {
  30295. return ActionManager._OnIntersectionExitTrigger;
  30296. },
  30297. enumerable: true,
  30298. configurable: true
  30299. });
  30300. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  30301. get: function () {
  30302. return ActionManager._OnKeyDownTrigger;
  30303. },
  30304. enumerable: true,
  30305. configurable: true
  30306. });
  30307. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  30308. get: function () {
  30309. return ActionManager._OnKeyUpTrigger;
  30310. },
  30311. enumerable: true,
  30312. configurable: true
  30313. });
  30314. // Methods
  30315. ActionManager.prototype.dispose = function () {
  30316. var index = this._scene._actionManagers.indexOf(this);
  30317. if (index > -1) {
  30318. this._scene._actionManagers.splice(index, 1);
  30319. }
  30320. };
  30321. ActionManager.prototype.getScene = function () {
  30322. return this._scene;
  30323. };
  30324. /**
  30325. * Does this action manager handles actions of any of the given triggers
  30326. * @param {number[]} triggers - the triggers to be tested
  30327. * @return {boolean} whether one (or more) of the triggers is handeled
  30328. */
  30329. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  30330. for (var index = 0; index < this.actions.length; index++) {
  30331. var action = this.actions[index];
  30332. if (triggers.indexOf(action.trigger) > -1) {
  30333. return true;
  30334. }
  30335. }
  30336. return false;
  30337. };
  30338. /**
  30339. * Does this action manager handles actions of a given trigger
  30340. * @param {number} trigger - the trigger to be tested
  30341. * @return {boolean} whether the trigger is handeled
  30342. */
  30343. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  30344. for (var index = 0; index < this.actions.length; index++) {
  30345. var action = this.actions[index];
  30346. if (action.trigger === trigger) {
  30347. return true;
  30348. }
  30349. }
  30350. return false;
  30351. };
  30352. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  30353. /**
  30354. * Does this action manager has pointer triggers
  30355. * @return {boolean} whether or not it has pointer triggers
  30356. */
  30357. get: function () {
  30358. for (var index = 0; index < this.actions.length; index++) {
  30359. var action = this.actions[index];
  30360. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  30361. return true;
  30362. }
  30363. }
  30364. return false;
  30365. },
  30366. enumerable: true,
  30367. configurable: true
  30368. });
  30369. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  30370. /**
  30371. * Does this action manager has pick triggers
  30372. * @return {boolean} whether or not it has pick triggers
  30373. */
  30374. get: function () {
  30375. for (var index = 0; index < this.actions.length; index++) {
  30376. var action = this.actions[index];
  30377. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  30378. return true;
  30379. }
  30380. }
  30381. return false;
  30382. },
  30383. enumerable: true,
  30384. configurable: true
  30385. });
  30386. /**
  30387. * Registers an action to this action manager
  30388. * @param {BABYLON.Action} action - the action to be registered
  30389. * @return {BABYLON.Action} the action amended (prepared) after registration
  30390. */
  30391. ActionManager.prototype.registerAction = function (action) {
  30392. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  30393. if (this.getScene().actionManager !== this) {
  30394. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  30395. return null;
  30396. }
  30397. }
  30398. this.actions.push(action);
  30399. action._actionManager = this;
  30400. action._prepare();
  30401. return action;
  30402. };
  30403. /**
  30404. * Process a specific trigger
  30405. * @param {number} trigger - the trigger to process
  30406. * @param evt {BABYLON.ActionEvent} the event details to be processed
  30407. */
  30408. ActionManager.prototype.processTrigger = function (trigger, evt) {
  30409. for (var index = 0; index < this.actions.length; index++) {
  30410. var action = this.actions[index];
  30411. if (action.trigger === trigger) {
  30412. if (trigger === ActionManager.OnKeyUpTrigger
  30413. || trigger === ActionManager.OnKeyDownTrigger) {
  30414. var parameter = action.getTriggerParameter();
  30415. if (parameter) {
  30416. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  30417. var actualkey = String.fromCharCode(unicode).toLowerCase();
  30418. if (actualkey !== parameter.toLowerCase()) {
  30419. continue;
  30420. }
  30421. }
  30422. }
  30423. action._executeCurrent(evt);
  30424. }
  30425. }
  30426. };
  30427. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  30428. var properties = propertyPath.split(".");
  30429. for (var index = 0; index < properties.length - 1; index++) {
  30430. target = target[properties[index]];
  30431. }
  30432. return target;
  30433. };
  30434. ActionManager.prototype._getProperty = function (propertyPath) {
  30435. var properties = propertyPath.split(".");
  30436. return properties[properties.length - 1];
  30437. };
  30438. ActionManager.Parse = function (parsedActions, object, scene) {
  30439. var actionManager = new BABYLON.ActionManager(scene);
  30440. if (object === null)
  30441. scene.actionManager = actionManager;
  30442. else
  30443. object.actionManager = actionManager;
  30444. // instanciate a new object
  30445. var instanciate = function (name, params) {
  30446. var newInstance = Object.create(BABYLON[name].prototype);
  30447. newInstance.constructor.apply(newInstance, params);
  30448. return newInstance;
  30449. };
  30450. var parseParameter = function (name, value, target, propertyPath) {
  30451. if (propertyPath === null) {
  30452. // String, boolean or float
  30453. var floatValue = parseFloat(value);
  30454. if (value === "true" || value === "false")
  30455. return value === "true";
  30456. else
  30457. return isNaN(floatValue) ? value : floatValue;
  30458. }
  30459. var effectiveTarget = propertyPath.split(".");
  30460. var values = value.split(",");
  30461. // Get effective Target
  30462. for (var i = 0; i < effectiveTarget.length; i++) {
  30463. target = target[effectiveTarget[i]];
  30464. }
  30465. // Return appropriate value with its type
  30466. if (typeof (target) === "boolean")
  30467. return values[0] === "true";
  30468. if (typeof (target) === "string")
  30469. return values[0];
  30470. // Parameters with multiple values such as Vector3 etc.
  30471. var split = new Array();
  30472. for (var i = 0; i < values.length; i++)
  30473. split.push(parseFloat(values[i]));
  30474. if (target instanceof BABYLON.Vector3)
  30475. return BABYLON.Vector3.FromArray(split);
  30476. if (target instanceof BABYLON.Vector4)
  30477. return BABYLON.Vector4.FromArray(split);
  30478. if (target instanceof BABYLON.Color3)
  30479. return BABYLON.Color3.FromArray(split);
  30480. if (target instanceof BABYLON.Color4)
  30481. return BABYLON.Color4.FromArray(split);
  30482. return parseFloat(values[0]);
  30483. };
  30484. // traverse graph per trigger
  30485. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  30486. if (combineArray === void 0) { combineArray = null; }
  30487. if (parsedAction.detached)
  30488. return;
  30489. var parameters = new Array();
  30490. var target = null;
  30491. var propertyPath = null;
  30492. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  30493. // Parameters
  30494. if (parsedAction.type === 2)
  30495. parameters.push(actionManager);
  30496. else
  30497. parameters.push(trigger);
  30498. if (combine) {
  30499. var actions = new Array();
  30500. for (var j = 0; j < parsedAction.combine.length; j++) {
  30501. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  30502. }
  30503. parameters.push(actions);
  30504. }
  30505. else {
  30506. for (var i = 0; i < parsedAction.properties.length; i++) {
  30507. var value = parsedAction.properties[i].value;
  30508. var name = parsedAction.properties[i].name;
  30509. var targetType = parsedAction.properties[i].targetType;
  30510. if (name === "target")
  30511. if (targetType !== null && targetType === "SceneProperties")
  30512. value = target = scene;
  30513. else
  30514. value = target = scene.getNodeByName(value);
  30515. else if (name === "parent")
  30516. value = scene.getNodeByName(value);
  30517. else if (name === "sound")
  30518. value = scene.getSoundByName(value);
  30519. else if (name !== "propertyPath") {
  30520. if (parsedAction.type === 2 && name === "operator")
  30521. value = BABYLON.ValueCondition[value];
  30522. else
  30523. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  30524. }
  30525. else {
  30526. propertyPath = value;
  30527. }
  30528. parameters.push(value);
  30529. }
  30530. }
  30531. if (combineArray === null) {
  30532. parameters.push(condition);
  30533. }
  30534. else {
  30535. parameters.push(null);
  30536. }
  30537. // If interpolate value action
  30538. if (parsedAction.name === "InterpolateValueAction") {
  30539. var param = parameters[parameters.length - 2];
  30540. parameters[parameters.length - 1] = param;
  30541. parameters[parameters.length - 2] = condition;
  30542. }
  30543. // Action or condition(s) and not CombineAction
  30544. var newAction = instanciate(parsedAction.name, parameters);
  30545. if (newAction instanceof BABYLON.Condition && condition !== null) {
  30546. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  30547. if (action)
  30548. action.then(nothing);
  30549. else
  30550. actionManager.registerAction(nothing);
  30551. action = nothing;
  30552. }
  30553. if (combineArray === null) {
  30554. if (newAction instanceof BABYLON.Condition) {
  30555. condition = newAction;
  30556. newAction = action;
  30557. }
  30558. else {
  30559. condition = null;
  30560. if (action)
  30561. action.then(newAction);
  30562. else
  30563. actionManager.registerAction(newAction);
  30564. }
  30565. }
  30566. else {
  30567. combineArray.push(newAction);
  30568. }
  30569. for (var i = 0; i < parsedAction.children.length; i++)
  30570. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  30571. };
  30572. // triggers
  30573. for (var i = 0; i < parsedActions.children.length; i++) {
  30574. var triggerParams;
  30575. var trigger = parsedActions.children[i];
  30576. if (trigger.properties.length > 0) {
  30577. var param = trigger.properties[0].value;
  30578. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  30579. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  30580. }
  30581. else
  30582. triggerParams = BABYLON.ActionManager[trigger.name];
  30583. for (var j = 0; j < trigger.children.length; j++) {
  30584. if (!trigger.detached)
  30585. traverse(trigger.children[j], triggerParams, null, null);
  30586. }
  30587. }
  30588. };
  30589. // Statics
  30590. ActionManager._NothingTrigger = 0;
  30591. ActionManager._OnPickTrigger = 1;
  30592. ActionManager._OnLeftPickTrigger = 2;
  30593. ActionManager._OnRightPickTrigger = 3;
  30594. ActionManager._OnCenterPickTrigger = 4;
  30595. ActionManager._OnPickDownTrigger = 5;
  30596. ActionManager._OnPickUpTrigger = 6;
  30597. ActionManager._OnLongPressTrigger = 7;
  30598. ActionManager._OnPointerOverTrigger = 8;
  30599. ActionManager._OnPointerOutTrigger = 9;
  30600. ActionManager._OnEveryFrameTrigger = 10;
  30601. ActionManager._OnIntersectionEnterTrigger = 11;
  30602. ActionManager._OnIntersectionExitTrigger = 12;
  30603. ActionManager._OnKeyDownTrigger = 13;
  30604. ActionManager._OnKeyUpTrigger = 14;
  30605. ActionManager._OnPickOutTrigger = 15;
  30606. ActionManager.DragMovementThreshold = 10; // in pixels
  30607. ActionManager.LongPressDelay = 500; // in milliseconds
  30608. return ActionManager;
  30609. })();
  30610. BABYLON.ActionManager = ActionManager;
  30611. })(BABYLON || (BABYLON = {}));
  30612. var BABYLON;
  30613. (function (BABYLON) {
  30614. var InterpolateValueAction = (function (_super) {
  30615. __extends(InterpolateValueAction, _super);
  30616. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  30617. if (duration === void 0) { duration = 1000; }
  30618. _super.call(this, triggerOptions, condition);
  30619. this.propertyPath = propertyPath;
  30620. this.value = value;
  30621. this.duration = duration;
  30622. this.stopOtherAnimations = stopOtherAnimations;
  30623. this.onInterpolationDone = onInterpolationDone;
  30624. this._target = target;
  30625. }
  30626. InterpolateValueAction.prototype._prepare = function () {
  30627. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  30628. this._property = this._getProperty(this.propertyPath);
  30629. };
  30630. InterpolateValueAction.prototype.execute = function () {
  30631. var scene = this._actionManager.getScene();
  30632. var keys = [
  30633. {
  30634. frame: 0,
  30635. value: this._target[this._property]
  30636. }, {
  30637. frame: 100,
  30638. value: this.value
  30639. }
  30640. ];
  30641. var dataType;
  30642. if (typeof this.value === "number") {
  30643. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  30644. }
  30645. else if (this.value instanceof BABYLON.Color3) {
  30646. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  30647. }
  30648. else if (this.value instanceof BABYLON.Vector3) {
  30649. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  30650. }
  30651. else if (this.value instanceof BABYLON.Matrix) {
  30652. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  30653. }
  30654. else if (this.value instanceof BABYLON.Quaternion) {
  30655. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  30656. }
  30657. else {
  30658. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  30659. return;
  30660. }
  30661. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  30662. animation.setKeys(keys);
  30663. if (this.stopOtherAnimations) {
  30664. scene.stopAnimation(this._target);
  30665. }
  30666. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  30667. };
  30668. return InterpolateValueAction;
  30669. })(BABYLON.Action);
  30670. BABYLON.InterpolateValueAction = InterpolateValueAction;
  30671. })(BABYLON || (BABYLON = {}));
  30672. var BABYLON;
  30673. (function (BABYLON) {
  30674. var SwitchBooleanAction = (function (_super) {
  30675. __extends(SwitchBooleanAction, _super);
  30676. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  30677. _super.call(this, triggerOptions, condition);
  30678. this.propertyPath = propertyPath;
  30679. this._target = target;
  30680. }
  30681. SwitchBooleanAction.prototype._prepare = function () {
  30682. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  30683. this._property = this._getProperty(this.propertyPath);
  30684. };
  30685. SwitchBooleanAction.prototype.execute = function () {
  30686. this._target[this._property] = !this._target[this._property];
  30687. };
  30688. return SwitchBooleanAction;
  30689. })(BABYLON.Action);
  30690. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  30691. var SetStateAction = (function (_super) {
  30692. __extends(SetStateAction, _super);
  30693. function SetStateAction(triggerOptions, target, value, condition) {
  30694. _super.call(this, triggerOptions, condition);
  30695. this.value = value;
  30696. this._target = target;
  30697. }
  30698. SetStateAction.prototype.execute = function () {
  30699. this._target.state = this.value;
  30700. };
  30701. return SetStateAction;
  30702. })(BABYLON.Action);
  30703. BABYLON.SetStateAction = SetStateAction;
  30704. var SetValueAction = (function (_super) {
  30705. __extends(SetValueAction, _super);
  30706. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  30707. _super.call(this, triggerOptions, condition);
  30708. this.propertyPath = propertyPath;
  30709. this.value = value;
  30710. this._target = target;
  30711. }
  30712. SetValueAction.prototype._prepare = function () {
  30713. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  30714. this._property = this._getProperty(this.propertyPath);
  30715. };
  30716. SetValueAction.prototype.execute = function () {
  30717. this._target[this._property] = this.value;
  30718. };
  30719. return SetValueAction;
  30720. })(BABYLON.Action);
  30721. BABYLON.SetValueAction = SetValueAction;
  30722. var IncrementValueAction = (function (_super) {
  30723. __extends(IncrementValueAction, _super);
  30724. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  30725. _super.call(this, triggerOptions, condition);
  30726. this.propertyPath = propertyPath;
  30727. this.value = value;
  30728. this._target = target;
  30729. }
  30730. IncrementValueAction.prototype._prepare = function () {
  30731. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  30732. this._property = this._getProperty(this.propertyPath);
  30733. if (typeof this._target[this._property] !== "number") {
  30734. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  30735. }
  30736. };
  30737. IncrementValueAction.prototype.execute = function () {
  30738. this._target[this._property] += this.value;
  30739. };
  30740. return IncrementValueAction;
  30741. })(BABYLON.Action);
  30742. BABYLON.IncrementValueAction = IncrementValueAction;
  30743. var PlayAnimationAction = (function (_super) {
  30744. __extends(PlayAnimationAction, _super);
  30745. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  30746. _super.call(this, triggerOptions, condition);
  30747. this.from = from;
  30748. this.to = to;
  30749. this.loop = loop;
  30750. this._target = target;
  30751. }
  30752. PlayAnimationAction.prototype._prepare = function () {
  30753. };
  30754. PlayAnimationAction.prototype.execute = function () {
  30755. var scene = this._actionManager.getScene();
  30756. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  30757. };
  30758. return PlayAnimationAction;
  30759. })(BABYLON.Action);
  30760. BABYLON.PlayAnimationAction = PlayAnimationAction;
  30761. var StopAnimationAction = (function (_super) {
  30762. __extends(StopAnimationAction, _super);
  30763. function StopAnimationAction(triggerOptions, target, condition) {
  30764. _super.call(this, triggerOptions, condition);
  30765. this._target = target;
  30766. }
  30767. StopAnimationAction.prototype._prepare = function () {
  30768. };
  30769. StopAnimationAction.prototype.execute = function () {
  30770. var scene = this._actionManager.getScene();
  30771. scene.stopAnimation(this._target);
  30772. };
  30773. return StopAnimationAction;
  30774. })(BABYLON.Action);
  30775. BABYLON.StopAnimationAction = StopAnimationAction;
  30776. var DoNothingAction = (function (_super) {
  30777. __extends(DoNothingAction, _super);
  30778. function DoNothingAction(triggerOptions, condition) {
  30779. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  30780. _super.call(this, triggerOptions, condition);
  30781. }
  30782. DoNothingAction.prototype.execute = function () {
  30783. };
  30784. return DoNothingAction;
  30785. })(BABYLON.Action);
  30786. BABYLON.DoNothingAction = DoNothingAction;
  30787. var CombineAction = (function (_super) {
  30788. __extends(CombineAction, _super);
  30789. function CombineAction(triggerOptions, children, condition) {
  30790. _super.call(this, triggerOptions, condition);
  30791. this.children = children;
  30792. }
  30793. CombineAction.prototype._prepare = function () {
  30794. for (var index = 0; index < this.children.length; index++) {
  30795. this.children[index]._actionManager = this._actionManager;
  30796. this.children[index]._prepare();
  30797. }
  30798. };
  30799. CombineAction.prototype.execute = function (evt) {
  30800. for (var index = 0; index < this.children.length; index++) {
  30801. this.children[index].execute(evt);
  30802. }
  30803. };
  30804. return CombineAction;
  30805. })(BABYLON.Action);
  30806. BABYLON.CombineAction = CombineAction;
  30807. var ExecuteCodeAction = (function (_super) {
  30808. __extends(ExecuteCodeAction, _super);
  30809. function ExecuteCodeAction(triggerOptions, func, condition) {
  30810. _super.call(this, triggerOptions, condition);
  30811. this.func = func;
  30812. }
  30813. ExecuteCodeAction.prototype.execute = function (evt) {
  30814. this.func(evt);
  30815. };
  30816. return ExecuteCodeAction;
  30817. })(BABYLON.Action);
  30818. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  30819. var SetParentAction = (function (_super) {
  30820. __extends(SetParentAction, _super);
  30821. function SetParentAction(triggerOptions, target, parent, condition) {
  30822. _super.call(this, triggerOptions, condition);
  30823. this._target = target;
  30824. this._parent = parent;
  30825. }
  30826. SetParentAction.prototype._prepare = function () {
  30827. };
  30828. SetParentAction.prototype.execute = function () {
  30829. if (this._target.parent === this._parent) {
  30830. return;
  30831. }
  30832. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  30833. invertParentWorldMatrix.invert();
  30834. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  30835. this._target.parent = this._parent;
  30836. };
  30837. return SetParentAction;
  30838. })(BABYLON.Action);
  30839. BABYLON.SetParentAction = SetParentAction;
  30840. var PlaySoundAction = (function (_super) {
  30841. __extends(PlaySoundAction, _super);
  30842. function PlaySoundAction(triggerOptions, sound, condition) {
  30843. _super.call(this, triggerOptions, condition);
  30844. this._sound = sound;
  30845. }
  30846. PlaySoundAction.prototype._prepare = function () {
  30847. };
  30848. PlaySoundAction.prototype.execute = function () {
  30849. if (this._sound !== undefined)
  30850. this._sound.play();
  30851. };
  30852. return PlaySoundAction;
  30853. })(BABYLON.Action);
  30854. BABYLON.PlaySoundAction = PlaySoundAction;
  30855. var StopSoundAction = (function (_super) {
  30856. __extends(StopSoundAction, _super);
  30857. function StopSoundAction(triggerOptions, sound, condition) {
  30858. _super.call(this, triggerOptions, condition);
  30859. this._sound = sound;
  30860. }
  30861. StopSoundAction.prototype._prepare = function () {
  30862. };
  30863. StopSoundAction.prototype.execute = function () {
  30864. if (this._sound !== undefined)
  30865. this._sound.stop();
  30866. };
  30867. return StopSoundAction;
  30868. })(BABYLON.Action);
  30869. BABYLON.StopSoundAction = StopSoundAction;
  30870. })(BABYLON || (BABYLON = {}));
  30871. var BABYLON;
  30872. (function (BABYLON) {
  30873. var Geometry = (function () {
  30874. function Geometry(id, scene, vertexData, updatable, mesh) {
  30875. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30876. this._totalVertices = 0;
  30877. this._isDisposed = false;
  30878. this.id = id;
  30879. this._engine = scene.getEngine();
  30880. this._meshes = [];
  30881. this._scene = scene;
  30882. //Init vertex buffer cache
  30883. this._vertexBuffers = {};
  30884. this._indices = [];
  30885. // vertexData
  30886. if (vertexData) {
  30887. this.setAllVerticesData(vertexData, updatable);
  30888. }
  30889. else {
  30890. this._totalVertices = 0;
  30891. this._indices = [];
  30892. }
  30893. // applyToMesh
  30894. if (mesh) {
  30895. if (mesh instanceof BABYLON.LinesMesh) {
  30896. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  30897. this.updateExtend();
  30898. }
  30899. this.applyToMesh(mesh);
  30900. mesh.computeWorldMatrix(true);
  30901. }
  30902. }
  30903. Object.defineProperty(Geometry.prototype, "boundingBias", {
  30904. /**
  30905. * 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
  30906. * @returns The Bias Vector
  30907. */
  30908. get: function () {
  30909. return this._boundingBias;
  30910. },
  30911. set: function (value) {
  30912. if (this._boundingBias && this._boundingBias.equals(value)) {
  30913. return;
  30914. }
  30915. this._boundingBias = value.clone();
  30916. this.updateBoundingInfo(true, null);
  30917. },
  30918. enumerable: true,
  30919. configurable: true
  30920. });
  30921. Object.defineProperty(Geometry.prototype, "extend", {
  30922. get: function () {
  30923. return this._extend;
  30924. },
  30925. enumerable: true,
  30926. configurable: true
  30927. });
  30928. Geometry.prototype.getScene = function () {
  30929. return this._scene;
  30930. };
  30931. Geometry.prototype.getEngine = function () {
  30932. return this._engine;
  30933. };
  30934. Geometry.prototype.isReady = function () {
  30935. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  30936. };
  30937. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  30938. vertexData.applyToGeometry(this, updatable);
  30939. this.notifyUpdate();
  30940. };
  30941. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  30942. if (this._vertexBuffers[kind]) {
  30943. this._vertexBuffers[kind].dispose();
  30944. }
  30945. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  30946. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30947. stride = this._vertexBuffers[kind].getStrideSize();
  30948. this._totalVertices = data.length / stride;
  30949. this.updateExtend(data);
  30950. var meshes = this._meshes;
  30951. var numOfMeshes = meshes.length;
  30952. for (var index = 0; index < numOfMeshes; index++) {
  30953. var mesh = meshes[index];
  30954. mesh._resetPointsArrayCache();
  30955. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30956. mesh._createGlobalSubMesh();
  30957. mesh.computeWorldMatrix(true);
  30958. }
  30959. }
  30960. this.notifyUpdate(kind);
  30961. };
  30962. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  30963. var vertexBuffer = this.getVertexBuffer(kind);
  30964. if (!vertexBuffer) {
  30965. return;
  30966. }
  30967. vertexBuffer.updateDirectly(data, offset);
  30968. this.notifyUpdate(kind);
  30969. };
  30970. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  30971. var vertexBuffer = this.getVertexBuffer(kind);
  30972. if (!vertexBuffer) {
  30973. return;
  30974. }
  30975. vertexBuffer.update(data);
  30976. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30977. var stride = vertexBuffer.getStrideSize();
  30978. this._totalVertices = data.length / stride;
  30979. this.updateBoundingInfo(updateExtends, data);
  30980. }
  30981. this.notifyUpdate(kind);
  30982. };
  30983. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  30984. if (updateExtends) {
  30985. this.updateExtend(data);
  30986. }
  30987. var meshes = this._meshes;
  30988. var numOfMeshes = meshes.length;
  30989. for (var index = 0; index < numOfMeshes; index++) {
  30990. var mesh = meshes[index];
  30991. mesh._resetPointsArrayCache();
  30992. if (updateExtends) {
  30993. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30994. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30995. var subMesh = mesh.subMeshes[subIndex];
  30996. subMesh.refreshBoundingInfo();
  30997. }
  30998. }
  30999. }
  31000. };
  31001. Geometry.prototype.getTotalVertices = function () {
  31002. if (!this.isReady()) {
  31003. return 0;
  31004. }
  31005. return this._totalVertices;
  31006. };
  31007. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  31008. var vertexBuffer = this.getVertexBuffer(kind);
  31009. if (!vertexBuffer) {
  31010. return null;
  31011. }
  31012. var orig = vertexBuffer.getData();
  31013. if (!copyWhenShared || this._meshes.length === 1) {
  31014. return orig;
  31015. }
  31016. else {
  31017. var len = orig.length;
  31018. var copy = [];
  31019. for (var i = 0; i < len; i++) {
  31020. copy.push(orig[i]);
  31021. }
  31022. return copy;
  31023. }
  31024. };
  31025. Geometry.prototype.getVertexBuffer = function (kind) {
  31026. if (!this.isReady()) {
  31027. return null;
  31028. }
  31029. return this._vertexBuffers[kind];
  31030. };
  31031. Geometry.prototype.getVertexBuffers = function () {
  31032. if (!this.isReady()) {
  31033. return null;
  31034. }
  31035. return this._vertexBuffers;
  31036. };
  31037. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31038. if (!this._vertexBuffers) {
  31039. if (this._delayInfo) {
  31040. return this._delayInfo.indexOf(kind) !== -1;
  31041. }
  31042. return false;
  31043. }
  31044. return this._vertexBuffers[kind] !== undefined;
  31045. };
  31046. Geometry.prototype.getVerticesDataKinds = function () {
  31047. var result = [];
  31048. var kind;
  31049. if (!this._vertexBuffers && this._delayInfo) {
  31050. for (kind in this._delayInfo) {
  31051. result.push(kind);
  31052. }
  31053. }
  31054. else {
  31055. for (kind in this._vertexBuffers) {
  31056. result.push(kind);
  31057. }
  31058. }
  31059. return result;
  31060. };
  31061. Geometry.prototype.setIndices = function (indices, totalVertices) {
  31062. if (this._indexBuffer) {
  31063. this._engine._releaseBuffer(this._indexBuffer);
  31064. }
  31065. this._indices = indices;
  31066. if (this._meshes.length !== 0 && this._indices) {
  31067. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31068. }
  31069. if (totalVertices !== undefined) {
  31070. this._totalVertices = totalVertices;
  31071. }
  31072. var meshes = this._meshes;
  31073. var numOfMeshes = meshes.length;
  31074. for (var index = 0; index < numOfMeshes; index++) {
  31075. meshes[index]._createGlobalSubMesh();
  31076. }
  31077. this.notifyUpdate();
  31078. };
  31079. Geometry.prototype.getTotalIndices = function () {
  31080. if (!this.isReady()) {
  31081. return 0;
  31082. }
  31083. return this._indices.length;
  31084. };
  31085. Geometry.prototype.getIndices = function (copyWhenShared) {
  31086. if (!this.isReady()) {
  31087. return null;
  31088. }
  31089. var orig = this._indices;
  31090. if (!copyWhenShared || this._meshes.length === 1) {
  31091. return orig;
  31092. }
  31093. else {
  31094. var len = orig.length;
  31095. var copy = [];
  31096. for (var i = 0; i < len; i++) {
  31097. copy.push(orig[i]);
  31098. }
  31099. return copy;
  31100. }
  31101. };
  31102. Geometry.prototype.getIndexBuffer = function () {
  31103. if (!this.isReady()) {
  31104. return null;
  31105. }
  31106. return this._indexBuffer;
  31107. };
  31108. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31109. var meshes = this._meshes;
  31110. var index = meshes.indexOf(mesh);
  31111. if (index === -1) {
  31112. return;
  31113. }
  31114. for (var kind in this._vertexBuffers) {
  31115. this._vertexBuffers[kind].dispose();
  31116. }
  31117. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  31118. this._indexBuffer = null;
  31119. }
  31120. meshes.splice(index, 1);
  31121. mesh._geometry = null;
  31122. if (meshes.length === 0 && shouldDispose) {
  31123. this.dispose();
  31124. }
  31125. };
  31126. Geometry.prototype.applyToMesh = function (mesh) {
  31127. if (mesh._geometry === this) {
  31128. return;
  31129. }
  31130. var previousGeometry = mesh._geometry;
  31131. if (previousGeometry) {
  31132. previousGeometry.releaseForMesh(mesh);
  31133. }
  31134. var meshes = this._meshes;
  31135. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31136. mesh._geometry = this;
  31137. this._scene.pushGeometry(this);
  31138. meshes.push(mesh);
  31139. if (this.isReady()) {
  31140. this._applyToMesh(mesh);
  31141. }
  31142. else {
  31143. mesh._boundingInfo = this._boundingInfo;
  31144. }
  31145. };
  31146. Geometry.prototype.updateExtend = function (data) {
  31147. if (data === void 0) { data = null; }
  31148. if (!data) {
  31149. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31150. }
  31151. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias);
  31152. };
  31153. Geometry.prototype._applyToMesh = function (mesh) {
  31154. var numOfMeshes = this._meshes.length;
  31155. // vertexBuffers
  31156. for (var kind in this._vertexBuffers) {
  31157. if (numOfMeshes === 1) {
  31158. this._vertexBuffers[kind].create();
  31159. }
  31160. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  31161. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31162. mesh._resetPointsArrayCache();
  31163. if (!this._extend) {
  31164. this.updateExtend(this._vertexBuffers[kind].getData());
  31165. }
  31166. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31167. mesh._createGlobalSubMesh();
  31168. //bounding info was just created again, world matrix should be applied again.
  31169. mesh._updateBoundingInfo();
  31170. }
  31171. }
  31172. // indexBuffer
  31173. if (numOfMeshes === 1 && this._indices) {
  31174. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31175. }
  31176. if (this._indexBuffer) {
  31177. this._indexBuffer.references = numOfMeshes;
  31178. }
  31179. };
  31180. Geometry.prototype.notifyUpdate = function (kind) {
  31181. if (this.onGeometryUpdated) {
  31182. this.onGeometryUpdated(this, kind);
  31183. }
  31184. };
  31185. Geometry.prototype.load = function (scene, onLoaded) {
  31186. var _this = this;
  31187. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31188. return;
  31189. }
  31190. if (this.isReady()) {
  31191. if (onLoaded) {
  31192. onLoaded();
  31193. }
  31194. return;
  31195. }
  31196. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31197. scene._addPendingData(this);
  31198. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31199. _this._delayLoadingFunction(JSON.parse(data), _this);
  31200. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31201. _this._delayInfo = [];
  31202. scene._removePendingData(_this);
  31203. var meshes = _this._meshes;
  31204. var numOfMeshes = meshes.length;
  31205. for (var index = 0; index < numOfMeshes; index++) {
  31206. _this._applyToMesh(meshes[index]);
  31207. }
  31208. if (onLoaded) {
  31209. onLoaded();
  31210. }
  31211. }, function () { }, scene.database);
  31212. };
  31213. Geometry.prototype.isDisposed = function () {
  31214. return this._isDisposed;
  31215. };
  31216. Geometry.prototype.dispose = function () {
  31217. var meshes = this._meshes;
  31218. var numOfMeshes = meshes.length;
  31219. var index;
  31220. for (index = 0; index < numOfMeshes; index++) {
  31221. this.releaseForMesh(meshes[index]);
  31222. }
  31223. this._meshes = [];
  31224. for (var kind in this._vertexBuffers) {
  31225. this._vertexBuffers[kind].dispose();
  31226. }
  31227. this._vertexBuffers = [];
  31228. this._totalVertices = 0;
  31229. if (this._indexBuffer) {
  31230. this._engine._releaseBuffer(this._indexBuffer);
  31231. }
  31232. this._indexBuffer = null;
  31233. this._indices = [];
  31234. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31235. this.delayLoadingFile = null;
  31236. this._delayLoadingFunction = null;
  31237. this._delayInfo = [];
  31238. this._boundingInfo = null;
  31239. this._scene.removeGeometry(this);
  31240. this._isDisposed = true;
  31241. };
  31242. Geometry.prototype.copy = function (id) {
  31243. var vertexData = new BABYLON.VertexData();
  31244. vertexData.indices = [];
  31245. var indices = this.getIndices();
  31246. for (var index = 0; index < indices.length; index++) {
  31247. vertexData.indices.push(indices[index]);
  31248. }
  31249. var updatable = false;
  31250. var stopChecking = false;
  31251. var kind;
  31252. for (kind in this._vertexBuffers) {
  31253. // using slice() to make a copy of the array and not just reference it
  31254. var data = this.getVerticesData(kind);
  31255. if (data instanceof Float32Array) {
  31256. vertexData.set(new Float32Array(data), kind);
  31257. }
  31258. else {
  31259. vertexData.set(data.slice(0), kind);
  31260. }
  31261. if (!stopChecking) {
  31262. updatable = this.getVertexBuffer(kind).isUpdatable();
  31263. stopChecking = !updatable;
  31264. }
  31265. }
  31266. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  31267. geometry.delayLoadState = this.delayLoadState;
  31268. geometry.delayLoadingFile = this.delayLoadingFile;
  31269. geometry._delayLoadingFunction = this._delayLoadingFunction;
  31270. for (kind in this._delayInfo) {
  31271. geometry._delayInfo = geometry._delayInfo || [];
  31272. geometry._delayInfo.push(kind);
  31273. }
  31274. // Bounding info
  31275. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31276. return geometry;
  31277. };
  31278. Geometry.prototype.serialize = function () {
  31279. var serializationObject = {};
  31280. serializationObject.id = this.id;
  31281. if (BABYLON.Tags.HasTags(this)) {
  31282. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31283. }
  31284. return serializationObject;
  31285. };
  31286. Geometry.prototype.serializeVerticeData = function () {
  31287. var serializationObject = this.serialize();
  31288. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31289. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31290. }
  31291. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31292. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31293. }
  31294. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31295. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31296. }
  31297. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31298. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  31299. }
  31300. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31301. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  31302. }
  31303. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31304. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  31305. }
  31306. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31307. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  31308. }
  31309. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31310. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  31311. }
  31312. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31313. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  31314. }
  31315. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31316. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31317. serializationObject.matricesIndices._isExpanded = true;
  31318. }
  31319. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31320. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31321. }
  31322. serializationObject.indices = this.getIndices();
  31323. return serializationObject;
  31324. };
  31325. // Statics
  31326. Geometry.ExtractFromMesh = function (mesh, id) {
  31327. var geometry = mesh._geometry;
  31328. if (!geometry) {
  31329. return null;
  31330. }
  31331. return geometry.copy(id);
  31332. };
  31333. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  31334. // be aware Math.random() could cause collisions
  31335. Geometry.RandomId = function () {
  31336. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  31337. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  31338. return v.toString(16);
  31339. });
  31340. };
  31341. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  31342. var scene = mesh.getScene();
  31343. // Geometry
  31344. var geometryId = parsedGeometry.geometryId;
  31345. if (geometryId) {
  31346. var geometry = scene.getGeometryByID(geometryId);
  31347. if (geometry) {
  31348. geometry.applyToMesh(mesh);
  31349. }
  31350. }
  31351. else if (parsedGeometry instanceof ArrayBuffer) {
  31352. var binaryInfo = mesh._binaryInfo;
  31353. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  31354. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  31355. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  31356. }
  31357. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  31358. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  31359. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  31360. }
  31361. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  31362. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  31363. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  31364. }
  31365. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  31366. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  31367. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  31368. }
  31369. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  31370. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  31371. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  31372. }
  31373. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  31374. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  31375. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  31376. }
  31377. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  31378. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  31379. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  31380. }
  31381. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  31382. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  31383. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  31384. }
  31385. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  31386. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  31387. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  31388. }
  31389. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  31390. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  31391. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  31392. }
  31393. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  31394. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  31395. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  31396. }
  31397. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31398. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31399. mesh.setIndices(indicesData);
  31400. }
  31401. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31402. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31403. mesh.subMeshes = [];
  31404. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31405. var materialIndex = subMeshesData[(i * 5) + 0];
  31406. var verticesStart = subMeshesData[(i * 5) + 1];
  31407. var verticesCount = subMeshesData[(i * 5) + 2];
  31408. var indexStart = subMeshesData[(i * 5) + 3];
  31409. var indexCount = subMeshesData[(i * 5) + 4];
  31410. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31411. }
  31412. }
  31413. }
  31414. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31415. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  31416. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  31417. if (parsedGeometry.uvs) {
  31418. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  31419. }
  31420. if (parsedGeometry.uvs2) {
  31421. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  31422. }
  31423. if (parsedGeometry.uvs3) {
  31424. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  31425. }
  31426. if (parsedGeometry.uvs4) {
  31427. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  31428. }
  31429. if (parsedGeometry.uvs5) {
  31430. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  31431. }
  31432. if (parsedGeometry.uvs6) {
  31433. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  31434. }
  31435. if (parsedGeometry.colors) {
  31436. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  31437. }
  31438. if (parsedGeometry.matricesIndices) {
  31439. if (!parsedGeometry.matricesIndices._isExpanded) {
  31440. var floatIndices = [];
  31441. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  31442. var matricesIndex = parsedGeometry.matricesIndices[i];
  31443. floatIndices.push(matricesIndex & 0x000000FF);
  31444. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31445. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31446. floatIndices.push(matricesIndex >> 24);
  31447. }
  31448. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  31449. }
  31450. else {
  31451. delete parsedGeometry.matricesIndices._isExpanded;
  31452. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  31453. }
  31454. }
  31455. if (parsedGeometry.matricesIndicesExtra) {
  31456. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  31457. var floatIndices = [];
  31458. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  31459. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  31460. floatIndices.push(matricesIndex & 0x000000FF);
  31461. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31462. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31463. floatIndices.push(matricesIndex >> 24);
  31464. }
  31465. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  31466. }
  31467. else {
  31468. delete parsedGeometry.matricesIndices._isExpanded;
  31469. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  31470. }
  31471. }
  31472. if (parsedGeometry.matricesWeights) {
  31473. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  31474. }
  31475. if (parsedGeometry.matricesWeightsExtra) {
  31476. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  31477. }
  31478. mesh.setIndices(parsedGeometry.indices);
  31479. }
  31480. // SubMeshes
  31481. if (parsedGeometry.subMeshes) {
  31482. mesh.subMeshes = [];
  31483. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  31484. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  31485. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  31486. }
  31487. }
  31488. // Flat shading
  31489. if (mesh._shouldGenerateFlatShading) {
  31490. mesh.convertToFlatShadedMesh();
  31491. delete mesh._shouldGenerateFlatShading;
  31492. }
  31493. // Update
  31494. mesh.computeWorldMatrix(true);
  31495. // Octree
  31496. if (scene['_selectionOctree']) {
  31497. scene['_selectionOctree'].addMesh(mesh);
  31498. }
  31499. };
  31500. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  31501. if (scene.getGeometryByID(parsedVertexData.id)) {
  31502. return null; // null since geometry could be something else than a box...
  31503. }
  31504. var geometry = new Geometry(parsedVertexData.id, scene);
  31505. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  31506. if (parsedVertexData.delayLoadingFile) {
  31507. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31508. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  31509. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  31510. geometry._delayInfo = [];
  31511. if (parsedVertexData.hasUVs) {
  31512. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  31513. }
  31514. if (parsedVertexData.hasUVs2) {
  31515. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  31516. }
  31517. if (parsedVertexData.hasUVs3) {
  31518. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  31519. }
  31520. if (parsedVertexData.hasUVs4) {
  31521. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  31522. }
  31523. if (parsedVertexData.hasUVs5) {
  31524. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  31525. }
  31526. if (parsedVertexData.hasUVs6) {
  31527. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  31528. }
  31529. if (parsedVertexData.hasColors) {
  31530. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  31531. }
  31532. if (parsedVertexData.hasMatricesIndices) {
  31533. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31534. }
  31535. if (parsedVertexData.hasMatricesWeights) {
  31536. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31537. }
  31538. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  31539. }
  31540. else {
  31541. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  31542. }
  31543. scene.pushGeometry(geometry, true);
  31544. return geometry;
  31545. };
  31546. return Geometry;
  31547. })();
  31548. BABYLON.Geometry = Geometry;
  31549. /////// Primitives //////////////////////////////////////////////
  31550. var Geometry;
  31551. (function (Geometry) {
  31552. var Primitives;
  31553. (function (Primitives) {
  31554. /// Abstract class
  31555. var _Primitive = (function (_super) {
  31556. __extends(_Primitive, _super);
  31557. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  31558. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  31559. this._canBeRegenerated = _canBeRegenerated;
  31560. this._beingRegenerated = true;
  31561. this.regenerate();
  31562. this._beingRegenerated = false;
  31563. }
  31564. _Primitive.prototype.canBeRegenerated = function () {
  31565. return this._canBeRegenerated;
  31566. };
  31567. _Primitive.prototype.regenerate = function () {
  31568. if (!this._canBeRegenerated) {
  31569. return;
  31570. }
  31571. this._beingRegenerated = true;
  31572. this.setAllVerticesData(this._regenerateVertexData(), false);
  31573. this._beingRegenerated = false;
  31574. };
  31575. _Primitive.prototype.asNewGeometry = function (id) {
  31576. return _super.prototype.copy.call(this, id);
  31577. };
  31578. // overrides
  31579. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  31580. if (!this._beingRegenerated) {
  31581. return;
  31582. }
  31583. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  31584. };
  31585. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  31586. if (!this._beingRegenerated) {
  31587. return;
  31588. }
  31589. _super.prototype.setVerticesData.call(this, kind, data, false);
  31590. };
  31591. // to override
  31592. // protected
  31593. _Primitive.prototype._regenerateVertexData = function () {
  31594. throw new Error("Abstract method");
  31595. };
  31596. _Primitive.prototype.copy = function (id) {
  31597. throw new Error("Must be overriden in sub-classes.");
  31598. };
  31599. _Primitive.prototype.serialize = function () {
  31600. var serializationObject = _super.prototype.serialize.call(this);
  31601. serializationObject.canBeRegenerated = this.canBeRegenerated();
  31602. return serializationObject;
  31603. };
  31604. return _Primitive;
  31605. })(Geometry);
  31606. Primitives._Primitive = _Primitive;
  31607. var Ribbon = (function (_super) {
  31608. __extends(Ribbon, _super);
  31609. // Members
  31610. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  31611. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31612. _super.call(this, id, scene, canBeRegenerated, mesh);
  31613. this.pathArray = pathArray;
  31614. this.closeArray = closeArray;
  31615. this.closePath = closePath;
  31616. this.offset = offset;
  31617. this.side = side;
  31618. }
  31619. Ribbon.prototype._regenerateVertexData = function () {
  31620. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  31621. };
  31622. Ribbon.prototype.copy = function (id) {
  31623. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  31624. };
  31625. return Ribbon;
  31626. })(_Primitive);
  31627. Primitives.Ribbon = Ribbon;
  31628. var Box = (function (_super) {
  31629. __extends(Box, _super);
  31630. // Members
  31631. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  31632. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31633. _super.call(this, id, scene, canBeRegenerated, mesh);
  31634. this.size = size;
  31635. this.side = side;
  31636. }
  31637. Box.prototype._regenerateVertexData = function () {
  31638. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  31639. };
  31640. Box.prototype.copy = function (id) {
  31641. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  31642. };
  31643. Box.prototype.serialize = function () {
  31644. var serializationObject = _super.prototype.serialize.call(this);
  31645. serializationObject.size = this.size;
  31646. return serializationObject;
  31647. };
  31648. Box.Parse = function (parsedBox, scene) {
  31649. if (scene.getGeometryByID(parsedBox.id)) {
  31650. return null; // null since geometry could be something else than a box...
  31651. }
  31652. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  31653. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  31654. scene.pushGeometry(box, true);
  31655. return box;
  31656. };
  31657. return Box;
  31658. })(_Primitive);
  31659. Primitives.Box = Box;
  31660. var Sphere = (function (_super) {
  31661. __extends(Sphere, _super);
  31662. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  31663. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31664. _super.call(this, id, scene, canBeRegenerated, mesh);
  31665. this.segments = segments;
  31666. this.diameter = diameter;
  31667. this.side = side;
  31668. }
  31669. Sphere.prototype._regenerateVertexData = function () {
  31670. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  31671. };
  31672. Sphere.prototype.copy = function (id) {
  31673. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  31674. };
  31675. Sphere.prototype.serialize = function () {
  31676. var serializationObject = _super.prototype.serialize.call(this);
  31677. serializationObject.segments = this.segments;
  31678. serializationObject.diameter = this.diameter;
  31679. return serializationObject;
  31680. };
  31681. Sphere.Parse = function (parsedSphere, scene) {
  31682. if (scene.getGeometryByID(parsedSphere.id)) {
  31683. return null; // null since geometry could be something else than a sphere...
  31684. }
  31685. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  31686. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  31687. scene.pushGeometry(sphere, true);
  31688. return sphere;
  31689. };
  31690. return Sphere;
  31691. })(_Primitive);
  31692. Primitives.Sphere = Sphere;
  31693. var Disc = (function (_super) {
  31694. __extends(Disc, _super);
  31695. // Members
  31696. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  31697. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31698. _super.call(this, id, scene, canBeRegenerated, mesh);
  31699. this.radius = radius;
  31700. this.tessellation = tessellation;
  31701. this.side = side;
  31702. }
  31703. Disc.prototype._regenerateVertexData = function () {
  31704. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  31705. };
  31706. Disc.prototype.copy = function (id) {
  31707. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  31708. };
  31709. return Disc;
  31710. })(_Primitive);
  31711. Primitives.Disc = Disc;
  31712. var Cylinder = (function (_super) {
  31713. __extends(Cylinder, _super);
  31714. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  31715. if (subdivisions === void 0) { subdivisions = 1; }
  31716. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31717. _super.call(this, id, scene, canBeRegenerated, mesh);
  31718. this.height = height;
  31719. this.diameterTop = diameterTop;
  31720. this.diameterBottom = diameterBottom;
  31721. this.tessellation = tessellation;
  31722. this.subdivisions = subdivisions;
  31723. this.side = side;
  31724. }
  31725. Cylinder.prototype._regenerateVertexData = function () {
  31726. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  31727. };
  31728. Cylinder.prototype.copy = function (id) {
  31729. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  31730. };
  31731. Cylinder.prototype.serialize = function () {
  31732. var serializationObject = _super.prototype.serialize.call(this);
  31733. serializationObject.height = this.height;
  31734. serializationObject.diameterTop = this.diameterTop;
  31735. serializationObject.diameterBottom = this.diameterBottom;
  31736. serializationObject.tessellation = this.tessellation;
  31737. return serializationObject;
  31738. };
  31739. Cylinder.Parse = function (parsedCylinder, scene) {
  31740. if (scene.getGeometryByID(parsedCylinder.id)) {
  31741. return null; // null since geometry could be something else than a cylinder...
  31742. }
  31743. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  31744. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  31745. scene.pushGeometry(cylinder, true);
  31746. return cylinder;
  31747. };
  31748. return Cylinder;
  31749. })(_Primitive);
  31750. Primitives.Cylinder = Cylinder;
  31751. var Torus = (function (_super) {
  31752. __extends(Torus, _super);
  31753. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  31754. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31755. _super.call(this, id, scene, canBeRegenerated, mesh);
  31756. this.diameter = diameter;
  31757. this.thickness = thickness;
  31758. this.tessellation = tessellation;
  31759. this.side = side;
  31760. }
  31761. Torus.prototype._regenerateVertexData = function () {
  31762. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  31763. };
  31764. Torus.prototype.copy = function (id) {
  31765. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  31766. };
  31767. Torus.prototype.serialize = function () {
  31768. var serializationObject = _super.prototype.serialize.call(this);
  31769. serializationObject.diameter = this.diameter;
  31770. serializationObject.thickness = this.thickness;
  31771. serializationObject.tessellation = this.tessellation;
  31772. return serializationObject;
  31773. };
  31774. Torus.Parse = function (parsedTorus, scene) {
  31775. if (scene.getGeometryByID(parsedTorus.id)) {
  31776. return null; // null since geometry could be something else than a torus...
  31777. }
  31778. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  31779. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  31780. scene.pushGeometry(torus, true);
  31781. return torus;
  31782. };
  31783. return Torus;
  31784. })(_Primitive);
  31785. Primitives.Torus = Torus;
  31786. var Ground = (function (_super) {
  31787. __extends(Ground, _super);
  31788. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  31789. _super.call(this, id, scene, canBeRegenerated, mesh);
  31790. this.width = width;
  31791. this.height = height;
  31792. this.subdivisions = subdivisions;
  31793. }
  31794. Ground.prototype._regenerateVertexData = function () {
  31795. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  31796. };
  31797. Ground.prototype.copy = function (id) {
  31798. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  31799. };
  31800. Ground.prototype.serialize = function () {
  31801. var serializationObject = _super.prototype.serialize.call(this);
  31802. serializationObject.width = this.width;
  31803. serializationObject.height = this.height;
  31804. serializationObject.subdivisions = this.subdivisions;
  31805. return serializationObject;
  31806. };
  31807. Ground.Parse = function (parsedGround, scene) {
  31808. if (scene.getGeometryByID(parsedGround.id)) {
  31809. return null; // null since geometry could be something else than a ground...
  31810. }
  31811. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  31812. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  31813. scene.pushGeometry(ground, true);
  31814. return ground;
  31815. };
  31816. return Ground;
  31817. })(_Primitive);
  31818. Primitives.Ground = Ground;
  31819. var TiledGround = (function (_super) {
  31820. __extends(TiledGround, _super);
  31821. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  31822. _super.call(this, id, scene, canBeRegenerated, mesh);
  31823. this.xmin = xmin;
  31824. this.zmin = zmin;
  31825. this.xmax = xmax;
  31826. this.zmax = zmax;
  31827. this.subdivisions = subdivisions;
  31828. this.precision = precision;
  31829. }
  31830. TiledGround.prototype._regenerateVertexData = function () {
  31831. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  31832. };
  31833. TiledGround.prototype.copy = function (id) {
  31834. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  31835. };
  31836. return TiledGround;
  31837. })(_Primitive);
  31838. Primitives.TiledGround = TiledGround;
  31839. var Plane = (function (_super) {
  31840. __extends(Plane, _super);
  31841. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  31842. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31843. _super.call(this, id, scene, canBeRegenerated, mesh);
  31844. this.size = size;
  31845. this.side = side;
  31846. }
  31847. Plane.prototype._regenerateVertexData = function () {
  31848. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  31849. };
  31850. Plane.prototype.copy = function (id) {
  31851. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  31852. };
  31853. Plane.prototype.serialize = function () {
  31854. var serializationObject = _super.prototype.serialize.call(this);
  31855. serializationObject.size = this.size;
  31856. return serializationObject;
  31857. };
  31858. Plane.Parse = function (parsedPlane, scene) {
  31859. if (scene.getGeometryByID(parsedPlane.id)) {
  31860. return null; // null since geometry could be something else than a ground...
  31861. }
  31862. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  31863. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  31864. scene.pushGeometry(plane, true);
  31865. return plane;
  31866. };
  31867. return Plane;
  31868. })(_Primitive);
  31869. Primitives.Plane = Plane;
  31870. var TorusKnot = (function (_super) {
  31871. __extends(TorusKnot, _super);
  31872. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  31873. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31874. _super.call(this, id, scene, canBeRegenerated, mesh);
  31875. this.radius = radius;
  31876. this.tube = tube;
  31877. this.radialSegments = radialSegments;
  31878. this.tubularSegments = tubularSegments;
  31879. this.p = p;
  31880. this.q = q;
  31881. this.side = side;
  31882. }
  31883. TorusKnot.prototype._regenerateVertexData = function () {
  31884. 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 });
  31885. };
  31886. TorusKnot.prototype.copy = function (id) {
  31887. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  31888. };
  31889. TorusKnot.prototype.serialize = function () {
  31890. var serializationObject = _super.prototype.serialize.call(this);
  31891. serializationObject.radius = this.radius;
  31892. serializationObject.tube = this.tube;
  31893. serializationObject.radialSegments = this.radialSegments;
  31894. serializationObject.tubularSegments = this.tubularSegments;
  31895. serializationObject.p = this.p;
  31896. serializationObject.q = this.q;
  31897. return serializationObject;
  31898. };
  31899. ;
  31900. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  31901. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  31902. return null; // null since geometry could be something else than a ground...
  31903. }
  31904. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  31905. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  31906. scene.pushGeometry(torusKnot, true);
  31907. return torusKnot;
  31908. };
  31909. return TorusKnot;
  31910. })(_Primitive);
  31911. Primitives.TorusKnot = TorusKnot;
  31912. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  31913. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  31914. })(BABYLON || (BABYLON = {}));
  31915. var BABYLON;
  31916. (function (BABYLON) {
  31917. var GroundMesh = (function (_super) {
  31918. __extends(GroundMesh, _super);
  31919. function GroundMesh(name, scene) {
  31920. _super.call(this, name, scene);
  31921. this.generateOctree = false;
  31922. this._worldInverse = new BABYLON.Matrix();
  31923. }
  31924. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  31925. get: function () {
  31926. return this._subdivisions;
  31927. },
  31928. enumerable: true,
  31929. configurable: true
  31930. });
  31931. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  31932. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  31933. this._subdivisions = chunksCount;
  31934. this.subdivide(this._subdivisions);
  31935. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  31936. };
  31937. /**
  31938. * Returns a height (y) value in the Worl system :
  31939. * the ground altitude at the coordinates (x, z) expressed in the World system.
  31940. * Returns the ground y position if (x, z) are outside the ground surface.
  31941. * Not pertinent if the ground is rotated.
  31942. */
  31943. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  31944. // express x and y in the ground local system
  31945. x -= this.position.x;
  31946. z -= this.position.z;
  31947. x /= this.scaling.x;
  31948. z /= this.scaling.z;
  31949. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  31950. return this.position.y;
  31951. }
  31952. if (!this._heightQuads || this._heightQuads.length == 0) {
  31953. this._initHeightQuads();
  31954. this._computeHeightQuads();
  31955. }
  31956. var facet = this._getFacetAt(x, z);
  31957. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  31958. // return y in the World system
  31959. return y * this.scaling.y + this.position.y;
  31960. };
  31961. /**
  31962. * Returns a normalized vector (Vector3) orthogonal to the ground
  31963. * at the ground coordinates (x, z) expressed in the World system.
  31964. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  31965. * Not pertinent if the ground is rotated.
  31966. */
  31967. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  31968. var normal = new BABYLON.Vector3(0, 1, 0);
  31969. this.getNormalAtCoordinatesToRef(x, z, normal);
  31970. return normal;
  31971. };
  31972. /**
  31973. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  31974. * at the ground coordinates (x, z) expressed in the World system.
  31975. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  31976. * Not pertinent if the ground is rotated.
  31977. */
  31978. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  31979. // express x and y in the ground local system
  31980. x -= this.position.x;
  31981. z -= this.position.z;
  31982. x /= this.scaling.x;
  31983. z /= this.scaling.z;
  31984. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  31985. return;
  31986. }
  31987. if (!this._heightQuads || this._heightQuads.length == 0) {
  31988. this._initHeightQuads();
  31989. this._computeHeightQuads();
  31990. }
  31991. var facet = this._getFacetAt(x, z);
  31992. ref.x = facet.x;
  31993. ref.y = facet.y;
  31994. ref.z = facet.z;
  31995. };
  31996. /**
  31997. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  31998. * if the ground has been updated.
  31999. * This can be used in the render loop
  32000. */
  32001. GroundMesh.prototype.updateCoordinateHeights = function () {
  32002. if (!this._heightQuads || this._heightQuads.length == 0) {
  32003. this._initHeightQuads();
  32004. }
  32005. this._computeHeightQuads();
  32006. };
  32007. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  32008. GroundMesh.prototype._getFacetAt = function (x, z) {
  32009. // retrieve col and row from x, z coordinates in the ground local system
  32010. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  32011. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  32012. var quad = this._heightQuads[row * this._subdivisions + col];
  32013. var facet;
  32014. if (z < quad.slope.x * x + quad.slope.y) {
  32015. facet = quad.facet1;
  32016. }
  32017. else {
  32018. facet = quad.facet2;
  32019. }
  32020. return facet;
  32021. };
  32022. // Creates and populates the heightMap array with "facet" elements :
  32023. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  32024. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  32025. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  32026. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  32027. GroundMesh.prototype._initHeightQuads = function () {
  32028. this._heightQuads = new Array();
  32029. for (var row = 0; row < this._subdivisions; row++) {
  32030. for (var col = 0; col < this._subdivisions; col++) {
  32031. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  32032. this._heightQuads[row * this._subdivisions + col] = quad;
  32033. }
  32034. }
  32035. };
  32036. // Compute each quad element values and update the the heightMap array :
  32037. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  32038. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  32039. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  32040. GroundMesh.prototype._computeHeightQuads = function () {
  32041. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32042. var v1 = BABYLON.Tmp.Vector3[0];
  32043. var v2 = BABYLON.Tmp.Vector3[1];
  32044. var v3 = BABYLON.Tmp.Vector3[2];
  32045. var v4 = BABYLON.Tmp.Vector3[3];
  32046. var v1v2 = BABYLON.Tmp.Vector3[4];
  32047. var v1v3 = BABYLON.Tmp.Vector3[5];
  32048. var v1v4 = BABYLON.Tmp.Vector3[6];
  32049. var norm1 = BABYLON.Tmp.Vector3[7];
  32050. var norm2 = BABYLON.Tmp.Vector3[8];
  32051. var i = 0;
  32052. var j = 0;
  32053. var k = 0;
  32054. var cd = 0; // 2D slope coefficient : z = cd * x + h
  32055. var h = 0;
  32056. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  32057. var d2 = 0;
  32058. for (var row = 0; row < this._subdivisions; row++) {
  32059. for (var col = 0; col < this._subdivisions; col++) {
  32060. i = col * 3;
  32061. j = row * (this._subdivisions + 1) * 3;
  32062. k = (row + 1) * (this._subdivisions + 1) * 3;
  32063. v1.x = positions[j + i];
  32064. v1.y = positions[j + i + 1];
  32065. v1.z = positions[j + i + 2];
  32066. v2.x = positions[j + i + 3];
  32067. v2.y = positions[j + i + 4];
  32068. v2.z = positions[j + i + 5];
  32069. v3.x = positions[k + i];
  32070. v3.y = positions[k + i + 1];
  32071. v3.z = positions[k + i + 2];
  32072. v4.x = positions[k + i + 3];
  32073. v4.y = positions[k + i + 4];
  32074. v4.z = positions[k + i + 5];
  32075. // 2D slope V1V4
  32076. cd = (v4.z - v1.z) / (v4.x - v1.x);
  32077. h = v1.z - cd * v1.x; // v1 belongs to the slope
  32078. // facet equations :
  32079. // we compute each facet normal vector
  32080. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  32081. // we compute the value d by applying the equation to v1 which belongs to the plane
  32082. // then we store the facet equation in a Vector4
  32083. v2.subtractToRef(v1, v1v2);
  32084. v3.subtractToRef(v1, v1v3);
  32085. v4.subtractToRef(v1, v1v4);
  32086. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  32087. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  32088. norm1.normalize();
  32089. norm2.normalize();
  32090. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  32091. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  32092. var quad = this._heightQuads[row * this._subdivisions + col];
  32093. quad.slope.copyFromFloats(cd, h);
  32094. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  32095. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  32096. }
  32097. }
  32098. };
  32099. return GroundMesh;
  32100. })(BABYLON.Mesh);
  32101. BABYLON.GroundMesh = GroundMesh;
  32102. })(BABYLON || (BABYLON = {}));
  32103. var BABYLON;
  32104. (function (BABYLON) {
  32105. var LinesMesh = (function (_super) {
  32106. __extends(LinesMesh, _super);
  32107. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  32108. if (parent === void 0) { parent = null; }
  32109. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  32110. this.color = new BABYLON.Color3(1, 1, 1);
  32111. this.alpha = 1;
  32112. this._intersectionThreshold = 0.1;
  32113. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  32114. attributes: ["position"],
  32115. uniforms: ["worldViewProjection", "color"],
  32116. needAlphaBlending: true
  32117. });
  32118. }
  32119. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  32120. /**
  32121. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  32122. * This margin is expressed in world space coordinates, so its value may vary.
  32123. * Default value is 0.1
  32124. * @returns the intersection Threshold value.
  32125. */
  32126. get: function () {
  32127. return this._intersectionThreshold;
  32128. },
  32129. /**
  32130. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  32131. * This margin is expressed in world space coordinates, so its value may vary.
  32132. * @param value the new threshold to apply
  32133. */
  32134. set: function (value) {
  32135. if (this._intersectionThreshold === value) {
  32136. return;
  32137. }
  32138. this._intersectionThreshold = value;
  32139. if (this.geometry) {
  32140. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  32141. }
  32142. },
  32143. enumerable: true,
  32144. configurable: true
  32145. });
  32146. Object.defineProperty(LinesMesh.prototype, "material", {
  32147. get: function () {
  32148. return this._colorShader;
  32149. },
  32150. enumerable: true,
  32151. configurable: true
  32152. });
  32153. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  32154. get: function () {
  32155. return true;
  32156. },
  32157. enumerable: true,
  32158. configurable: true
  32159. });
  32160. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  32161. get: function () {
  32162. return false;
  32163. },
  32164. enumerable: true,
  32165. configurable: true
  32166. });
  32167. LinesMesh.prototype.createInstance = function (name) {
  32168. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  32169. return null;
  32170. };
  32171. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  32172. var engine = this.getScene().getEngine();
  32173. var indexToBind = this._geometry.getIndexBuffer();
  32174. // VBOs
  32175. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  32176. // Color
  32177. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  32178. };
  32179. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  32180. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  32181. return;
  32182. }
  32183. var engine = this.getScene().getEngine();
  32184. // Draw order
  32185. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  32186. };
  32187. LinesMesh.prototype.dispose = function (doNotRecurse) {
  32188. this._colorShader.dispose();
  32189. _super.prototype.dispose.call(this, doNotRecurse);
  32190. };
  32191. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  32192. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  32193. };
  32194. return LinesMesh;
  32195. })(BABYLON.Mesh);
  32196. BABYLON.LinesMesh = LinesMesh;
  32197. })(BABYLON || (BABYLON = {}));
  32198. var BABYLON;
  32199. (function (BABYLON) {
  32200. var DebugLayer = (function () {
  32201. function DebugLayer(scene) {
  32202. var _this = this;
  32203. this._transformationMatrix = BABYLON.Matrix.Identity();
  32204. this._enabled = false;
  32205. this._labelsEnabled = false;
  32206. this._displayStatistics = true;
  32207. this._displayTree = false;
  32208. this._displayLogs = false;
  32209. this._skeletonViewers = new Array();
  32210. this._identityMatrix = BABYLON.Matrix.Identity();
  32211. this.axisRatio = 0.02;
  32212. this.accentColor = "orange";
  32213. this._scene = scene;
  32214. this._syncPositions = function () {
  32215. var engine = _this._scene.getEngine();
  32216. var canvasRect = engine.getRenderingCanvasClientRect();
  32217. if (_this._showUI) {
  32218. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  32219. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  32220. _this._statsDiv.style.width = "400px";
  32221. _this._statsDiv.style.height = "auto";
  32222. _this._statsSubsetDiv.style.maxHeight = "240px";
  32223. _this._optionsDiv.style.left = "0px";
  32224. _this._optionsDiv.style.top = "10px";
  32225. _this._optionsDiv.style.width = "200px";
  32226. _this._optionsDiv.style.height = "auto";
  32227. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  32228. _this._logDiv.style.left = "0px";
  32229. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  32230. _this._logDiv.style.width = "600px";
  32231. _this._logDiv.style.height = "160px";
  32232. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  32233. _this._treeDiv.style.top = "10px";
  32234. _this._treeDiv.style.width = "300px";
  32235. _this._treeDiv.style.height = "auto";
  32236. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  32237. }
  32238. _this._globalDiv.style.left = canvasRect.left + "px";
  32239. _this._globalDiv.style.top = canvasRect.top + "px";
  32240. _this._drawingCanvas.style.left = "0px";
  32241. _this._drawingCanvas.style.top = "0px";
  32242. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  32243. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  32244. var devicePixelRatio = window.devicePixelRatio || 1;
  32245. var context = _this._drawingContext;
  32246. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  32247. context.mozBackingStorePixelRatio ||
  32248. context.msBackingStorePixelRatio ||
  32249. context.oBackingStorePixelRatio ||
  32250. context.backingStorePixelRatio || 1;
  32251. _this._ratio = devicePixelRatio / backingStoreRatio;
  32252. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  32253. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  32254. };
  32255. this._onCanvasClick = function (evt) {
  32256. _this._clickPosition = {
  32257. x: evt.clientX * _this._ratio,
  32258. y: evt.clientY * _this._ratio
  32259. };
  32260. };
  32261. this._syncUI = function () {
  32262. if (_this._showUI) {
  32263. if (_this._displayStatistics) {
  32264. _this._displayStats();
  32265. _this._statsDiv.style.display = "";
  32266. }
  32267. else {
  32268. _this._statsDiv.style.display = "none";
  32269. }
  32270. if (_this._displayLogs) {
  32271. _this._logDiv.style.display = "";
  32272. }
  32273. else {
  32274. _this._logDiv.style.display = "none";
  32275. }
  32276. if (_this._displayTree) {
  32277. _this._treeDiv.style.display = "";
  32278. if (_this._needToRefreshMeshesTree) {
  32279. _this._needToRefreshMeshesTree = false;
  32280. _this._refreshMeshesTreeContent();
  32281. }
  32282. }
  32283. else {
  32284. _this._treeDiv.style.display = "none";
  32285. }
  32286. }
  32287. };
  32288. this._syncData = function () {
  32289. if (_this._labelsEnabled || !_this._showUI) {
  32290. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  32291. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  32292. var engine = _this._scene.getEngine();
  32293. var viewport = _this._camera.viewport;
  32294. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  32295. // Meshes
  32296. var meshes = _this._camera.getActiveMeshes();
  32297. var index;
  32298. var projectedPosition;
  32299. for (index = 0; index < meshes.length; index++) {
  32300. var mesh = meshes.data[index];
  32301. var position = mesh.getBoundingInfo().boundingSphere.center;
  32302. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  32303. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  32304. _this._renderAxis(projectedPosition, mesh, globalViewport);
  32305. }
  32306. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  32307. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  32308. }
  32309. }
  32310. // Cameras
  32311. var cameras = _this._scene.cameras;
  32312. for (index = 0; index < cameras.length; index++) {
  32313. var camera = cameras[index];
  32314. if (camera === _this._camera) {
  32315. continue;
  32316. }
  32317. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  32318. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  32319. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  32320. _this._camera.detachControl(engine.getRenderingCanvas());
  32321. _this._camera = camera;
  32322. _this._camera.attachControl(engine.getRenderingCanvas());
  32323. }, function () { return "purple"; });
  32324. }
  32325. }
  32326. // Lights
  32327. var lights = _this._scene.lights;
  32328. for (index = 0; index < lights.length; index++) {
  32329. var light = lights[index];
  32330. if (light.position) {
  32331. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  32332. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  32333. _this._renderLabel(light.name, projectedPosition, -20, function () {
  32334. light.setEnabled(!light.isEnabled());
  32335. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  32336. }
  32337. }
  32338. }
  32339. }
  32340. _this._clickPosition = undefined;
  32341. };
  32342. }
  32343. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  32344. while (this._treeSubsetDiv.hasChildNodes()) {
  32345. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  32346. }
  32347. // Add meshes
  32348. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  32349. sortedArray.sort(function (a, b) {
  32350. if (a.name === b.name) {
  32351. return 0;
  32352. }
  32353. return (a.name > b.name) ? 1 : -1;
  32354. });
  32355. for (var index = 0; index < sortedArray.length; index++) {
  32356. var mesh = sortedArray[index];
  32357. if (!mesh.isEnabled()) {
  32358. continue;
  32359. }
  32360. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  32361. m.isVisible = element.checked;
  32362. }, mesh);
  32363. }
  32364. };
  32365. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  32366. this._drawingContext.beginPath();
  32367. this._drawingContext.moveTo(zero.x, zero.y);
  32368. this._drawingContext.lineTo(unit.x, unit.y);
  32369. this._drawingContext.strokeStyle = color;
  32370. this._drawingContext.lineWidth = 4;
  32371. this._drawingContext.stroke();
  32372. this._drawingContext.font = "normal 14px Segoe UI";
  32373. this._drawingContext.fillStyle = color;
  32374. this._drawingContext.fillText(label, unitText.x, unitText.y);
  32375. };
  32376. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  32377. var position = mesh.getBoundingInfo().boundingSphere.center;
  32378. var worldMatrix = mesh.getWorldMatrix();
  32379. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  32380. var unit = (unprojectedVector.subtract(position)).length();
  32381. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32382. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32383. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  32384. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32385. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32386. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  32387. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  32388. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  32389. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  32390. };
  32391. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  32392. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  32393. this._drawingContext.font = "normal 12px Segoe UI";
  32394. var textMetrics = this._drawingContext.measureText(text);
  32395. var centerX = projectedPosition.x - textMetrics.width / 2;
  32396. var centerY = projectedPosition.y;
  32397. var clientRect = this._drawingCanvas.getBoundingClientRect();
  32398. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  32399. onClick();
  32400. }
  32401. this._drawingContext.beginPath();
  32402. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  32403. this._drawingContext.fillStyle = getFillStyle();
  32404. this._drawingContext.globalAlpha = 0.5;
  32405. this._drawingContext.fill();
  32406. this._drawingContext.globalAlpha = 1.0;
  32407. this._drawingContext.strokeStyle = '#FFFFFF';
  32408. this._drawingContext.lineWidth = 1;
  32409. this._drawingContext.stroke();
  32410. this._drawingContext.fillStyle = "#FFFFFF";
  32411. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  32412. this._drawingContext.beginPath();
  32413. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  32414. this._drawingContext.fill();
  32415. }
  32416. };
  32417. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  32418. if (!this._clickPosition) {
  32419. return false;
  32420. }
  32421. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  32422. return false;
  32423. }
  32424. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  32425. return false;
  32426. }
  32427. return true;
  32428. };
  32429. DebugLayer.prototype.isVisible = function () {
  32430. return this._enabled;
  32431. };
  32432. DebugLayer.prototype.hide = function () {
  32433. if (!this._enabled) {
  32434. return;
  32435. }
  32436. this._enabled = false;
  32437. var engine = this._scene.getEngine();
  32438. this._scene.unregisterBeforeRender(this._syncData);
  32439. this._scene.unregisterAfterRender(this._syncUI);
  32440. this._rootElement.removeChild(this._globalDiv);
  32441. this._scene.forceShowBoundingBoxes = false;
  32442. this._scene.forceWireframe = false;
  32443. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  32444. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  32445. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  32446. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  32447. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  32448. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  32449. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  32450. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  32451. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  32452. this._scene.shadowsEnabled = true;
  32453. this._scene.particlesEnabled = true;
  32454. this._scene.postProcessesEnabled = true;
  32455. this._scene.collisionsEnabled = true;
  32456. this._scene.lightsEnabled = true;
  32457. this._scene.texturesEnabled = true;
  32458. this._scene.lensFlaresEnabled = true;
  32459. this._scene.proceduralTexturesEnabled = true;
  32460. this._scene.renderTargetsEnabled = true;
  32461. this._scene.probesEnabled = true;
  32462. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  32463. this._clearSkeletonViewers();
  32464. };
  32465. DebugLayer.prototype._clearSkeletonViewers = function () {
  32466. for (var index = 0; index < this._skeletonViewers.length; index++) {
  32467. this._skeletonViewers[index].dispose();
  32468. }
  32469. this._skeletonViewers = [];
  32470. };
  32471. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  32472. if (showUI === void 0) { showUI = true; }
  32473. if (camera === void 0) { camera = null; }
  32474. if (rootElement === void 0) { rootElement = null; }
  32475. if (this._enabled) {
  32476. return;
  32477. }
  32478. this._enabled = true;
  32479. if (camera) {
  32480. this._camera = camera;
  32481. }
  32482. else {
  32483. this._camera = this._scene.activeCamera;
  32484. }
  32485. this._showUI = showUI;
  32486. var engine = this._scene.getEngine();
  32487. this._globalDiv = document.createElement("div");
  32488. this._rootElement = rootElement || document.body;
  32489. this._rootElement.appendChild(this._globalDiv);
  32490. this._generateDOMelements();
  32491. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  32492. this._syncPositions();
  32493. this._scene.registerBeforeRender(this._syncData);
  32494. this._scene.registerAfterRender(this._syncUI);
  32495. };
  32496. DebugLayer.prototype._clearLabels = function () {
  32497. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  32498. for (var index = 0; index < this._scene.meshes.length; index++) {
  32499. var mesh = this._scene.meshes[index];
  32500. mesh.renderOverlay = false;
  32501. }
  32502. };
  32503. DebugLayer.prototype._generateheader = function (root, text) {
  32504. var header = document.createElement("div");
  32505. header.innerHTML = text + "&nbsp;";
  32506. header.style.textAlign = "right";
  32507. header.style.width = "100%";
  32508. header.style.color = "white";
  32509. header.style.backgroundColor = "Black";
  32510. header.style.padding = "5px 5px 4px 0px";
  32511. header.style.marginLeft = "-5px";
  32512. header.style.fontWeight = "bold";
  32513. root.appendChild(header);
  32514. };
  32515. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  32516. var label = document.createElement("label");
  32517. label.style.display = "inline";
  32518. label.innerHTML = title;
  32519. label.style.color = color;
  32520. root.appendChild(label);
  32521. root.appendChild(document.createElement("br"));
  32522. };
  32523. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  32524. if (tag === void 0) { tag = null; }
  32525. var label = document.createElement("label");
  32526. label.style.display = "inline";
  32527. var boundingBoxesCheckbox = document.createElement("input");
  32528. boundingBoxesCheckbox.type = "checkbox";
  32529. boundingBoxesCheckbox.checked = initialState;
  32530. boundingBoxesCheckbox.style.display = "inline";
  32531. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  32532. boundingBoxesCheckbox.style.verticalAlign = "sub";
  32533. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  32534. task(evt.target, tag);
  32535. });
  32536. label.appendChild(boundingBoxesCheckbox);
  32537. var container = document.createElement("span");
  32538. var leftPart = document.createElement("span");
  32539. var rightPart = document.createElement("span");
  32540. rightPart.style.cssFloat = "right";
  32541. leftPart.innerHTML = leftTitle;
  32542. rightPart.innerHTML = rightTitle;
  32543. rightPart.style.fontSize = "12px";
  32544. rightPart.style.maxWidth = "200px";
  32545. container.appendChild(leftPart);
  32546. container.appendChild(rightPart);
  32547. label.appendChild(container);
  32548. root.appendChild(label);
  32549. root.appendChild(document.createElement("br"));
  32550. };
  32551. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  32552. if (tag === void 0) { tag = null; }
  32553. var label = document.createElement("label");
  32554. label.style.display = "inline";
  32555. var checkBox = document.createElement("input");
  32556. checkBox.type = "checkbox";
  32557. checkBox.checked = initialState;
  32558. checkBox.style.display = "inline";
  32559. checkBox.style.margin = "0px 5px 0px 0px";
  32560. checkBox.style.verticalAlign = "sub";
  32561. checkBox.addEventListener("change", function (evt) {
  32562. task(evt.target, tag);
  32563. });
  32564. label.appendChild(checkBox);
  32565. label.appendChild(document.createTextNode(title));
  32566. root.appendChild(label);
  32567. root.appendChild(document.createElement("br"));
  32568. };
  32569. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  32570. if (tag === void 0) { tag = null; }
  32571. var button = document.createElement("button");
  32572. button.innerHTML = title;
  32573. button.style.height = "24px";
  32574. button.style.width = "150px";
  32575. button.style.marginBottom = "5px";
  32576. button.style.color = "#444444";
  32577. button.style.border = "1px solid white";
  32578. button.className = "debugLayerButton";
  32579. button.addEventListener("click", function (evt) {
  32580. task(evt.target, tag);
  32581. });
  32582. root.appendChild(button);
  32583. root.appendChild(document.createElement("br"));
  32584. };
  32585. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  32586. if (tag === void 0) { tag = null; }
  32587. var label = document.createElement("label");
  32588. label.style.display = "inline";
  32589. var boundingBoxesRadio = document.createElement("input");
  32590. boundingBoxesRadio.type = "radio";
  32591. boundingBoxesRadio.name = name;
  32592. boundingBoxesRadio.checked = initialState;
  32593. boundingBoxesRadio.style.display = "inline";
  32594. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  32595. boundingBoxesRadio.style.verticalAlign = "sub";
  32596. boundingBoxesRadio.addEventListener("change", function (evt) {
  32597. task(evt.target, tag);
  32598. });
  32599. label.appendChild(boundingBoxesRadio);
  32600. label.appendChild(document.createTextNode(title));
  32601. root.appendChild(label);
  32602. root.appendChild(document.createElement("br"));
  32603. };
  32604. DebugLayer.prototype._generateDOMelements = function () {
  32605. var _this = this;
  32606. this._globalDiv.id = "DebugLayer";
  32607. this._globalDiv.style.position = "absolute";
  32608. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  32609. this._globalDiv.style.fontSize = "14px";
  32610. this._globalDiv.style.color = "white";
  32611. // Drawing canvas
  32612. this._drawingCanvas = document.createElement("canvas");
  32613. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  32614. this._drawingCanvas.style.position = "absolute";
  32615. this._drawingCanvas.style.pointerEvents = "none";
  32616. this._drawingCanvas.style.backgroundColor = "transparent";
  32617. this._drawingContext = this._drawingCanvas.getContext("2d");
  32618. this._globalDiv.appendChild(this._drawingCanvas);
  32619. if (this._showUI) {
  32620. var background = "rgba(128, 128, 128, 0.4)";
  32621. var border = "rgb(180, 180, 180) solid 1px";
  32622. // Stats
  32623. this._statsDiv = document.createElement("div");
  32624. this._statsDiv.id = "DebugLayerStats";
  32625. this._statsDiv.style.border = border;
  32626. this._statsDiv.style.position = "absolute";
  32627. this._statsDiv.style.background = background;
  32628. this._statsDiv.style.padding = "0px 0px 0px 5px";
  32629. this._generateheader(this._statsDiv, "STATISTICS");
  32630. this._statsSubsetDiv = document.createElement("div");
  32631. this._statsSubsetDiv.style.paddingTop = "5px";
  32632. this._statsSubsetDiv.style.paddingBottom = "5px";
  32633. this._statsSubsetDiv.style.overflowY = "auto";
  32634. this._statsDiv.appendChild(this._statsSubsetDiv);
  32635. // Tree
  32636. this._treeDiv = document.createElement("div");
  32637. this._treeDiv.id = "DebugLayerTree";
  32638. this._treeDiv.style.border = border;
  32639. this._treeDiv.style.position = "absolute";
  32640. this._treeDiv.style.background = background;
  32641. this._treeDiv.style.padding = "0px 0px 0px 5px";
  32642. this._treeDiv.style.display = "none";
  32643. this._generateheader(this._treeDiv, "MESHES TREE");
  32644. this._treeSubsetDiv = document.createElement("div");
  32645. this._treeSubsetDiv.style.paddingTop = "5px";
  32646. this._treeSubsetDiv.style.paddingRight = "5px";
  32647. this._treeSubsetDiv.style.overflowY = "auto";
  32648. this._treeSubsetDiv.style.maxHeight = "300px";
  32649. this._treeDiv.appendChild(this._treeSubsetDiv);
  32650. this._needToRefreshMeshesTree = true;
  32651. // Logs
  32652. this._logDiv = document.createElement("div");
  32653. this._logDiv.style.border = border;
  32654. this._logDiv.id = "DebugLayerLogs";
  32655. this._logDiv.style.position = "absolute";
  32656. this._logDiv.style.background = background;
  32657. this._logDiv.style.padding = "0px 0px 0px 5px";
  32658. this._logDiv.style.display = "none";
  32659. this._generateheader(this._logDiv, "LOGS");
  32660. this._logSubsetDiv = document.createElement("div");
  32661. this._logSubsetDiv.style.height = "127px";
  32662. this._logSubsetDiv.style.paddingTop = "5px";
  32663. this._logSubsetDiv.style.overflowY = "auto";
  32664. this._logSubsetDiv.style.fontSize = "12px";
  32665. this._logSubsetDiv.style.fontFamily = "consolas";
  32666. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  32667. this._logDiv.appendChild(this._logSubsetDiv);
  32668. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  32669. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  32670. };
  32671. // Options
  32672. this._optionsDiv = document.createElement("div");
  32673. this._optionsDiv.id = "DebugLayerOptions";
  32674. this._optionsDiv.style.border = border;
  32675. this._optionsDiv.style.position = "absolute";
  32676. this._optionsDiv.style.background = background;
  32677. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  32678. this._optionsDiv.style.overflowY = "auto";
  32679. this._generateheader(this._optionsDiv, "OPTIONS");
  32680. this._optionsSubsetDiv = document.createElement("div");
  32681. this._optionsSubsetDiv.style.paddingTop = "5px";
  32682. this._optionsSubsetDiv.style.paddingBottom = "5px";
  32683. this._optionsSubsetDiv.style.overflowY = "auto";
  32684. this._optionsSubsetDiv.style.maxHeight = "200px";
  32685. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  32686. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  32687. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  32688. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  32689. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  32690. _this._displayTree = element.checked;
  32691. _this._needToRefreshMeshesTree = true;
  32692. });
  32693. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32694. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  32695. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  32696. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  32697. _this._labelsEnabled = element.checked;
  32698. if (!_this._labelsEnabled) {
  32699. _this._clearLabels();
  32700. }
  32701. });
  32702. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  32703. if (element.checked) {
  32704. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  32705. }
  32706. else {
  32707. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  32708. }
  32709. });
  32710. ;
  32711. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32712. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  32713. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  32714. if (element.checked) {
  32715. _this._scene.forceWireframe = false;
  32716. _this._scene.forcePointsCloud = false;
  32717. }
  32718. });
  32719. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  32720. if (element.checked) {
  32721. _this._scene.forceWireframe = true;
  32722. _this._scene.forcePointsCloud = false;
  32723. }
  32724. });
  32725. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  32726. if (element.checked) {
  32727. _this._scene.forceWireframe = false;
  32728. _this._scene.forcePointsCloud = true;
  32729. }
  32730. });
  32731. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32732. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  32733. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  32734. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  32735. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  32736. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  32737. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  32738. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  32739. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  32740. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  32741. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  32742. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  32743. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32744. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  32745. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  32746. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  32747. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  32748. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  32749. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  32750. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  32751. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  32752. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  32753. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  32754. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  32755. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  32756. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  32757. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  32758. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  32759. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  32760. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32761. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  32762. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  32763. if (element.checked) {
  32764. _this._scene.headphone = true;
  32765. }
  32766. });
  32767. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  32768. if (element.checked) {
  32769. _this._scene.headphone = false;
  32770. }
  32771. });
  32772. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  32773. _this._scene.audioEnabled = !element.checked;
  32774. });
  32775. }
  32776. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32777. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  32778. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  32779. if (!element.checked) {
  32780. _this._clearSkeletonViewers();
  32781. return;
  32782. }
  32783. for (var index = 0; index < _this._scene.meshes.length; index++) {
  32784. var mesh = _this._scene.meshes[index];
  32785. if (mesh.skeleton) {
  32786. var found = false;
  32787. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  32788. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  32789. found = true;
  32790. break;
  32791. }
  32792. }
  32793. if (found) {
  32794. continue;
  32795. }
  32796. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  32797. viewer.isEnabled = true;
  32798. _this._skeletonViewers.push(viewer);
  32799. }
  32800. }
  32801. });
  32802. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32803. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  32804. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  32805. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  32806. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  32807. if (_this._camera) {
  32808. console.log(_this._camera);
  32809. }
  32810. else {
  32811. console.warn("No camera defined, or debug layer created before camera creation!");
  32812. }
  32813. });
  32814. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32815. this._globalDiv.appendChild(this._statsDiv);
  32816. this._globalDiv.appendChild(this._logDiv);
  32817. this._globalDiv.appendChild(this._optionsDiv);
  32818. this._globalDiv.appendChild(this._treeDiv);
  32819. }
  32820. };
  32821. DebugLayer.prototype._displayStats = function () {
  32822. var scene = this._scene;
  32823. var engine = scene.getEngine();
  32824. var glInfo = engine.getGlInfo();
  32825. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  32826. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  32827. + "<b>Count</b><br>"
  32828. + "Total meshes: " + scene.meshes.length + "<br>"
  32829. + "Total lights: " + scene.lights.length + "<br>"
  32830. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  32831. + "Total materials: " + scene.materials.length + "<br>"
  32832. + "Total textures: " + scene.textures.length + "<br>"
  32833. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  32834. + "Active indices: " + scene.getActiveIndices() + "<br>"
  32835. + "Active bones: " + scene.getActiveBones() + "<br>"
  32836. + "Active particles: " + scene.getActiveParticles() + "<br>"
  32837. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  32838. + "<b>Duration</b><br>"
  32839. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  32840. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  32841. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  32842. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  32843. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  32844. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  32845. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  32846. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  32847. + "</div>"
  32848. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  32849. + "<b>Extensions</b><br>"
  32850. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  32851. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  32852. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  32853. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  32854. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  32855. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  32856. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  32857. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  32858. + "</div><br>"
  32859. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  32860. + "<b>Caps.</b><br>"
  32861. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  32862. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  32863. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  32864. + "<b>Info</b><br>"
  32865. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  32866. + glInfo.version + "<br>"
  32867. + "</div><br>"
  32868. + glInfo.renderer + "<br>";
  32869. if (this.customStatsFunction) {
  32870. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  32871. }
  32872. };
  32873. return DebugLayer;
  32874. })();
  32875. BABYLON.DebugLayer = DebugLayer;
  32876. })(BABYLON || (BABYLON = {}));
  32877. var BABYLON;
  32878. (function (BABYLON) {
  32879. var DefaultLoadingScreen = (function () {
  32880. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  32881. var _this = this;
  32882. if (_loadingText === void 0) { _loadingText = ""; }
  32883. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  32884. this._renderingCanvas = _renderingCanvas;
  32885. this._loadingText = _loadingText;
  32886. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  32887. // Resize
  32888. this._resizeLoadingUI = function () {
  32889. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  32890. _this._loadingDiv.style.position = "absolute";
  32891. _this._loadingDiv.style.left = canvasRect.left + "px";
  32892. _this._loadingDiv.style.top = canvasRect.top + "px";
  32893. _this._loadingDiv.style.width = canvasRect.width + "px";
  32894. _this._loadingDiv.style.height = canvasRect.height + "px";
  32895. };
  32896. }
  32897. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  32898. var _this = this;
  32899. if (this._loadingDiv) {
  32900. // Do not add a loading screen if there is already one
  32901. return;
  32902. }
  32903. this._loadingDiv = document.createElement("div");
  32904. this._loadingDiv.id = "babylonjsLoadingDiv";
  32905. this._loadingDiv.style.opacity = "0";
  32906. this._loadingDiv.style.transition = "opacity 1.5s ease";
  32907. // Loading text
  32908. this._loadingTextDiv = document.createElement("div");
  32909. this._loadingTextDiv.style.position = "absolute";
  32910. this._loadingTextDiv.style.left = "0";
  32911. this._loadingTextDiv.style.top = "50%";
  32912. this._loadingTextDiv.style.marginTop = "80px";
  32913. this._loadingTextDiv.style.width = "100%";
  32914. this._loadingTextDiv.style.height = "20px";
  32915. this._loadingTextDiv.style.fontFamily = "Arial";
  32916. this._loadingTextDiv.style.fontSize = "14px";
  32917. this._loadingTextDiv.style.color = "white";
  32918. this._loadingTextDiv.style.textAlign = "center";
  32919. this._loadingTextDiv.innerHTML = "Loading";
  32920. this._loadingDiv.appendChild(this._loadingTextDiv);
  32921. //set the predefined text
  32922. this._loadingTextDiv.innerHTML = this._loadingText;
  32923. // Loading img
  32924. var imgBack = new Image();
  32925. 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==";
  32926. imgBack.style.position = "absolute";
  32927. imgBack.style.left = "50%";
  32928. imgBack.style.top = "50%";
  32929. imgBack.style.marginLeft = "-50px";
  32930. imgBack.style.marginTop = "-50px";
  32931. imgBack.style.transition = "transform 1.0s ease";
  32932. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  32933. var deg = 360;
  32934. var onTransitionEnd = function () {
  32935. deg += 360;
  32936. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  32937. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  32938. };
  32939. imgBack.addEventListener("transitionend", onTransitionEnd);
  32940. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  32941. this._loadingDiv.appendChild(imgBack);
  32942. // front image
  32943. var imgFront = new Image();
  32944. 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=";
  32945. imgFront.style.position = "absolute";
  32946. imgFront.style.left = "50%";
  32947. imgFront.style.top = "50%";
  32948. imgFront.style.marginLeft = "-50px";
  32949. imgFront.style.marginTop = "-50px";
  32950. this._loadingDiv.appendChild(imgFront);
  32951. this._resizeLoadingUI();
  32952. window.addEventListener("resize", this._resizeLoadingUI);
  32953. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  32954. document.body.appendChild(this._loadingDiv);
  32955. setTimeout(function () {
  32956. _this._loadingDiv.style.opacity = "1";
  32957. imgBack.style.transform = "rotateZ(360deg)";
  32958. imgBack.style.webkitTransform = "rotateZ(360deg)";
  32959. }, 0);
  32960. };
  32961. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  32962. var _this = this;
  32963. if (!this._loadingDiv) {
  32964. return;
  32965. }
  32966. var onTransitionEnd = function () {
  32967. if (!_this._loadingDiv) {
  32968. return;
  32969. }
  32970. document.body.removeChild(_this._loadingDiv);
  32971. window.removeEventListener("resize", _this._resizeLoadingUI);
  32972. _this._loadingDiv = null;
  32973. };
  32974. this._loadingDiv.style.opacity = "0";
  32975. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  32976. };
  32977. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  32978. set: function (text) {
  32979. this._loadingText = text;
  32980. if (this._loadingTextDiv) {
  32981. this._loadingTextDiv.innerHTML = this._loadingText;
  32982. }
  32983. },
  32984. enumerable: true,
  32985. configurable: true
  32986. });
  32987. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  32988. get: function () {
  32989. return this._loadingDivBackgroundColor;
  32990. },
  32991. set: function (color) {
  32992. this._loadingDivBackgroundColor = color;
  32993. if (!this._loadingDiv) {
  32994. return;
  32995. }
  32996. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  32997. },
  32998. enumerable: true,
  32999. configurable: true
  33000. });
  33001. return DefaultLoadingScreen;
  33002. })();
  33003. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  33004. })(BABYLON || (BABYLON = {}));
  33005. var BABYLON;
  33006. (function (BABYLON) {
  33007. var AudioEngine = (function () {
  33008. function AudioEngine() {
  33009. this._audioContext = null;
  33010. this._audioContextInitialized = false;
  33011. this.canUseWebAudio = false;
  33012. this.WarnedWebAudioUnsupported = false;
  33013. this.unlocked = false;
  33014. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  33015. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  33016. this.canUseWebAudio = true;
  33017. }
  33018. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  33019. this._unlockiOSaudio();
  33020. }
  33021. else {
  33022. this.unlocked = true;
  33023. }
  33024. }
  33025. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  33026. get: function () {
  33027. if (!this._audioContextInitialized) {
  33028. this._initializeAudioContext();
  33029. }
  33030. return this._audioContext;
  33031. },
  33032. enumerable: true,
  33033. configurable: true
  33034. });
  33035. AudioEngine.prototype._unlockiOSaudio = function () {
  33036. var _this = this;
  33037. var unlockaudio = function () {
  33038. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  33039. var source = _this.audioContext.createBufferSource();
  33040. source.buffer = buffer;
  33041. source.connect(_this.audioContext.destination);
  33042. source.start(0);
  33043. setTimeout(function () {
  33044. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  33045. _this.unlocked = true;
  33046. window.removeEventListener('touchend', unlockaudio, false);
  33047. if (_this.onAudioUnlocked) {
  33048. _this.onAudioUnlocked();
  33049. }
  33050. }
  33051. }, 0);
  33052. };
  33053. window.addEventListener('touchend', unlockaudio, false);
  33054. };
  33055. AudioEngine.prototype._initializeAudioContext = function () {
  33056. try {
  33057. if (this.canUseWebAudio) {
  33058. this._audioContext = new AudioContext();
  33059. // create a global volume gain node
  33060. this.masterGain = this._audioContext.createGain();
  33061. this.masterGain.gain.value = 1;
  33062. this.masterGain.connect(this._audioContext.destination);
  33063. this._audioContextInitialized = true;
  33064. }
  33065. }
  33066. catch (e) {
  33067. this.canUseWebAudio = false;
  33068. BABYLON.Tools.Error("Web Audio: " + e.message);
  33069. }
  33070. };
  33071. AudioEngine.prototype.dispose = function () {
  33072. if (this.canUseWebAudio && this._audioContextInitialized) {
  33073. if (this._connectedAnalyser) {
  33074. this._connectedAnalyser.stopDebugCanvas();
  33075. this._connectedAnalyser.dispose();
  33076. this.masterGain.disconnect();
  33077. this.masterGain.connect(this._audioContext.destination);
  33078. this._connectedAnalyser = null;
  33079. }
  33080. this.masterGain.gain.value = 1;
  33081. }
  33082. this.WarnedWebAudioUnsupported = false;
  33083. };
  33084. AudioEngine.prototype.getGlobalVolume = function () {
  33085. if (this.canUseWebAudio && this._audioContextInitialized) {
  33086. return this.masterGain.gain.value;
  33087. }
  33088. else {
  33089. return -1;
  33090. }
  33091. };
  33092. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  33093. if (this.canUseWebAudio && this._audioContextInitialized) {
  33094. this.masterGain.gain.value = newVolume;
  33095. }
  33096. };
  33097. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  33098. if (this._connectedAnalyser) {
  33099. this._connectedAnalyser.stopDebugCanvas();
  33100. }
  33101. if (this.canUseWebAudio && this._audioContextInitialized) {
  33102. this._connectedAnalyser = analyser;
  33103. this.masterGain.disconnect();
  33104. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  33105. }
  33106. };
  33107. return AudioEngine;
  33108. })();
  33109. BABYLON.AudioEngine = AudioEngine;
  33110. })(BABYLON || (BABYLON = {}));
  33111. var BABYLON;
  33112. (function (BABYLON) {
  33113. var Sound = (function () {
  33114. /**
  33115. * Create a sound and attach it to a scene
  33116. * @param name Name of your sound
  33117. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  33118. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  33119. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  33120. */
  33121. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  33122. var _this = this;
  33123. this.autoplay = false;
  33124. this.loop = false;
  33125. this.useCustomAttenuation = false;
  33126. this.spatialSound = false;
  33127. this.refDistance = 1;
  33128. this.rolloffFactor = 1;
  33129. this.maxDistance = 100;
  33130. this.distanceModel = "linear";
  33131. this._panningModel = "equalpower";
  33132. this._playbackRate = 1;
  33133. this._streaming = false;
  33134. this._startTime = 0;
  33135. this._startOffset = 0;
  33136. this._position = BABYLON.Vector3.Zero();
  33137. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  33138. this._volume = 1;
  33139. this._isLoaded = false;
  33140. this._isReadyToPlay = false;
  33141. this.isPlaying = false;
  33142. this.isPaused = false;
  33143. this._isDirectional = false;
  33144. // Used if you'd like to create a directional sound.
  33145. // If not set, the sound will be omnidirectional
  33146. this._coneInnerAngle = 360;
  33147. this._coneOuterAngle = 360;
  33148. this._coneOuterGain = 0;
  33149. this._isOutputConnected = false;
  33150. this.name = name;
  33151. this._scene = scene;
  33152. this._readyToPlayCallback = readyToPlayCallback;
  33153. // Default custom attenuation function is a linear attenuation
  33154. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  33155. if (currentDistance < maxDistance) {
  33156. return currentVolume * (1 - currentDistance / maxDistance);
  33157. }
  33158. else {
  33159. return 0;
  33160. }
  33161. };
  33162. if (options) {
  33163. this.autoplay = options.autoplay || false;
  33164. this.loop = options.loop || false;
  33165. // if volume === 0, we need another way to check this option
  33166. if (options.volume !== undefined) {
  33167. this._volume = options.volume;
  33168. }
  33169. this.spatialSound = options.spatialSound || false;
  33170. this.maxDistance = options.maxDistance || 100;
  33171. this.useCustomAttenuation = options.useCustomAttenuation || false;
  33172. this.rolloffFactor = options.rolloffFactor || 1;
  33173. this.refDistance = options.refDistance || 1;
  33174. this.distanceModel = options.distanceModel || "linear";
  33175. this._playbackRate = options.playbackRate || 1;
  33176. this._streaming = options.streaming || false;
  33177. }
  33178. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33179. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  33180. this._soundGain.gain.value = this._volume;
  33181. this._inputAudioNode = this._soundGain;
  33182. this._ouputAudioNode = this._soundGain;
  33183. if (this.spatialSound) {
  33184. this._createSpatialParameters();
  33185. }
  33186. this._scene.mainSoundTrack.AddSound(this);
  33187. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  33188. if (urlOrArrayBuffer) {
  33189. // If it's an URL
  33190. if (typeof (urlOrArrayBuffer) === "string") {
  33191. // Loading sound using XHR2
  33192. if (!this._streaming) {
  33193. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  33194. }
  33195. else {
  33196. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  33197. this._htmlAudioElement.controls = false;
  33198. this._htmlAudioElement.loop = this.loop;
  33199. this._htmlAudioElement.crossOrigin = "anonymous";
  33200. this._htmlAudioElement.preload = "auto";
  33201. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  33202. _this._isReadyToPlay = true;
  33203. if (_this.autoplay) {
  33204. _this.play();
  33205. }
  33206. if (_this._readyToPlayCallback) {
  33207. _this._readyToPlayCallback();
  33208. }
  33209. });
  33210. document.body.appendChild(this._htmlAudioElement);
  33211. }
  33212. }
  33213. else {
  33214. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  33215. if (urlOrArrayBuffer.byteLength > 0) {
  33216. this._soundLoaded(urlOrArrayBuffer);
  33217. }
  33218. }
  33219. else {
  33220. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  33221. }
  33222. }
  33223. }
  33224. }
  33225. else {
  33226. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  33227. this._scene.mainSoundTrack.AddSound(this);
  33228. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  33229. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  33230. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  33231. }
  33232. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  33233. if (this._readyToPlayCallback) {
  33234. window.setTimeout(function () {
  33235. _this._readyToPlayCallback();
  33236. }, 1000);
  33237. }
  33238. }
  33239. }
  33240. Sound.prototype.dispose = function () {
  33241. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  33242. if (this.isPlaying) {
  33243. this.stop();
  33244. }
  33245. this._isReadyToPlay = false;
  33246. if (this.soundTrackId === -1) {
  33247. this._scene.mainSoundTrack.RemoveSound(this);
  33248. }
  33249. else {
  33250. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  33251. }
  33252. if (this._soundGain) {
  33253. this._soundGain.disconnect();
  33254. this._soundGain = null;
  33255. }
  33256. if (this._soundPanner) {
  33257. this._soundPanner.disconnect();
  33258. this._soundPanner = null;
  33259. }
  33260. if (this._soundSource) {
  33261. this._soundSource.disconnect();
  33262. this._soundSource = null;
  33263. }
  33264. this._audioBuffer = null;
  33265. if (this._htmlAudioElement) {
  33266. this._htmlAudioElement.pause();
  33267. this._htmlAudioElement.src = "";
  33268. document.body.removeChild(this._htmlAudioElement);
  33269. }
  33270. if (this._connectedMesh) {
  33271. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33272. this._connectedMesh = null;
  33273. }
  33274. }
  33275. };
  33276. Sound.prototype._soundLoaded = function (audioData) {
  33277. var _this = this;
  33278. this._isLoaded = true;
  33279. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  33280. _this._audioBuffer = buffer;
  33281. _this._isReadyToPlay = true;
  33282. if (_this.autoplay) {
  33283. _this.play();
  33284. }
  33285. if (_this._readyToPlayCallback) {
  33286. _this._readyToPlayCallback();
  33287. }
  33288. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  33289. };
  33290. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  33291. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33292. this._audioBuffer = audioBuffer;
  33293. this._isReadyToPlay = true;
  33294. }
  33295. };
  33296. Sound.prototype.updateOptions = function (options) {
  33297. if (options) {
  33298. this.loop = options.loop || this.loop;
  33299. this.maxDistance = options.maxDistance || this.maxDistance;
  33300. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  33301. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  33302. this.refDistance = options.refDistance || this.refDistance;
  33303. this.distanceModel = options.distanceModel || this.distanceModel;
  33304. this._playbackRate = options.playbackRate || this._playbackRate;
  33305. this._updateSpatialParameters();
  33306. if (this.isPlaying) {
  33307. if (this._streaming) {
  33308. this._htmlAudioElement.playbackRate = this._playbackRate;
  33309. }
  33310. else {
  33311. this._soundSource.playbackRate.value = this._playbackRate;
  33312. }
  33313. }
  33314. }
  33315. };
  33316. Sound.prototype._createSpatialParameters = function () {
  33317. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33318. if (this._scene.headphone) {
  33319. this._panningModel = "HRTF";
  33320. }
  33321. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  33322. this._updateSpatialParameters();
  33323. this._soundPanner.connect(this._ouputAudioNode);
  33324. this._inputAudioNode = this._soundPanner;
  33325. }
  33326. };
  33327. Sound.prototype._updateSpatialParameters = function () {
  33328. if (this.spatialSound) {
  33329. if (this.useCustomAttenuation) {
  33330. // Tricks to disable in a way embedded Web Audio attenuation
  33331. this._soundPanner.distanceModel = "linear";
  33332. this._soundPanner.maxDistance = Number.MAX_VALUE;
  33333. this._soundPanner.refDistance = 1;
  33334. this._soundPanner.rolloffFactor = 1;
  33335. this._soundPanner.panningModel = this._panningModel;
  33336. }
  33337. else {
  33338. this._soundPanner.distanceModel = this.distanceModel;
  33339. this._soundPanner.maxDistance = this.maxDistance;
  33340. this._soundPanner.refDistance = this.refDistance;
  33341. this._soundPanner.rolloffFactor = this.rolloffFactor;
  33342. this._soundPanner.panningModel = this._panningModel;
  33343. }
  33344. }
  33345. };
  33346. Sound.prototype.switchPanningModelToHRTF = function () {
  33347. this._panningModel = "HRTF";
  33348. this._switchPanningModel();
  33349. };
  33350. Sound.prototype.switchPanningModelToEqualPower = function () {
  33351. this._panningModel = "equalpower";
  33352. this._switchPanningModel();
  33353. };
  33354. Sound.prototype._switchPanningModel = function () {
  33355. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33356. this._soundPanner.panningModel = this._panningModel;
  33357. }
  33358. };
  33359. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  33360. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33361. if (this._isOutputConnected) {
  33362. this._ouputAudioNode.disconnect();
  33363. }
  33364. this._ouputAudioNode.connect(soundTrackAudioNode);
  33365. this._isOutputConnected = true;
  33366. }
  33367. };
  33368. /**
  33369. * Transform this sound into a directional source
  33370. * @param coneInnerAngle Size of the inner cone in degree
  33371. * @param coneOuterAngle Size of the outer cone in degree
  33372. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  33373. */
  33374. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  33375. if (coneOuterAngle < coneInnerAngle) {
  33376. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  33377. return;
  33378. }
  33379. this._coneInnerAngle = coneInnerAngle;
  33380. this._coneOuterAngle = coneOuterAngle;
  33381. this._coneOuterGain = coneOuterGain;
  33382. this._isDirectional = true;
  33383. if (this.isPlaying && this.loop) {
  33384. this.stop();
  33385. this.play();
  33386. }
  33387. };
  33388. Sound.prototype.setPosition = function (newPosition) {
  33389. this._position = newPosition;
  33390. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33391. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33392. }
  33393. };
  33394. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  33395. this._localDirection = newLocalDirection;
  33396. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  33397. this._updateDirection();
  33398. }
  33399. };
  33400. Sound.prototype._updateDirection = function () {
  33401. var mat = this._connectedMesh.getWorldMatrix();
  33402. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  33403. direction.normalize();
  33404. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  33405. };
  33406. Sound.prototype.updateDistanceFromListener = function () {
  33407. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  33408. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  33409. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  33410. }
  33411. };
  33412. Sound.prototype.setAttenuationFunction = function (callback) {
  33413. this._customAttenuationFunction = callback;
  33414. };
  33415. /**
  33416. * Play the sound
  33417. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  33418. */
  33419. Sound.prototype.play = function (time) {
  33420. var _this = this;
  33421. if (this._isReadyToPlay && this._scene.audioEnabled) {
  33422. try {
  33423. if (this._startOffset < 0) {
  33424. time = -this._startOffset;
  33425. this._startOffset = 0;
  33426. }
  33427. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33428. if (!this._soundSource || !this._streamingSource) {
  33429. if (this.spatialSound) {
  33430. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33431. if (this._isDirectional) {
  33432. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  33433. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  33434. this._soundPanner.coneOuterGain = this._coneOuterGain;
  33435. if (this._connectedMesh) {
  33436. this._updateDirection();
  33437. }
  33438. else {
  33439. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  33440. }
  33441. }
  33442. }
  33443. }
  33444. if (this._streaming) {
  33445. if (!this._streamingSource) {
  33446. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  33447. this._htmlAudioElement.onended = function () { _this._onended(); };
  33448. this._htmlAudioElement.playbackRate = this._playbackRate;
  33449. }
  33450. this._streamingSource.disconnect();
  33451. this._streamingSource.connect(this._inputAudioNode);
  33452. this._htmlAudioElement.play();
  33453. }
  33454. else {
  33455. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  33456. this._soundSource.buffer = this._audioBuffer;
  33457. this._soundSource.connect(this._inputAudioNode);
  33458. this._soundSource.loop = this.loop;
  33459. this._soundSource.playbackRate.value = this._playbackRate;
  33460. this._soundSource.onended = function () { _this._onended(); };
  33461. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  33462. }
  33463. this._startTime = startTime;
  33464. this.isPlaying = true;
  33465. this.isPaused = false;
  33466. }
  33467. catch (ex) {
  33468. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  33469. }
  33470. }
  33471. };
  33472. Sound.prototype._onended = function () {
  33473. this.isPlaying = false;
  33474. if (this.onended) {
  33475. this.onended();
  33476. }
  33477. };
  33478. /**
  33479. * Stop the sound
  33480. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  33481. */
  33482. Sound.prototype.stop = function (time) {
  33483. if (this.isPlaying) {
  33484. if (this._streaming) {
  33485. this._htmlAudioElement.pause();
  33486. // Test needed for Firefox or it will generate an Invalid State Error
  33487. if (this._htmlAudioElement.currentTime > 0) {
  33488. this._htmlAudioElement.currentTime = 0;
  33489. }
  33490. }
  33491. else {
  33492. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33493. this._soundSource.stop(stopTime);
  33494. if (!this.isPaused) {
  33495. this._startOffset = 0;
  33496. }
  33497. }
  33498. this.isPlaying = false;
  33499. }
  33500. };
  33501. Sound.prototype.pause = function () {
  33502. if (this.isPlaying) {
  33503. this.isPaused = true;
  33504. if (this._streaming) {
  33505. this._htmlAudioElement.pause();
  33506. }
  33507. else {
  33508. this.stop(0);
  33509. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  33510. }
  33511. }
  33512. };
  33513. Sound.prototype.setVolume = function (newVolume, time) {
  33514. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33515. if (time) {
  33516. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  33517. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  33518. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  33519. }
  33520. else {
  33521. this._soundGain.gain.value = newVolume;
  33522. }
  33523. }
  33524. this._volume = newVolume;
  33525. };
  33526. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  33527. this._playbackRate = newPlaybackRate;
  33528. if (this.isPlaying) {
  33529. if (this._streaming) {
  33530. this._htmlAudioElement.playbackRate = this._playbackRate;
  33531. }
  33532. else {
  33533. this._soundSource.playbackRate.value = this._playbackRate;
  33534. }
  33535. }
  33536. };
  33537. Sound.prototype.getVolume = function () {
  33538. return this._volume;
  33539. };
  33540. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  33541. var _this = this;
  33542. if (this._connectedMesh) {
  33543. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33544. this._registerFunc = null;
  33545. }
  33546. this._connectedMesh = meshToConnectTo;
  33547. if (!this.spatialSound) {
  33548. this.spatialSound = true;
  33549. this._createSpatialParameters();
  33550. if (this.isPlaying && this.loop) {
  33551. this.stop();
  33552. this.play();
  33553. }
  33554. }
  33555. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  33556. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  33557. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  33558. };
  33559. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  33560. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  33561. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  33562. this._updateDirection();
  33563. }
  33564. };
  33565. Sound.prototype.clone = function () {
  33566. var _this = this;
  33567. if (!this._streaming) {
  33568. var setBufferAndRun = function () {
  33569. if (_this._isReadyToPlay) {
  33570. clonedSound._audioBuffer = _this.getAudioBuffer();
  33571. clonedSound._isReadyToPlay = true;
  33572. if (clonedSound.autoplay) {
  33573. clonedSound.play();
  33574. }
  33575. }
  33576. else {
  33577. window.setTimeout(setBufferAndRun, 300);
  33578. }
  33579. };
  33580. var currentOptions = {
  33581. autoplay: this.autoplay, loop: this.loop,
  33582. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  33583. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  33584. refDistance: this.refDistance, distanceModel: this.distanceModel
  33585. };
  33586. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  33587. if (this.useCustomAttenuation) {
  33588. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  33589. }
  33590. clonedSound.setPosition(this._position);
  33591. clonedSound.setPlaybackRate(this._playbackRate);
  33592. setBufferAndRun();
  33593. return clonedSound;
  33594. }
  33595. else {
  33596. return null;
  33597. }
  33598. };
  33599. Sound.prototype.getAudioBuffer = function () {
  33600. return this._audioBuffer;
  33601. };
  33602. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  33603. var soundName = parsedSound.name;
  33604. var soundUrl;
  33605. if (parsedSound.url) {
  33606. soundUrl = rootUrl + parsedSound.url;
  33607. }
  33608. else {
  33609. soundUrl = rootUrl + soundName;
  33610. }
  33611. var options = {
  33612. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  33613. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  33614. rolloffFactor: parsedSound.rolloffFactor,
  33615. refDistance: parsedSound.refDistance,
  33616. distanceModel: parsedSound.distanceModel,
  33617. playbackRate: parsedSound.playbackRate
  33618. };
  33619. var newSound;
  33620. if (!sourceSound) {
  33621. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  33622. scene._addPendingData(newSound);
  33623. }
  33624. else {
  33625. var setBufferAndRun = function () {
  33626. if (sourceSound._isReadyToPlay) {
  33627. newSound._audioBuffer = sourceSound.getAudioBuffer();
  33628. newSound._isReadyToPlay = true;
  33629. if (newSound.autoplay) {
  33630. newSound.play();
  33631. }
  33632. }
  33633. else {
  33634. window.setTimeout(setBufferAndRun, 300);
  33635. }
  33636. };
  33637. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  33638. setBufferAndRun();
  33639. }
  33640. if (parsedSound.position) {
  33641. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  33642. newSound.setPosition(soundPosition);
  33643. }
  33644. if (parsedSound.isDirectional) {
  33645. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  33646. if (parsedSound.localDirectionToMesh) {
  33647. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  33648. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  33649. }
  33650. }
  33651. if (parsedSound.connectedMeshId) {
  33652. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  33653. if (connectedMesh) {
  33654. newSound.attachToMesh(connectedMesh);
  33655. }
  33656. }
  33657. return newSound;
  33658. };
  33659. return Sound;
  33660. })();
  33661. BABYLON.Sound = Sound;
  33662. })(BABYLON || (BABYLON = {}));
  33663. var BABYLON;
  33664. (function (BABYLON) {
  33665. var SoundTrack = (function () {
  33666. function SoundTrack(scene, options) {
  33667. this.id = -1;
  33668. this._isMainTrack = false;
  33669. this._isInitialized = false;
  33670. this._scene = scene;
  33671. this.soundCollection = new Array();
  33672. this._options = options;
  33673. if (!this._isMainTrack) {
  33674. this._scene.soundTracks.push(this);
  33675. this.id = this._scene.soundTracks.length - 1;
  33676. }
  33677. }
  33678. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  33679. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33680. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  33681. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  33682. if (this._options) {
  33683. if (this._options.volume) {
  33684. this._outputAudioNode.gain.value = this._options.volume;
  33685. }
  33686. if (this._options.mainTrack) {
  33687. this._isMainTrack = this._options.mainTrack;
  33688. }
  33689. }
  33690. this._isInitialized = true;
  33691. }
  33692. };
  33693. SoundTrack.prototype.dispose = function () {
  33694. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33695. if (this._connectedAnalyser) {
  33696. this._connectedAnalyser.stopDebugCanvas();
  33697. }
  33698. while (this.soundCollection.length) {
  33699. this.soundCollection[0].dispose();
  33700. }
  33701. if (this._outputAudioNode) {
  33702. this._outputAudioNode.disconnect();
  33703. }
  33704. this._outputAudioNode = null;
  33705. }
  33706. };
  33707. SoundTrack.prototype.AddSound = function (sound) {
  33708. if (!this._isInitialized) {
  33709. this._initializeSoundTrackAudioGraph();
  33710. }
  33711. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33712. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  33713. }
  33714. if (sound.soundTrackId) {
  33715. if (sound.soundTrackId === -1) {
  33716. this._scene.mainSoundTrack.RemoveSound(sound);
  33717. }
  33718. else {
  33719. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  33720. }
  33721. }
  33722. this.soundCollection.push(sound);
  33723. sound.soundTrackId = this.id;
  33724. };
  33725. SoundTrack.prototype.RemoveSound = function (sound) {
  33726. var index = this.soundCollection.indexOf(sound);
  33727. if (index !== -1) {
  33728. this.soundCollection.splice(index, 1);
  33729. }
  33730. };
  33731. SoundTrack.prototype.setVolume = function (newVolume) {
  33732. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33733. this._outputAudioNode.gain.value = newVolume;
  33734. }
  33735. };
  33736. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  33737. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33738. for (var i = 0; i < this.soundCollection.length; i++) {
  33739. this.soundCollection[i].switchPanningModelToHRTF();
  33740. }
  33741. }
  33742. };
  33743. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  33744. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33745. for (var i = 0; i < this.soundCollection.length; i++) {
  33746. this.soundCollection[i].switchPanningModelToEqualPower();
  33747. }
  33748. }
  33749. };
  33750. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  33751. if (this._connectedAnalyser) {
  33752. this._connectedAnalyser.stopDebugCanvas();
  33753. }
  33754. this._connectedAnalyser = analyser;
  33755. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33756. this._outputAudioNode.disconnect();
  33757. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  33758. }
  33759. };
  33760. return SoundTrack;
  33761. })();
  33762. BABYLON.SoundTrack = SoundTrack;
  33763. })(BABYLON || (BABYLON = {}));
  33764. var BABYLON;
  33765. (function (BABYLON) {
  33766. var SIMDVector3 = (function () {
  33767. function SIMDVector3() {
  33768. }
  33769. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  33770. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  33771. var m0 = SIMD.float32x4.load(transformation.m, 0);
  33772. var m1 = SIMD.float32x4.load(transformation.m, 4);
  33773. var m2 = SIMD.float32x4.load(transformation.m, 8);
  33774. var m3 = SIMD.float32x4.load(transformation.m, 12);
  33775. 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));
  33776. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  33777. SIMD.float32x4.storeXYZ(result._data, 0, r);
  33778. };
  33779. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  33780. var v0 = SIMD.float32x4.splat(x);
  33781. var v1 = SIMD.float32x4.splat(y);
  33782. var v2 = SIMD.float32x4.splat(z);
  33783. var m0 = SIMD.float32x4.load(transformation.m, 0);
  33784. var m1 = SIMD.float32x4.load(transformation.m, 4);
  33785. var m2 = SIMD.float32x4.load(transformation.m, 8);
  33786. var m3 = SIMD.float32x4.load(transformation.m, 12);
  33787. 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));
  33788. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  33789. SIMD.float32x4.storeXYZ(result._data, 0, r);
  33790. };
  33791. return SIMDVector3;
  33792. })();
  33793. BABYLON.SIMDVector3 = SIMDVector3;
  33794. var SIMDMatrix = (function () {
  33795. function SIMDMatrix() {
  33796. }
  33797. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  33798. if (offset === void 0) { offset = 0; }
  33799. var tm = this.m;
  33800. var om = other.m;
  33801. var om0 = SIMD.float32x4.load(om, 0);
  33802. var om1 = SIMD.float32x4.load(om, 4);
  33803. var om2 = SIMD.float32x4.load(om, 8);
  33804. var om3 = SIMD.float32x4.load(om, 12);
  33805. var tm0 = SIMD.float32x4.load(tm, 0);
  33806. 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)))));
  33807. var tm1 = SIMD.float32x4.load(tm, 4);
  33808. 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)))));
  33809. var tm2 = SIMD.float32x4.load(tm, 8);
  33810. 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)))));
  33811. var tm3 = SIMD.float32x4.load(tm, 12);
  33812. 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)))));
  33813. };
  33814. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  33815. var src = this.m;
  33816. var dest = other.m;
  33817. var row0, row1, row2, row3;
  33818. var tmp1;
  33819. var minor0, minor1, minor2, minor3;
  33820. var det;
  33821. // Load the 4 rows
  33822. var src0 = SIMD.float32x4.load(src, 0);
  33823. var src1 = SIMD.float32x4.load(src, 4);
  33824. var src2 = SIMD.float32x4.load(src, 8);
  33825. var src3 = SIMD.float32x4.load(src, 12);
  33826. // Transpose the source matrix. Sort of. Not a true transpose operation
  33827. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  33828. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  33829. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  33830. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  33831. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  33832. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  33833. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  33834. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  33835. // This is a true transposition, but it will lead to an incorrect result
  33836. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  33837. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  33838. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  33839. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  33840. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  33841. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  33842. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  33843. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  33844. // ----
  33845. tmp1 = SIMD.float32x4.mul(row2, row3);
  33846. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33847. minor0 = SIMD.float32x4.mul(row1, tmp1);
  33848. minor1 = SIMD.float32x4.mul(row0, tmp1);
  33849. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33850. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  33851. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  33852. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  33853. // ----
  33854. tmp1 = SIMD.float32x4.mul(row1, row2);
  33855. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33856. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  33857. minor3 = SIMD.float32x4.mul(row0, tmp1);
  33858. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33859. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  33860. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  33861. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  33862. // ----
  33863. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  33864. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33865. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  33866. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  33867. minor2 = SIMD.float32x4.mul(row0, tmp1);
  33868. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33869. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  33870. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  33871. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  33872. // ----
  33873. tmp1 = SIMD.float32x4.mul(row0, row1);
  33874. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33875. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  33876. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  33877. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33878. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  33879. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  33880. // ----
  33881. tmp1 = SIMD.float32x4.mul(row0, row3);
  33882. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33883. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  33884. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  33885. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33886. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  33887. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  33888. // ----
  33889. tmp1 = SIMD.float32x4.mul(row0, row2);
  33890. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33891. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  33892. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  33893. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33894. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  33895. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  33896. // Compute determinant
  33897. det = SIMD.float32x4.mul(row0, minor0);
  33898. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  33899. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  33900. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  33901. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  33902. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  33903. // These shuffles aren't necessary if the faulty transposition is done
  33904. // up at the top of this function.
  33905. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  33906. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  33907. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  33908. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  33909. // Compute final values by multiplying with 1/det
  33910. minor0 = SIMD.float32x4.mul(det, minor0);
  33911. minor1 = SIMD.float32x4.mul(det, minor1);
  33912. minor2 = SIMD.float32x4.mul(det, minor2);
  33913. minor3 = SIMD.float32x4.mul(det, minor3);
  33914. SIMD.float32x4.store(dest, 0, minor0);
  33915. SIMD.float32x4.store(dest, 4, minor1);
  33916. SIMD.float32x4.store(dest, 8, minor2);
  33917. SIMD.float32x4.store(dest, 12, minor3);
  33918. return this;
  33919. };
  33920. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  33921. var out = result.m;
  33922. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  33923. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  33924. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  33925. // cc.kmVec3Subtract(f, pCenter, pEye);
  33926. var f = SIMD.float32x4.sub(center, eye);
  33927. // cc.kmVec3Normalize(f, f);
  33928. var tmp = SIMD.float32x4.mul(f, f);
  33929. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  33930. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  33931. // cc.kmVec3Assign(up, pUp);
  33932. // cc.kmVec3Normalize(up, up);
  33933. tmp = SIMD.float32x4.mul(up, up);
  33934. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  33935. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  33936. // cc.kmVec3Cross(s, f, up);
  33937. 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)));
  33938. // cc.kmVec3Normalize(s, s);
  33939. tmp = SIMD.float32x4.mul(s, s);
  33940. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  33941. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  33942. // cc.kmVec3Cross(u, s, f);
  33943. 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)));
  33944. // cc.kmVec3Normalize(s, s);
  33945. tmp = SIMD.float32x4.mul(s, s);
  33946. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  33947. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  33948. var zero = SIMD.float32x4.splat(0.0);
  33949. s = SIMD.float32x4.neg(s);
  33950. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  33951. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  33952. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  33953. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  33954. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  33955. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  33956. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  33957. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  33958. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  33959. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  33960. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  33961. var b3 = SIMD.float32x4.neg(eye);
  33962. b3 = SIMD.float32x4.withW(b3, 1.0);
  33963. 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)))));
  33964. 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)))));
  33965. 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)))));
  33966. 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)))));
  33967. };
  33968. return SIMDMatrix;
  33969. })();
  33970. BABYLON.SIMDMatrix = SIMDMatrix;
  33971. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  33972. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  33973. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  33974. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  33975. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  33976. var SIMDHelper = (function () {
  33977. function SIMDHelper() {
  33978. }
  33979. Object.defineProperty(SIMDHelper, "IsEnabled", {
  33980. get: function () {
  33981. return SIMDHelper._isEnabled;
  33982. },
  33983. enumerable: true,
  33984. configurable: true
  33985. });
  33986. SIMDHelper.DisableSIMD = function () {
  33987. // Replace functions
  33988. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  33989. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  33990. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  33991. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  33992. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  33993. SIMDHelper._isEnabled = false;
  33994. };
  33995. SIMDHelper.EnableSIMD = function () {
  33996. if (window.SIMD === undefined) {
  33997. return;
  33998. }
  33999. // Replace functions
  34000. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  34001. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  34002. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  34003. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  34004. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  34005. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  34006. get: function () { return this._data[0]; },
  34007. set: function (value) {
  34008. if (!this._data) {
  34009. this._data = new Float32Array(3);
  34010. }
  34011. this._data[0] = value;
  34012. }
  34013. });
  34014. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  34015. get: function () { return this._data[1]; },
  34016. set: function (value) {
  34017. this._data[1] = value;
  34018. }
  34019. });
  34020. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  34021. get: function () { return this._data[2]; },
  34022. set: function (value) {
  34023. this._data[2] = value;
  34024. }
  34025. });
  34026. SIMDHelper._isEnabled = true;
  34027. };
  34028. SIMDHelper._isEnabled = false;
  34029. return SIMDHelper;
  34030. })();
  34031. BABYLON.SIMDHelper = SIMDHelper;
  34032. })(BABYLON || (BABYLON = {}));
  34033. var BABYLON;
  34034. (function (BABYLON) {
  34035. var ShaderMaterial = (function (_super) {
  34036. __extends(ShaderMaterial, _super);
  34037. function ShaderMaterial(name, scene, shaderPath, options) {
  34038. _super.call(this, name, scene);
  34039. this._textures = {};
  34040. this._floats = {};
  34041. this._floatsArrays = {};
  34042. this._colors3 = {};
  34043. this._colors4 = {};
  34044. this._vectors2 = {};
  34045. this._vectors3 = {};
  34046. this._vectors4 = {};
  34047. this._matrices = {};
  34048. this._matrices3x3 = {};
  34049. this._matrices2x2 = {};
  34050. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  34051. this._shaderPath = shaderPath;
  34052. options.needAlphaBlending = options.needAlphaBlending || false;
  34053. options.needAlphaTesting = options.needAlphaTesting || false;
  34054. options.attributes = options.attributes || ["position", "normal", "uv"];
  34055. options.uniforms = options.uniforms || ["worldViewProjection"];
  34056. options.samplers = options.samplers || [];
  34057. options.defines = options.defines || [];
  34058. this._options = options;
  34059. }
  34060. ShaderMaterial.prototype.needAlphaBlending = function () {
  34061. return this._options.needAlphaBlending;
  34062. };
  34063. ShaderMaterial.prototype.needAlphaTesting = function () {
  34064. return this._options.needAlphaTesting;
  34065. };
  34066. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  34067. if (this._options.uniforms.indexOf(uniformName) === -1) {
  34068. this._options.uniforms.push(uniformName);
  34069. }
  34070. };
  34071. ShaderMaterial.prototype.setTexture = function (name, texture) {
  34072. if (this._options.samplers.indexOf(name) === -1) {
  34073. this._options.samplers.push(name);
  34074. }
  34075. this._textures[name] = texture;
  34076. return this;
  34077. };
  34078. ShaderMaterial.prototype.setFloat = function (name, value) {
  34079. this._checkUniform(name);
  34080. this._floats[name] = value;
  34081. return this;
  34082. };
  34083. ShaderMaterial.prototype.setFloats = function (name, value) {
  34084. this._checkUniform(name);
  34085. this._floatsArrays[name] = value;
  34086. return this;
  34087. };
  34088. ShaderMaterial.prototype.setColor3 = function (name, value) {
  34089. this._checkUniform(name);
  34090. this._colors3[name] = value;
  34091. return this;
  34092. };
  34093. ShaderMaterial.prototype.setColor4 = function (name, value) {
  34094. this._checkUniform(name);
  34095. this._colors4[name] = value;
  34096. return this;
  34097. };
  34098. ShaderMaterial.prototype.setVector2 = function (name, value) {
  34099. this._checkUniform(name);
  34100. this._vectors2[name] = value;
  34101. return this;
  34102. };
  34103. ShaderMaterial.prototype.setVector3 = function (name, value) {
  34104. this._checkUniform(name);
  34105. this._vectors3[name] = value;
  34106. return this;
  34107. };
  34108. ShaderMaterial.prototype.setVector4 = function (name, value) {
  34109. this._checkUniform(name);
  34110. this._vectors4[name] = value;
  34111. return this;
  34112. };
  34113. ShaderMaterial.prototype.setMatrix = function (name, value) {
  34114. this._checkUniform(name);
  34115. this._matrices[name] = value;
  34116. return this;
  34117. };
  34118. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  34119. this._checkUniform(name);
  34120. this._matrices3x3[name] = value;
  34121. return this;
  34122. };
  34123. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  34124. this._checkUniform(name);
  34125. this._matrices2x2[name] = value;
  34126. return this;
  34127. };
  34128. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  34129. var scene = this.getScene();
  34130. var engine = scene.getEngine();
  34131. if (!this.checkReadyOnEveryCall) {
  34132. if (this._renderId === scene.getRenderId()) {
  34133. return true;
  34134. }
  34135. }
  34136. // Instances
  34137. var defines = [];
  34138. var fallbacks = new BABYLON.EffectFallbacks();
  34139. if (useInstances) {
  34140. defines.push("#define INSTANCES");
  34141. }
  34142. for (var index = 0; index < this._options.defines.length; index++) {
  34143. defines.push(this._options.defines[index]);
  34144. }
  34145. // Bones
  34146. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  34147. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34148. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34149. fallbacks.addCPUSkinningFallback(0, mesh);
  34150. }
  34151. // Alpha test
  34152. if (engine.getAlphaTesting()) {
  34153. defines.push("#define ALPHATEST");
  34154. }
  34155. var previousEffect = this._effect;
  34156. var join = defines.join("\n");
  34157. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  34158. if (!this._effect.isReady()) {
  34159. return false;
  34160. }
  34161. if (previousEffect !== this._effect) {
  34162. scene.resetCachedMaterial();
  34163. }
  34164. this._renderId = scene.getRenderId();
  34165. return true;
  34166. };
  34167. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34168. var scene = this.getScene();
  34169. if (this._options.uniforms.indexOf("world") !== -1) {
  34170. this._effect.setMatrix("world", world);
  34171. }
  34172. if (this._options.uniforms.indexOf("worldView") !== -1) {
  34173. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  34174. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  34175. }
  34176. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  34177. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  34178. }
  34179. };
  34180. ShaderMaterial.prototype.bind = function (world, mesh) {
  34181. // Std values
  34182. this.bindOnlyWorldMatrix(world);
  34183. if (this.getScene().getCachedMaterial() !== this) {
  34184. if (this._options.uniforms.indexOf("view") !== -1) {
  34185. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  34186. }
  34187. if (this._options.uniforms.indexOf("projection") !== -1) {
  34188. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  34189. }
  34190. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  34191. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  34192. }
  34193. // Bones
  34194. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  34195. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  34196. }
  34197. // Texture
  34198. for (var name in this._textures) {
  34199. this._effect.setTexture(name, this._textures[name]);
  34200. }
  34201. // Float
  34202. for (name in this._floats) {
  34203. this._effect.setFloat(name, this._floats[name]);
  34204. }
  34205. // Float s
  34206. for (name in this._floatsArrays) {
  34207. this._effect.setArray(name, this._floatsArrays[name]);
  34208. }
  34209. // Color3
  34210. for (name in this._colors3) {
  34211. this._effect.setColor3(name, this._colors3[name]);
  34212. }
  34213. // Color4
  34214. for (name in this._colors4) {
  34215. var color = this._colors4[name];
  34216. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  34217. }
  34218. // Vector2
  34219. for (name in this._vectors2) {
  34220. this._effect.setVector2(name, this._vectors2[name]);
  34221. }
  34222. // Vector3
  34223. for (name in this._vectors3) {
  34224. this._effect.setVector3(name, this._vectors3[name]);
  34225. }
  34226. // Vector4
  34227. for (name in this._vectors4) {
  34228. this._effect.setVector4(name, this._vectors4[name]);
  34229. }
  34230. // Matrix
  34231. for (name in this._matrices) {
  34232. this._effect.setMatrix(name, this._matrices[name]);
  34233. }
  34234. // Matrix 3x3
  34235. for (name in this._matrices3x3) {
  34236. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  34237. }
  34238. // Matrix 2x2
  34239. for (name in this._matrices2x2) {
  34240. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  34241. }
  34242. }
  34243. _super.prototype.bind.call(this, world, mesh);
  34244. };
  34245. ShaderMaterial.prototype.clone = function (name) {
  34246. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  34247. return newShaderMaterial;
  34248. };
  34249. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34250. if (forceDisposeTextures) {
  34251. for (var name in this._textures) {
  34252. this._textures[name].dispose();
  34253. }
  34254. }
  34255. this._textures = {};
  34256. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  34257. };
  34258. ShaderMaterial.prototype.serialize = function () {
  34259. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  34260. serializationObject.customType = "BABYLON.ShaderMaterial";
  34261. serializationObject.options = this._options;
  34262. serializationObject.shaderPath = this._shaderPath;
  34263. // Texture
  34264. serializationObject.textures = {};
  34265. for (var name in this._textures) {
  34266. serializationObject.textures[name] = this._textures[name].serialize();
  34267. }
  34268. // Float
  34269. serializationObject.floats = {};
  34270. for (name in this._floats) {
  34271. serializationObject.floats[name] = this._floats[name];
  34272. }
  34273. // Float s
  34274. serializationObject.floatArrays = {};
  34275. for (name in this._floatsArrays) {
  34276. serializationObject.floatArrays[name] = this._floatsArrays[name];
  34277. }
  34278. // Color3
  34279. serializationObject.colors3 = {};
  34280. for (name in this._colors3) {
  34281. serializationObject.colors3[name] = this._colors3[name].asArray();
  34282. }
  34283. // Color4
  34284. serializationObject.colors4 = {};
  34285. for (name in this._colors4) {
  34286. serializationObject.colors4[name] = this._colors4[name].asArray();
  34287. }
  34288. // Vector2
  34289. serializationObject.vectors2 = {};
  34290. for (name in this._vectors2) {
  34291. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  34292. }
  34293. // Vector3
  34294. serializationObject.vectors3 = {};
  34295. for (name in this._vectors3) {
  34296. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  34297. }
  34298. // Vector4
  34299. serializationObject.vectors4 = {};
  34300. for (name in this._vectors4) {
  34301. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  34302. }
  34303. // Matrix
  34304. serializationObject.matrices = {};
  34305. for (name in this._matrices) {
  34306. serializationObject.matrices[name] = this._matrices[name].asArray();
  34307. }
  34308. // Matrix 3x3
  34309. serializationObject.matrices3x3 = {};
  34310. for (name in this._matrices3x3) {
  34311. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  34312. }
  34313. // Matrix 2x2
  34314. serializationObject.matrices2x2 = {};
  34315. for (name in this._matrices2x2) {
  34316. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  34317. }
  34318. return serializationObject;
  34319. };
  34320. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  34321. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  34322. // Texture
  34323. for (var name in source.textures) {
  34324. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  34325. }
  34326. // Float
  34327. for (name in source.floats) {
  34328. material.setFloat(name, source.floats[name]);
  34329. }
  34330. // Float s
  34331. for (name in source.floatsArrays) {
  34332. material.setFloats(name, source.floatsArrays[name]);
  34333. }
  34334. // Color3
  34335. for (name in source.colors3) {
  34336. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  34337. }
  34338. // Color4
  34339. for (name in source.colors4) {
  34340. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  34341. }
  34342. // Vector2
  34343. for (name in source.vectors2) {
  34344. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  34345. }
  34346. // Vector3
  34347. for (name in source.vectors3) {
  34348. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  34349. }
  34350. // Vector4
  34351. for (name in source.vectors4) {
  34352. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  34353. }
  34354. // Matrix
  34355. for (name in source.matrices) {
  34356. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  34357. }
  34358. // Matrix 3x3
  34359. for (name in source.matrices3x3) {
  34360. material.setMatrix3x3(name, source.matrices3x3[name]);
  34361. }
  34362. // Matrix 2x2
  34363. for (name in source.matrices2x2) {
  34364. material.setMatrix2x2(name, source.matrices2x2[name]);
  34365. }
  34366. return material;
  34367. };
  34368. return ShaderMaterial;
  34369. })(BABYLON.Material);
  34370. BABYLON.ShaderMaterial = ShaderMaterial;
  34371. })(BABYLON || (BABYLON = {}));
  34372. var BABYLON;
  34373. (function (BABYLON) {
  34374. var Internals;
  34375. (function (Internals) {
  34376. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  34377. // All values and structures referenced from:
  34378. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  34379. var DDS_MAGIC = 0x20534444;
  34380. 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;
  34381. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  34382. 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;
  34383. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  34384. function FourCCToInt32(value) {
  34385. return value.charCodeAt(0) +
  34386. (value.charCodeAt(1) << 8) +
  34387. (value.charCodeAt(2) << 16) +
  34388. (value.charCodeAt(3) << 24);
  34389. }
  34390. function Int32ToFourCC(value) {
  34391. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  34392. }
  34393. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  34394. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  34395. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  34396. var headerLengthInt = 31; // The header length in 32 bit ints
  34397. // Offsets into the header array
  34398. var off_magic = 0;
  34399. var off_size = 1;
  34400. var off_flags = 2;
  34401. var off_height = 3;
  34402. var off_width = 4;
  34403. var off_mipmapCount = 7;
  34404. var off_pfFlags = 20;
  34405. var off_pfFourCC = 21;
  34406. var off_RGBbpp = 22;
  34407. var off_RMask = 23;
  34408. var off_GMask = 24;
  34409. var off_BMask = 25;
  34410. var off_AMask = 26;
  34411. var off_caps1 = 27;
  34412. var off_caps2 = 28;
  34413. ;
  34414. var DDSTools = (function () {
  34415. function DDSTools() {
  34416. }
  34417. DDSTools.GetDDSInfo = function (arrayBuffer) {
  34418. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  34419. var mipmapCount = 1;
  34420. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  34421. mipmapCount = Math.max(1, header[off_mipmapCount]);
  34422. }
  34423. return {
  34424. width: header[off_width],
  34425. height: header[off_height],
  34426. mipmapCount: mipmapCount,
  34427. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  34428. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  34429. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  34430. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  34431. };
  34432. };
  34433. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34434. var byteArray = new Uint8Array(dataLength);
  34435. var srcData = new Uint8Array(arrayBuffer);
  34436. var index = 0;
  34437. for (var y = height - 1; y >= 0; y--) {
  34438. for (var x = 0; x < width; x++) {
  34439. var srcPos = dataOffset + (x + y * width) * 4;
  34440. byteArray[index + 2] = srcData[srcPos];
  34441. byteArray[index + 1] = srcData[srcPos + 1];
  34442. byteArray[index] = srcData[srcPos + 2];
  34443. byteArray[index + 3] = srcData[srcPos + 3];
  34444. index += 4;
  34445. }
  34446. }
  34447. return byteArray;
  34448. };
  34449. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34450. var byteArray = new Uint8Array(dataLength);
  34451. var srcData = new Uint8Array(arrayBuffer);
  34452. var index = 0;
  34453. for (var y = height - 1; y >= 0; y--) {
  34454. for (var x = 0; x < width; x++) {
  34455. var srcPos = dataOffset + (x + y * width) * 3;
  34456. byteArray[index + 2] = srcData[srcPos];
  34457. byteArray[index + 1] = srcData[srcPos + 1];
  34458. byteArray[index] = srcData[srcPos + 2];
  34459. index += 3;
  34460. }
  34461. }
  34462. return byteArray;
  34463. };
  34464. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34465. var byteArray = new Uint8Array(dataLength);
  34466. var srcData = new Uint8Array(arrayBuffer);
  34467. var index = 0;
  34468. for (var y = height - 1; y >= 0; y--) {
  34469. for (var x = 0; x < width; x++) {
  34470. var srcPos = dataOffset + (x + y * width);
  34471. byteArray[index] = srcData[srcPos];
  34472. index++;
  34473. }
  34474. }
  34475. return byteArray;
  34476. };
  34477. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  34478. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  34479. if (header[off_magic] != DDS_MAGIC) {
  34480. BABYLON.Tools.Error("Invalid magic number in DDS header");
  34481. return;
  34482. }
  34483. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  34484. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  34485. return;
  34486. }
  34487. if (info.isFourCC) {
  34488. fourCC = header[off_pfFourCC];
  34489. switch (fourCC) {
  34490. case FOURCC_DXT1:
  34491. blockBytes = 8;
  34492. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  34493. break;
  34494. case FOURCC_DXT3:
  34495. blockBytes = 16;
  34496. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  34497. break;
  34498. case FOURCC_DXT5:
  34499. blockBytes = 16;
  34500. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  34501. break;
  34502. default:
  34503. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  34504. return;
  34505. }
  34506. }
  34507. mipmapCount = 1;
  34508. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  34509. mipmapCount = Math.max(1, header[off_mipmapCount]);
  34510. }
  34511. var bpp = header[off_RGBbpp];
  34512. for (var face = 0; face < faces; face++) {
  34513. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  34514. width = header[off_width];
  34515. height = header[off_height];
  34516. dataOffset = header[off_size] + 4;
  34517. for (i = 0; i < mipmapCount; ++i) {
  34518. if (info.isRGB) {
  34519. if (bpp === 24) {
  34520. dataLength = width * height * 3;
  34521. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34522. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  34523. }
  34524. else {
  34525. dataLength = width * height * 4;
  34526. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34527. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  34528. }
  34529. }
  34530. else if (info.isLuminance) {
  34531. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  34532. var unpaddedRowSize = width;
  34533. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  34534. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  34535. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34536. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  34537. }
  34538. else {
  34539. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  34540. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  34541. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  34542. }
  34543. dataOffset += dataLength;
  34544. width *= 0.5;
  34545. height *= 0.5;
  34546. width = Math.max(1.0, width);
  34547. height = Math.max(1.0, height);
  34548. }
  34549. }
  34550. };
  34551. return DDSTools;
  34552. })();
  34553. Internals.DDSTools = DDSTools;
  34554. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34555. })(BABYLON || (BABYLON = {}));
  34556. var BABYLON;
  34557. (function (BABYLON) {
  34558. var CannonJSPlugin = (function () {
  34559. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  34560. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  34561. if (iterations === void 0) { iterations = 10; }
  34562. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  34563. this.name = "CannonJSPlugin";
  34564. this._physicsMaterials = [];
  34565. this._fixedTimeStep = 1 / 60;
  34566. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  34567. this._currentCollisionGroup = 2;
  34568. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  34569. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  34570. this._tmpPosition = BABYLON.Vector3.Zero();
  34571. this._tmpQuaternion = new BABYLON.Quaternion();
  34572. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  34573. this._tmpDeltaRotation = new BABYLON.Quaternion();
  34574. this._tmpUnityRotation = new BABYLON.Quaternion();
  34575. if (!this.isSupported()) {
  34576. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  34577. return;
  34578. }
  34579. this.world = new CANNON.World();
  34580. this.world.broadphase = new CANNON.NaiveBroadphase();
  34581. this.world.solver.iterations = iterations;
  34582. }
  34583. CannonJSPlugin.prototype.setGravity = function (gravity) {
  34584. this.world.gravity.copy(gravity);
  34585. };
  34586. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  34587. this._fixedTimeStep = timeStep;
  34588. };
  34589. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  34590. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  34591. };
  34592. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  34593. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  34594. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  34595. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  34596. };
  34597. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  34598. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  34599. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  34600. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  34601. };
  34602. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  34603. //parent-child relationship. Does this impostor has a parent impostor?
  34604. if (impostor.parent) {
  34605. if (impostor.physicsBody) {
  34606. this.removePhysicsBody(impostor);
  34607. //TODO is that needed?
  34608. impostor.forceUpdate();
  34609. }
  34610. return;
  34611. }
  34612. //should a new body be created for this impostor?
  34613. if (impostor.isBodyInitRequired()) {
  34614. var shape = this._createShape(impostor);
  34615. //unregister events, if body is being changed
  34616. var oldBody = impostor.physicsBody;
  34617. if (oldBody) {
  34618. this.removePhysicsBody(impostor);
  34619. }
  34620. //create the body and material
  34621. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  34622. var bodyCreationObject = {
  34623. mass: impostor.getParam("mass"),
  34624. material: material
  34625. };
  34626. // A simple extend, in case native options were used.
  34627. var nativeOptions = impostor.getParam("nativeOptions");
  34628. for (var key in nativeOptions) {
  34629. if (nativeOptions.hasOwnProperty(key)) {
  34630. bodyCreationObject[key] = nativeOptions[key];
  34631. }
  34632. }
  34633. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  34634. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  34635. this.world.addEventListener("preStep", impostor.beforeStep);
  34636. this.world.addEventListener("postStep", impostor.afterStep);
  34637. impostor.physicsBody.addShape(shape);
  34638. this.world.add(impostor.physicsBody);
  34639. //try to keep the body moving in the right direction by taking old properties.
  34640. //Should be tested!
  34641. if (oldBody) {
  34642. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  34643. impostor.physicsBody[param].copy(oldBody[param]);
  34644. });
  34645. }
  34646. this._processChildMeshes(impostor);
  34647. }
  34648. //now update the body's transformation
  34649. this._updatePhysicsBodyTransformation(impostor);
  34650. };
  34651. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  34652. var _this = this;
  34653. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  34654. if (meshChildren.length) {
  34655. var processMesh = function (localPosition, mesh) {
  34656. var childImpostor = mesh.getPhysicsImpostor();
  34657. if (childImpostor) {
  34658. var parent = childImpostor.parent;
  34659. if (parent !== mainImpostor) {
  34660. var localPosition = mesh.position;
  34661. if (childImpostor.physicsBody) {
  34662. _this.removePhysicsBody(childImpostor);
  34663. childImpostor.physicsBody = null;
  34664. }
  34665. childImpostor.parent = mainImpostor;
  34666. childImpostor.resetUpdateFlags();
  34667. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  34668. //Add the mass of the children.
  34669. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  34670. }
  34671. }
  34672. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  34673. };
  34674. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  34675. }
  34676. };
  34677. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  34678. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  34679. this.world.removeEventListener("preStep", impostor.beforeStep);
  34680. this.world.removeEventListener("postStep", impostor.afterStep);
  34681. this.world.remove(impostor.physicsBody);
  34682. };
  34683. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  34684. var mainBody = impostorJoint.mainImpostor.physicsBody;
  34685. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  34686. if (!mainBody || !connectedBody) {
  34687. return;
  34688. }
  34689. var constraint;
  34690. var jointData = impostorJoint.joint.jointData;
  34691. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  34692. var constraintData = {
  34693. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  34694. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  34695. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  34696. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  34697. maxForce: jointData.nativeParams.maxForce,
  34698. collideConnected: !!jointData.collision
  34699. };
  34700. //Not needed, Cannon has a collideConnected flag
  34701. /*if (!jointData.collision) {
  34702. //add 1st body to a collision group of its own, if it is not in 1
  34703. if (mainBody.collisionFilterGroup === 1) {
  34704. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  34705. this._currentCollisionGroup <<= 1;
  34706. }
  34707. if (connectedBody.collisionFilterGroup === 1) {
  34708. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  34709. this._currentCollisionGroup <<= 1;
  34710. }
  34711. //add their mask to the collisionFilterMask of each other:
  34712. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  34713. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  34714. }*/
  34715. switch (impostorJoint.joint.type) {
  34716. case BABYLON.PhysicsJoint.HingeJoint:
  34717. case BABYLON.PhysicsJoint.Hinge2Joint:
  34718. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  34719. break;
  34720. case BABYLON.PhysicsJoint.DistanceJoint:
  34721. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  34722. break;
  34723. case BABYLON.PhysicsJoint.SpringJoint:
  34724. var springData = jointData;
  34725. constraint = new CANNON.Spring(mainBody, connectedBody, {
  34726. restLength: springData.length,
  34727. stiffness: springData.stiffness,
  34728. damping: springData.damping,
  34729. localAnchorA: constraintData.pivotA,
  34730. localAnchorB: constraintData.pivotB
  34731. });
  34732. break;
  34733. case BABYLON.PhysicsJoint.PointToPointJoint:
  34734. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  34735. default:
  34736. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  34737. break;
  34738. }
  34739. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  34740. constraint.collideConnected = !!jointData.collision;
  34741. impostorJoint.joint.physicsJoint = constraint;
  34742. //don't add spring as constraint, as it is not one.
  34743. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  34744. this.world.addConstraint(constraint);
  34745. }
  34746. else {
  34747. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  34748. constraint.applyForce();
  34749. });
  34750. }
  34751. };
  34752. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  34753. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  34754. };
  34755. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  34756. var index;
  34757. var mat;
  34758. for (index = 0; index < this._physicsMaterials.length; index++) {
  34759. mat = this._physicsMaterials[index];
  34760. if (mat.friction === friction && mat.restitution === restitution) {
  34761. return mat;
  34762. }
  34763. }
  34764. var currentMat = new CANNON.Material(name);
  34765. currentMat.friction = friction;
  34766. currentMat.restitution = restitution;
  34767. this._physicsMaterials.push(currentMat);
  34768. return currentMat;
  34769. };
  34770. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  34771. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  34772. };
  34773. CannonJSPlugin.prototype._createShape = function (impostor) {
  34774. var object = impostor.object;
  34775. var returnValue;
  34776. var extendSize = impostor.getObjectExtendSize();
  34777. switch (impostor.type) {
  34778. case BABYLON.PhysicsEngine.SphereImpostor:
  34779. var radiusX = extendSize.x;
  34780. var radiusY = extendSize.y;
  34781. var radiusZ = extendSize.z;
  34782. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  34783. break;
  34784. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  34785. case BABYLON.PhysicsImpostor.CylinderImpostor:
  34786. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  34787. break;
  34788. case BABYLON.PhysicsImpostor.BoxImpostor:
  34789. var box = extendSize.scale(0.5);
  34790. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  34791. break;
  34792. case BABYLON.PhysicsImpostor.PlaneImpostor:
  34793. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  34794. returnValue = new CANNON.Plane();
  34795. break;
  34796. case BABYLON.PhysicsImpostor.MeshImpostor:
  34797. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  34798. var rawFaces = object.getIndices ? object.getIndices() : [];
  34799. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  34800. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  34801. break;
  34802. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  34803. returnValue = this._createHeightmap(object);
  34804. break;
  34805. case BABYLON.PhysicsImpostor.ParticleImpostor:
  34806. returnValue = new CANNON.Particle();
  34807. break;
  34808. }
  34809. return returnValue;
  34810. };
  34811. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  34812. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34813. var matrix = [];
  34814. //For now pointDepth will not be used and will be automatically calculated.
  34815. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  34816. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  34817. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  34818. var elementSize = dim * 2 / arraySize;
  34819. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  34820. for (var i = 0; i < pos.length; i = i + 3) {
  34821. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  34822. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  34823. var y = pos[i + 1] + minY;
  34824. if (!matrix[x]) {
  34825. matrix[x] = [];
  34826. }
  34827. if (!matrix[x][z]) {
  34828. matrix[x][z] = y;
  34829. }
  34830. matrix[x][z] = Math.max(y, matrix[x][z]);
  34831. }
  34832. for (var x = 0; x <= arraySize; ++x) {
  34833. if (!matrix[x]) {
  34834. var loc = 1;
  34835. while (!matrix[(x + loc) % arraySize]) {
  34836. loc++;
  34837. }
  34838. matrix[x] = matrix[(x + loc) % arraySize].slice();
  34839. }
  34840. for (var z = 0; z <= arraySize; ++z) {
  34841. if (!matrix[x][z]) {
  34842. var loc = 1;
  34843. var newValue;
  34844. while (newValue === undefined) {
  34845. newValue = matrix[x][(z + loc++) % arraySize];
  34846. }
  34847. matrix[x][z] = newValue;
  34848. }
  34849. }
  34850. }
  34851. var shape = new CANNON.Heightfield(matrix, {
  34852. elementSize: elementSize
  34853. });
  34854. //For future reference, needed for body transformation
  34855. shape.minY = minY;
  34856. return shape;
  34857. };
  34858. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  34859. var object = impostor.object;
  34860. //make sure it is updated...
  34861. object.computeWorldMatrix && object.computeWorldMatrix(true);
  34862. // The delta between the mesh position and the mesh bounding box center
  34863. var center = impostor.getObjectCenter();
  34864. var extendSize = impostor.getObjectExtendSize();
  34865. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  34866. this._tmpPosition.copyFrom(center);
  34867. var quaternion = object.rotationQuaternion;
  34868. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  34869. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  34870. //-90 DEG in X, precalculated
  34871. quaternion = quaternion.multiply(this._minus90X);
  34872. //Invert! (Precalculated, 90 deg in X)
  34873. //No need to clone. this will never change.
  34874. impostor.setDeltaRotation(this._plus90X);
  34875. }
  34876. //If it is a heightfield, if should be centered.
  34877. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  34878. var mesh = object;
  34879. //calculate the correct body position:
  34880. var rotationQuaternion = mesh.rotationQuaternion;
  34881. mesh.rotationQuaternion = this._tmpUnityRotation;
  34882. mesh.computeWorldMatrix(true);
  34883. //get original center with no rotation
  34884. var c = center.clone();
  34885. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  34886. //rotation is back
  34887. mesh.rotationQuaternion = rotationQuaternion;
  34888. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  34889. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  34890. mesh.setPivotMatrix(p);
  34891. mesh.computeWorldMatrix(true);
  34892. //calculate the translation
  34893. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  34894. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  34895. //add it inverted to the delta
  34896. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  34897. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  34898. mesh.setPivotMatrix(oldPivot);
  34899. mesh.computeWorldMatrix(true);
  34900. }
  34901. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  34902. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  34903. this._tmpPosition.copyFrom(object.position);
  34904. }
  34905. impostor.setDeltaPosition(this._tmpDeltaPosition);
  34906. //Now update the impostor object
  34907. impostor.physicsBody.position.copy(this._tmpPosition);
  34908. impostor.physicsBody.quaternion.copy(quaternion);
  34909. };
  34910. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  34911. impostor.object.position.copyFrom(impostor.physicsBody.position);
  34912. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  34913. };
  34914. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  34915. impostor.physicsBody.position.copy(newPosition);
  34916. impostor.physicsBody.quaternion.copy(newRotation);
  34917. };
  34918. CannonJSPlugin.prototype.isSupported = function () {
  34919. return window.CANNON !== undefined;
  34920. };
  34921. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  34922. impostor.physicsBody.velocity.copy(velocity);
  34923. };
  34924. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  34925. impostor.physicsBody.angularVelocity.copy(velocity);
  34926. };
  34927. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  34928. var v = impostor.physicsBody.velocity;
  34929. if (!v)
  34930. return null;
  34931. return new BABYLON.Vector3(v.x, v.y, v.z);
  34932. };
  34933. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  34934. var v = impostor.physicsBody.angularVelocity;
  34935. if (!v)
  34936. return null;
  34937. return new BABYLON.Vector3(v.x, v.y, v.z);
  34938. };
  34939. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  34940. impostor.physicsBody.mass = mass;
  34941. impostor.physicsBody.updateMassProperties();
  34942. };
  34943. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  34944. impostor.physicsBody.sleep();
  34945. };
  34946. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  34947. impostor.physicsBody.wakeUp();
  34948. };
  34949. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  34950. joint.physicsJoint.distance = maxDistance;
  34951. };
  34952. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  34953. if (!motorIndex) {
  34954. joint.physicsJoint.enableMotor();
  34955. }
  34956. };
  34957. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  34958. if (!motorIndex) {
  34959. joint.physicsJoint.disableMotor();
  34960. }
  34961. };
  34962. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  34963. if (!motorIndex) {
  34964. joint.physicsJoint.enableMotor();
  34965. joint.physicsJoint.setMotorSpeed(speed);
  34966. if (maxForce) {
  34967. this.setLimit(joint, maxForce);
  34968. }
  34969. }
  34970. };
  34971. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  34972. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  34973. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  34974. };
  34975. CannonJSPlugin.prototype.dispose = function () {
  34976. //nothing to do, actually.
  34977. };
  34978. return CannonJSPlugin;
  34979. })();
  34980. BABYLON.CannonJSPlugin = CannonJSPlugin;
  34981. })(BABYLON || (BABYLON = {}));
  34982. var BABYLON;
  34983. (function (BABYLON) {
  34984. var OimoJSPlugin = (function () {
  34985. function OimoJSPlugin(iterations) {
  34986. this.name = "OimoJSPlugin";
  34987. this._tmpImpostorsArray = [];
  34988. this._tmpPositionVector = BABYLON.Vector3.Zero();
  34989. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  34990. this.world.clear();
  34991. //making sure no stats are calculated
  34992. this.world.isNoStat = true;
  34993. }
  34994. OimoJSPlugin.prototype.setGravity = function (gravity) {
  34995. this.world.gravity.copy(gravity);
  34996. };
  34997. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  34998. this.world.timeStep = timeStep;
  34999. };
  35000. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  35001. var _this = this;
  35002. impostors.forEach(function (impostor) {
  35003. impostor.beforeStep();
  35004. });
  35005. this.world.step();
  35006. impostors.forEach(function (impostor) {
  35007. impostor.afterStep();
  35008. //update the ordered impostors array
  35009. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  35010. });
  35011. //check for collisions
  35012. var contact = this.world.contacts;
  35013. while (contact !== null) {
  35014. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  35015. contact = contact.next;
  35016. continue;
  35017. }
  35018. //is this body colliding with any other? get the impostor
  35019. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  35020. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  35021. if (!mainImpostor || !collidingImpostor) {
  35022. contact = contact.next;
  35023. continue;
  35024. }
  35025. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  35026. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  35027. contact = contact.next;
  35028. }
  35029. };
  35030. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  35031. var mass = impostor.physicsBody.massInfo.mass;
  35032. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  35033. };
  35034. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  35035. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  35036. this.applyImpulse(impostor, force, contactPoint);
  35037. };
  35038. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  35039. var _this = this;
  35040. //parent-child relationship. Does this impostor has a parent impostor?
  35041. if (impostor.parent) {
  35042. if (impostor.physicsBody) {
  35043. this.removePhysicsBody(impostor);
  35044. //TODO is that needed?
  35045. impostor.forceUpdate();
  35046. }
  35047. return;
  35048. }
  35049. if (impostor.isBodyInitRequired()) {
  35050. var bodyConfig = {
  35051. name: impostor.uniqueId,
  35052. //Oimo must have mass, also for static objects.
  35053. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  35054. size: [],
  35055. type: [],
  35056. pos: [],
  35057. rot: [],
  35058. move: impostor.getParam("mass") !== 0,
  35059. //Supporting older versions of Oimo
  35060. world: this.world
  35061. };
  35062. var impostors = [impostor];
  35063. function addToArray(parent) {
  35064. if (!parent.getChildMeshes)
  35065. return;
  35066. parent.getChildMeshes().forEach(function (m) {
  35067. if (m.physicsImpostor) {
  35068. impostors.push(m.physicsImpostor);
  35069. m.physicsImpostor._init();
  35070. }
  35071. });
  35072. }
  35073. addToArray(impostor.object);
  35074. function checkWithEpsilon(value) {
  35075. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  35076. }
  35077. impostors.forEach(function (i) {
  35078. //get the correct bounding box
  35079. var oldQuaternion = i.object.rotationQuaternion;
  35080. var rot = new OIMO.Euler().setFromQuaternion({
  35081. x: impostor.object.rotationQuaternion.x,
  35082. y: impostor.object.rotationQuaternion.y,
  35083. z: impostor.object.rotationQuaternion.z,
  35084. s: impostor.object.rotationQuaternion.w });
  35085. var extendSize = i.getObjectExtendSize();
  35086. if (i === impostor) {
  35087. var center = impostor.getObjectCenter();
  35088. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  35089. //Can also use Array.prototype.push.apply
  35090. bodyConfig.pos.push(center.x);
  35091. bodyConfig.pos.push(center.y);
  35092. bodyConfig.pos.push(center.z);
  35093. //tmp solution
  35094. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  35095. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  35096. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  35097. }
  35098. else {
  35099. bodyConfig.pos.push(i.object.position.x);
  35100. bodyConfig.pos.push(i.object.position.y);
  35101. bodyConfig.pos.push(i.object.position.z);
  35102. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  35103. bodyConfig.rot.push(0);
  35104. bodyConfig.rot.push(0);
  35105. bodyConfig.rot.push(0);
  35106. }
  35107. // register mesh
  35108. switch (i.type) {
  35109. case BABYLON.PhysicsImpostor.ParticleImpostor:
  35110. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  35111. case BABYLON.PhysicsImpostor.SphereImpostor:
  35112. var radiusX = extendSize.x;
  35113. var radiusY = extendSize.y;
  35114. var radiusZ = extendSize.z;
  35115. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  35116. bodyConfig.type.push('sphere');
  35117. //due to the way oimo works with compounds, add 3 times
  35118. bodyConfig.size.push(size);
  35119. bodyConfig.size.push(size);
  35120. bodyConfig.size.push(size);
  35121. break;
  35122. case BABYLON.PhysicsImpostor.CylinderImpostor:
  35123. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  35124. var sizeY = checkWithEpsilon(extendSize.y);
  35125. bodyConfig.type.push('cylinder');
  35126. bodyConfig.size.push(sizeX);
  35127. bodyConfig.size.push(sizeY);
  35128. //due to the way oimo works with compounds, add one more value.
  35129. bodyConfig.size.push(sizeY);
  35130. break;
  35131. case BABYLON.PhysicsImpostor.PlaneImpostor:
  35132. case BABYLON.PhysicsImpostor.BoxImpostor:
  35133. default:
  35134. var sizeX = checkWithEpsilon(extendSize.x);
  35135. var sizeY = checkWithEpsilon(extendSize.y);
  35136. var sizeZ = checkWithEpsilon(extendSize.z);
  35137. bodyConfig.type.push('box');
  35138. bodyConfig.size.push(sizeX);
  35139. bodyConfig.size.push(sizeY);
  35140. bodyConfig.size.push(sizeZ);
  35141. break;
  35142. }
  35143. //actually not needed, but hey...
  35144. i.object.rotationQuaternion = oldQuaternion;
  35145. });
  35146. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  35147. }
  35148. else {
  35149. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  35150. }
  35151. impostor.setDeltaPosition(this._tmpPositionVector);
  35152. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  35153. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  35154. };
  35155. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  35156. //impostor.physicsBody.dispose();
  35157. //Same as : (older oimo versions)
  35158. this.world.removeRigidBody(impostor.physicsBody);
  35159. };
  35160. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  35161. var mainBody = impostorJoint.mainImpostor.physicsBody;
  35162. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  35163. if (!mainBody || !connectedBody) {
  35164. return;
  35165. }
  35166. var jointData = impostorJoint.joint.jointData;
  35167. var options = jointData.nativeParams || {};
  35168. var type;
  35169. var nativeJointData = {
  35170. body1: mainBody,
  35171. body2: connectedBody,
  35172. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  35173. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  35174. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  35175. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  35176. min: options.min,
  35177. max: options.max,
  35178. collision: options.collision || jointData.collision,
  35179. spring: options.spring,
  35180. //supporting older version of Oimo
  35181. world: this.world
  35182. };
  35183. switch (impostorJoint.joint.type) {
  35184. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  35185. type = "jointBall";
  35186. break;
  35187. case BABYLON.PhysicsJoint.SpringJoint:
  35188. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  35189. var springData = jointData;
  35190. nativeJointData.min = springData.length || nativeJointData.min;
  35191. //Max should also be set, just make sure it is at least min
  35192. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  35193. case BABYLON.PhysicsJoint.DistanceJoint:
  35194. type = "jointDistance";
  35195. nativeJointData.max = jointData.maxDistance;
  35196. break;
  35197. case BABYLON.PhysicsJoint.PrismaticJoint:
  35198. type = "jointPrisme";
  35199. break;
  35200. case BABYLON.PhysicsJoint.SliderJoint:
  35201. type = "jointSlide";
  35202. break;
  35203. case BABYLON.PhysicsJoint.WheelJoint:
  35204. type = "jointWheel";
  35205. break;
  35206. case BABYLON.PhysicsJoint.HingeJoint:
  35207. default:
  35208. type = "jointHinge";
  35209. break;
  35210. }
  35211. nativeJointData.type = type;
  35212. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  35213. };
  35214. OimoJSPlugin.prototype.removeJoint = function (joint) {
  35215. joint.joint.physicsJoint.dispose();
  35216. };
  35217. OimoJSPlugin.prototype.isSupported = function () {
  35218. return OIMO !== undefined;
  35219. };
  35220. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  35221. if (!impostor.physicsBody.sleeping) {
  35222. //TODO check that
  35223. if (impostor.physicsBody.shapes.next) {
  35224. var parentShape = this._getLastShape(impostor.physicsBody);
  35225. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  35226. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  35227. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  35228. }
  35229. else {
  35230. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  35231. }
  35232. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  35233. }
  35234. };
  35235. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  35236. var body = impostor.physicsBody;
  35237. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  35238. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  35239. body.syncShapes();
  35240. body.awake();
  35241. };
  35242. OimoJSPlugin.prototype._getLastShape = function (body) {
  35243. var lastShape = body.shapes;
  35244. while (lastShape.next) {
  35245. lastShape = lastShape.next;
  35246. }
  35247. return lastShape;
  35248. };
  35249. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  35250. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  35251. };
  35252. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  35253. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  35254. };
  35255. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  35256. var v = impostor.physicsBody.linearVelocity;
  35257. if (!v)
  35258. return null;
  35259. return new BABYLON.Vector3(v.x, v.y, v.z);
  35260. };
  35261. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  35262. var v = impostor.physicsBody.angularVelocity;
  35263. if (!v)
  35264. return null;
  35265. return new BABYLON.Vector3(v.x, v.y, v.z);
  35266. };
  35267. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  35268. var staticBody = mass === 0;
  35269. //this will actually set the body's density and not its mass.
  35270. //But this is how oimo treats the mass variable.
  35271. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  35272. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  35273. };
  35274. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  35275. impostor.physicsBody.sleep();
  35276. };
  35277. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  35278. impostor.physicsBody.awake();
  35279. };
  35280. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  35281. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  35282. if (minDistance !== void 0) {
  35283. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  35284. }
  35285. };
  35286. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  35287. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.limitMotor;
  35288. if (motor) {
  35289. motor.setMotor(speed, maxForce);
  35290. }
  35291. };
  35292. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  35293. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.limitMotor;
  35294. if (motor) {
  35295. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  35296. }
  35297. };
  35298. OimoJSPlugin.prototype.dispose = function () {
  35299. this.world.clear();
  35300. };
  35301. return OimoJSPlugin;
  35302. })();
  35303. BABYLON.OimoJSPlugin = OimoJSPlugin;
  35304. })(BABYLON || (BABYLON = {}));
  35305. var BABYLON;
  35306. (function (BABYLON) {
  35307. var DisplayPassPostProcess = (function (_super) {
  35308. __extends(DisplayPassPostProcess, _super);
  35309. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  35310. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  35311. }
  35312. return DisplayPassPostProcess;
  35313. })(BABYLON.PostProcess);
  35314. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  35315. })(BABYLON || (BABYLON = {}));
  35316. var BABYLON;
  35317. (function (BABYLON) {
  35318. var SimplificationSettings = (function () {
  35319. function SimplificationSettings(quality, distance, optimizeMesh) {
  35320. this.quality = quality;
  35321. this.distance = distance;
  35322. this.optimizeMesh = optimizeMesh;
  35323. }
  35324. return SimplificationSettings;
  35325. })();
  35326. BABYLON.SimplificationSettings = SimplificationSettings;
  35327. var SimplificationQueue = (function () {
  35328. function SimplificationQueue() {
  35329. this.running = false;
  35330. this._simplificationArray = [];
  35331. }
  35332. SimplificationQueue.prototype.addTask = function (task) {
  35333. this._simplificationArray.push(task);
  35334. };
  35335. SimplificationQueue.prototype.executeNext = function () {
  35336. var task = this._simplificationArray.pop();
  35337. if (task) {
  35338. this.running = true;
  35339. this.runSimplification(task);
  35340. }
  35341. else {
  35342. this.running = false;
  35343. }
  35344. };
  35345. SimplificationQueue.prototype.runSimplification = function (task) {
  35346. var _this = this;
  35347. if (task.parallelProcessing) {
  35348. //parallel simplifier
  35349. task.settings.forEach(function (setting) {
  35350. var simplifier = _this.getSimplifier(task);
  35351. simplifier.simplify(setting, function (newMesh) {
  35352. task.mesh.addLODLevel(setting.distance, newMesh);
  35353. newMesh.isVisible = true;
  35354. //check if it is the last
  35355. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  35356. //all done, run the success callback.
  35357. task.successCallback();
  35358. }
  35359. _this.executeNext();
  35360. });
  35361. });
  35362. }
  35363. else {
  35364. //single simplifier.
  35365. var simplifier = this.getSimplifier(task);
  35366. var runDecimation = function (setting, callback) {
  35367. simplifier.simplify(setting, function (newMesh) {
  35368. task.mesh.addLODLevel(setting.distance, newMesh);
  35369. newMesh.isVisible = true;
  35370. //run the next quality level
  35371. callback();
  35372. });
  35373. };
  35374. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  35375. runDecimation(task.settings[loop.index], function () {
  35376. loop.executeNext();
  35377. });
  35378. }, function () {
  35379. //execution ended, run the success callback.
  35380. if (task.successCallback) {
  35381. task.successCallback();
  35382. }
  35383. _this.executeNext();
  35384. });
  35385. }
  35386. };
  35387. SimplificationQueue.prototype.getSimplifier = function (task) {
  35388. switch (task.simplificationType) {
  35389. case SimplificationType.QUADRATIC:
  35390. default:
  35391. return new QuadraticErrorSimplification(task.mesh);
  35392. }
  35393. };
  35394. return SimplificationQueue;
  35395. })();
  35396. BABYLON.SimplificationQueue = SimplificationQueue;
  35397. /**
  35398. * The implemented types of simplification.
  35399. * At the moment only Quadratic Error Decimation is implemented.
  35400. */
  35401. (function (SimplificationType) {
  35402. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  35403. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  35404. var SimplificationType = BABYLON.SimplificationType;
  35405. var DecimationTriangle = (function () {
  35406. function DecimationTriangle(vertices) {
  35407. this.vertices = vertices;
  35408. this.error = new Array(4);
  35409. this.deleted = false;
  35410. this.isDirty = false;
  35411. this.deletePending = false;
  35412. this.borderFactor = 0;
  35413. }
  35414. return DecimationTriangle;
  35415. })();
  35416. BABYLON.DecimationTriangle = DecimationTriangle;
  35417. var DecimationVertex = (function () {
  35418. function DecimationVertex(position, id) {
  35419. this.position = position;
  35420. this.id = id;
  35421. this.isBorder = true;
  35422. this.q = new QuadraticMatrix();
  35423. this.triangleCount = 0;
  35424. this.triangleStart = 0;
  35425. this.originalOffsets = [];
  35426. }
  35427. DecimationVertex.prototype.updatePosition = function (newPosition) {
  35428. this.position.copyFrom(newPosition);
  35429. };
  35430. return DecimationVertex;
  35431. })();
  35432. BABYLON.DecimationVertex = DecimationVertex;
  35433. var QuadraticMatrix = (function () {
  35434. function QuadraticMatrix(data) {
  35435. this.data = new Array(10);
  35436. for (var i = 0; i < 10; ++i) {
  35437. if (data && data[i]) {
  35438. this.data[i] = data[i];
  35439. }
  35440. else {
  35441. this.data[i] = 0;
  35442. }
  35443. }
  35444. }
  35445. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  35446. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  35447. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  35448. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  35449. return det;
  35450. };
  35451. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  35452. for (var i = 0; i < 10; ++i) {
  35453. this.data[i] += matrix.data[i];
  35454. }
  35455. };
  35456. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  35457. for (var i = 0; i < 10; ++i) {
  35458. this.data[i] += data[i];
  35459. }
  35460. };
  35461. QuadraticMatrix.prototype.add = function (matrix) {
  35462. var m = new QuadraticMatrix();
  35463. for (var i = 0; i < 10; ++i) {
  35464. m.data[i] = this.data[i] + matrix.data[i];
  35465. }
  35466. return m;
  35467. };
  35468. QuadraticMatrix.FromData = function (a, b, c, d) {
  35469. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  35470. };
  35471. //returning an array to avoid garbage collection
  35472. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  35473. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  35474. };
  35475. return QuadraticMatrix;
  35476. })();
  35477. BABYLON.QuadraticMatrix = QuadraticMatrix;
  35478. var Reference = (function () {
  35479. function Reference(vertexId, triangleId) {
  35480. this.vertexId = vertexId;
  35481. this.triangleId = triangleId;
  35482. }
  35483. return Reference;
  35484. })();
  35485. BABYLON.Reference = Reference;
  35486. /**
  35487. * An implementation of the Quadratic Error simplification algorithm.
  35488. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  35489. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  35490. * @author RaananW
  35491. */
  35492. var QuadraticErrorSimplification = (function () {
  35493. function QuadraticErrorSimplification(_mesh) {
  35494. this._mesh = _mesh;
  35495. this.initialized = false;
  35496. this.syncIterations = 5000;
  35497. this.aggressiveness = 7;
  35498. this.decimationIterations = 100;
  35499. this.boundingBoxEpsilon = BABYLON.Epsilon;
  35500. }
  35501. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  35502. var _this = this;
  35503. this.initDecimatedMesh();
  35504. //iterating through the submeshes array, one after the other.
  35505. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  35506. _this.initWithMesh(loop.index, function () {
  35507. _this.runDecimation(settings, loop.index, function () {
  35508. loop.executeNext();
  35509. });
  35510. }, settings.optimizeMesh);
  35511. }, function () {
  35512. setTimeout(function () {
  35513. successCallback(_this._reconstructedMesh);
  35514. }, 0);
  35515. });
  35516. };
  35517. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  35518. var _this = this;
  35519. var gCount = 0;
  35520. triangle.vertices.forEach(function (vertex) {
  35521. var count = 0;
  35522. var vPos = vertex.position;
  35523. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  35524. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  35525. ++count;
  35526. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  35527. ++count;
  35528. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  35529. ++count;
  35530. if (count > 1) {
  35531. ++gCount;
  35532. }
  35533. ;
  35534. });
  35535. if (gCount > 1) {
  35536. console.log(triangle, gCount);
  35537. }
  35538. return gCount > 1;
  35539. };
  35540. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  35541. var _this = this;
  35542. var targetCount = ~~(this.triangles.length * settings.quality);
  35543. var deletedTriangles = 0;
  35544. var triangleCount = this.triangles.length;
  35545. var iterationFunction = function (iteration, callback) {
  35546. setTimeout(function () {
  35547. if (iteration % 5 === 0) {
  35548. _this.updateMesh(iteration === 0);
  35549. }
  35550. for (var i = 0; i < _this.triangles.length; ++i) {
  35551. _this.triangles[i].isDirty = false;
  35552. }
  35553. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  35554. var trianglesIterator = function (i) {
  35555. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  35556. var t = _this.triangles[tIdx];
  35557. if (!t)
  35558. return;
  35559. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  35560. return;
  35561. }
  35562. for (var j = 0; j < 3; ++j) {
  35563. if (t.error[j] < threshold) {
  35564. var deleted0 = [];
  35565. var deleted1 = [];
  35566. var v0 = t.vertices[j];
  35567. var v1 = t.vertices[(j + 1) % 3];
  35568. if (v0.isBorder || v1.isBorder)
  35569. continue;
  35570. var p = BABYLON.Vector3.Zero();
  35571. var n = BABYLON.Vector3.Zero();
  35572. var uv = BABYLON.Vector2.Zero();
  35573. var color = new BABYLON.Color4(0, 0, 0, 1);
  35574. _this.calculateError(v0, v1, p, n, uv, color);
  35575. var delTr = [];
  35576. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  35577. continue;
  35578. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  35579. continue;
  35580. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  35581. continue;
  35582. var uniqueArray = [];
  35583. delTr.forEach(function (deletedT) {
  35584. if (uniqueArray.indexOf(deletedT) === -1) {
  35585. deletedT.deletePending = true;
  35586. uniqueArray.push(deletedT);
  35587. }
  35588. });
  35589. if (uniqueArray.length % 2 !== 0) {
  35590. continue;
  35591. }
  35592. v0.q = v1.q.add(v0.q);
  35593. v0.updatePosition(p);
  35594. var tStart = _this.references.length;
  35595. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  35596. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  35597. var tCount = _this.references.length - tStart;
  35598. if (tCount <= v0.triangleCount) {
  35599. if (tCount) {
  35600. for (var c = 0; c < tCount; c++) {
  35601. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  35602. }
  35603. }
  35604. }
  35605. else {
  35606. v0.triangleStart = tStart;
  35607. }
  35608. v0.triangleCount = tCount;
  35609. break;
  35610. }
  35611. }
  35612. };
  35613. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  35614. }, 0);
  35615. };
  35616. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  35617. if (triangleCount - deletedTriangles <= targetCount)
  35618. loop.breakLoop();
  35619. else {
  35620. iterationFunction(loop.index, function () {
  35621. loop.executeNext();
  35622. });
  35623. }
  35624. }, function () {
  35625. setTimeout(function () {
  35626. //reconstruct this part of the mesh
  35627. _this.reconstructMesh(submeshIndex);
  35628. successCallback();
  35629. }, 0);
  35630. });
  35631. };
  35632. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  35633. var _this = this;
  35634. this.vertices = [];
  35635. this.triangles = [];
  35636. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35637. var indices = this._mesh.getIndices();
  35638. var submesh = this._mesh.subMeshes[submeshIndex];
  35639. var findInVertices = function (positionToSearch) {
  35640. if (optimizeMesh) {
  35641. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  35642. if (_this.vertices[ii].position.equals(positionToSearch)) {
  35643. return _this.vertices[ii];
  35644. }
  35645. }
  35646. }
  35647. return null;
  35648. };
  35649. var vertexReferences = [];
  35650. var vertexInit = function (i) {
  35651. var offset = i + submesh.verticesStart;
  35652. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  35653. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  35654. vertex.originalOffsets.push(offset);
  35655. if (vertex.id === _this.vertices.length) {
  35656. _this.vertices.push(vertex);
  35657. }
  35658. vertexReferences.push(vertex.id);
  35659. };
  35660. //var totalVertices = mesh.getTotalVertices();
  35661. var totalVertices = submesh.verticesCount;
  35662. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  35663. var indicesInit = function (i) {
  35664. var offset = (submesh.indexStart / 3) + i;
  35665. var pos = (offset * 3);
  35666. var i0 = indices[pos + 0];
  35667. var i1 = indices[pos + 1];
  35668. var i2 = indices[pos + 2];
  35669. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  35670. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  35671. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  35672. var triangle = new DecimationTriangle([v0, v1, v2]);
  35673. triangle.originalOffset = pos;
  35674. _this.triangles.push(triangle);
  35675. };
  35676. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  35677. _this.init(callback);
  35678. });
  35679. });
  35680. };
  35681. QuadraticErrorSimplification.prototype.init = function (callback) {
  35682. var _this = this;
  35683. var triangleInit1 = function (i) {
  35684. var t = _this.triangles[i];
  35685. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  35686. for (var j = 0; j < 3; j++) {
  35687. 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))));
  35688. }
  35689. };
  35690. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  35691. var triangleInit2 = function (i) {
  35692. var t = _this.triangles[i];
  35693. for (var j = 0; j < 3; ++j) {
  35694. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  35695. }
  35696. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  35697. };
  35698. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  35699. _this.initialized = true;
  35700. callback();
  35701. });
  35702. });
  35703. };
  35704. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  35705. var newTriangles = [];
  35706. var i;
  35707. for (i = 0; i < this.vertices.length; ++i) {
  35708. this.vertices[i].triangleCount = 0;
  35709. }
  35710. var t;
  35711. var j;
  35712. for (i = 0; i < this.triangles.length; ++i) {
  35713. if (!this.triangles[i].deleted) {
  35714. t = this.triangles[i];
  35715. for (j = 0; j < 3; ++j) {
  35716. t.vertices[j].triangleCount = 1;
  35717. }
  35718. newTriangles.push(t);
  35719. }
  35720. }
  35721. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  35722. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  35723. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  35724. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  35725. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35726. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  35727. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  35728. var vertexCount = 0;
  35729. for (i = 0; i < this.vertices.length; ++i) {
  35730. var vertex = this.vertices[i];
  35731. vertex.id = vertexCount;
  35732. if (vertex.triangleCount) {
  35733. vertex.originalOffsets.forEach(function (originalOffset) {
  35734. newPositionData.push(vertex.position.x);
  35735. newPositionData.push(vertex.position.y);
  35736. newPositionData.push(vertex.position.z);
  35737. newNormalData.push(normalData[originalOffset * 3]);
  35738. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  35739. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  35740. if (uvs && uvs.length) {
  35741. newUVsData.push(uvs[(originalOffset * 2)]);
  35742. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  35743. }
  35744. else if (colorsData && colorsData.length) {
  35745. newColorsData.push(colorsData[(originalOffset * 4)]);
  35746. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  35747. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  35748. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  35749. }
  35750. ++vertexCount;
  35751. });
  35752. }
  35753. }
  35754. var startingIndex = this._reconstructedMesh.getTotalIndices();
  35755. var startingVertex = this._reconstructedMesh.getTotalVertices();
  35756. var submeshesArray = this._reconstructedMesh.subMeshes;
  35757. this._reconstructedMesh.subMeshes = [];
  35758. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  35759. var originalIndices = this._mesh.getIndices();
  35760. for (i = 0; i < newTriangles.length; ++i) {
  35761. t = newTriangles[i]; //now get the new referencing point for each vertex
  35762. [0, 1, 2].forEach(function (idx) {
  35763. var id = originalIndices[t.originalOffset + idx];
  35764. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  35765. if (offset < 0)
  35766. offset = 0;
  35767. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  35768. });
  35769. }
  35770. //overwriting the old vertex buffers and indices.
  35771. this._reconstructedMesh.setIndices(newIndicesArray);
  35772. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  35773. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  35774. if (newUVsData.length > 0)
  35775. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  35776. if (newColorsData.length > 0)
  35777. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  35778. //create submesh
  35779. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  35780. if (submeshIndex > 0) {
  35781. this._reconstructedMesh.subMeshes = [];
  35782. submeshesArray.forEach(function (submesh) {
  35783. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  35784. });
  35785. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  35786. }
  35787. };
  35788. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  35789. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  35790. this._reconstructedMesh.material = this._mesh.material;
  35791. this._reconstructedMesh.parent = this._mesh.parent;
  35792. this._reconstructedMesh.isVisible = false;
  35793. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  35794. };
  35795. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  35796. for (var i = 0; i < vertex1.triangleCount; ++i) {
  35797. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  35798. if (t.deleted)
  35799. continue;
  35800. var s = this.references[vertex1.triangleStart + i].vertexId;
  35801. var v1 = t.vertices[(s + 1) % 3];
  35802. var v2 = t.vertices[(s + 2) % 3];
  35803. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  35804. deletedArray[i] = true;
  35805. delTr.push(t);
  35806. continue;
  35807. }
  35808. var d1 = v1.position.subtract(point);
  35809. d1 = d1.normalize();
  35810. var d2 = v2.position.subtract(point);
  35811. d2 = d2.normalize();
  35812. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  35813. return true;
  35814. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  35815. deletedArray[i] = false;
  35816. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  35817. return true;
  35818. }
  35819. return false;
  35820. };
  35821. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  35822. var newDeleted = deletedTriangles;
  35823. for (var i = 0; i < vertex.triangleCount; ++i) {
  35824. var ref = this.references[vertex.triangleStart + i];
  35825. var t = this.triangles[ref.triangleId];
  35826. if (t.deleted)
  35827. continue;
  35828. if (deletedArray[i] && t.deletePending) {
  35829. t.deleted = true;
  35830. newDeleted++;
  35831. continue;
  35832. }
  35833. t.vertices[ref.vertexId] = origVertex;
  35834. t.isDirty = true;
  35835. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  35836. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  35837. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  35838. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  35839. this.references.push(ref);
  35840. }
  35841. return newDeleted;
  35842. };
  35843. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  35844. for (var i = 0; i < this.vertices.length; ++i) {
  35845. var vCount = [];
  35846. var vId = [];
  35847. var v = this.vertices[i];
  35848. var j;
  35849. for (j = 0; j < v.triangleCount; ++j) {
  35850. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  35851. for (var ii = 0; ii < 3; ii++) {
  35852. var ofs = 0;
  35853. var vv = triangle.vertices[ii];
  35854. while (ofs < vCount.length) {
  35855. if (vId[ofs] === vv.id)
  35856. break;
  35857. ++ofs;
  35858. }
  35859. if (ofs === vCount.length) {
  35860. vCount.push(1);
  35861. vId.push(vv.id);
  35862. }
  35863. else {
  35864. vCount[ofs]++;
  35865. }
  35866. }
  35867. }
  35868. for (j = 0; j < vCount.length; ++j) {
  35869. if (vCount[j] === 1) {
  35870. this.vertices[vId[j]].isBorder = true;
  35871. }
  35872. else {
  35873. this.vertices[vId[j]].isBorder = false;
  35874. }
  35875. }
  35876. }
  35877. };
  35878. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  35879. if (identifyBorders === void 0) { identifyBorders = false; }
  35880. var i;
  35881. if (!identifyBorders) {
  35882. var newTrianglesVector = [];
  35883. for (i = 0; i < this.triangles.length; ++i) {
  35884. if (!this.triangles[i].deleted) {
  35885. newTrianglesVector.push(this.triangles[i]);
  35886. }
  35887. }
  35888. this.triangles = newTrianglesVector;
  35889. }
  35890. for (i = 0; i < this.vertices.length; ++i) {
  35891. this.vertices[i].triangleCount = 0;
  35892. this.vertices[i].triangleStart = 0;
  35893. }
  35894. var t;
  35895. var j;
  35896. var v;
  35897. for (i = 0; i < this.triangles.length; ++i) {
  35898. t = this.triangles[i];
  35899. for (j = 0; j < 3; ++j) {
  35900. v = t.vertices[j];
  35901. v.triangleCount++;
  35902. }
  35903. }
  35904. var tStart = 0;
  35905. for (i = 0; i < this.vertices.length; ++i) {
  35906. this.vertices[i].triangleStart = tStart;
  35907. tStart += this.vertices[i].triangleCount;
  35908. this.vertices[i].triangleCount = 0;
  35909. }
  35910. var newReferences = new Array(this.triangles.length * 3);
  35911. for (i = 0; i < this.triangles.length; ++i) {
  35912. t = this.triangles[i];
  35913. for (j = 0; j < 3; ++j) {
  35914. v = t.vertices[j];
  35915. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  35916. v.triangleCount++;
  35917. }
  35918. }
  35919. this.references = newReferences;
  35920. if (identifyBorders) {
  35921. this.identifyBorder();
  35922. }
  35923. };
  35924. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  35925. var x = point.x;
  35926. var y = point.y;
  35927. var z = point.z;
  35928. 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
  35929. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  35930. };
  35931. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  35932. var q = vertex1.q.add(vertex2.q);
  35933. var border = vertex1.isBorder && vertex2.isBorder;
  35934. var error = 0;
  35935. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  35936. if (qDet !== 0 && !border) {
  35937. if (!pointResult) {
  35938. pointResult = BABYLON.Vector3.Zero();
  35939. }
  35940. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  35941. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  35942. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  35943. error = this.vertexError(q, pointResult);
  35944. }
  35945. else {
  35946. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  35947. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  35948. var error1 = this.vertexError(q, vertex1.position);
  35949. var error2 = this.vertexError(q, vertex2.position);
  35950. var error3 = this.vertexError(q, p3);
  35951. error = Math.min(error1, error2, error3);
  35952. if (error === error1) {
  35953. if (pointResult) {
  35954. pointResult.copyFrom(vertex1.position);
  35955. }
  35956. }
  35957. else if (error === error2) {
  35958. if (pointResult) {
  35959. pointResult.copyFrom(vertex2.position);
  35960. }
  35961. }
  35962. else {
  35963. if (pointResult) {
  35964. pointResult.copyFrom(p3);
  35965. }
  35966. }
  35967. }
  35968. return error;
  35969. };
  35970. return QuadraticErrorSimplification;
  35971. })();
  35972. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  35973. })(BABYLON || (BABYLON = {}));
  35974. var BABYLON;
  35975. (function (BABYLON) {
  35976. var serializedGeometries = [];
  35977. var serializeGeometry = function (geometry, serializationGeometries) {
  35978. if (serializedGeometries[geometry.id]) {
  35979. return;
  35980. }
  35981. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  35982. serializationGeometries.boxes.push(geometry.serialize());
  35983. }
  35984. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  35985. serializationGeometries.spheres.push(geometry.serialize());
  35986. }
  35987. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  35988. serializationGeometries.cylinders.push(geometry.serialize());
  35989. }
  35990. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  35991. serializationGeometries.toruses.push(geometry.serialize());
  35992. }
  35993. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  35994. serializationGeometries.grounds.push(geometry.serialize());
  35995. }
  35996. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  35997. serializationGeometries.planes.push(geometry.serialize());
  35998. }
  35999. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  36000. serializationGeometries.torusKnots.push(geometry.serialize());
  36001. }
  36002. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  36003. throw new Error("Unknown primitive type");
  36004. }
  36005. else {
  36006. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  36007. }
  36008. serializedGeometries[geometry.id] = true;
  36009. };
  36010. var serializeMesh = function (mesh, serializationScene) {
  36011. var serializationObject = {};
  36012. serializationObject.name = mesh.name;
  36013. serializationObject.id = mesh.id;
  36014. if (BABYLON.Tags.HasTags(mesh)) {
  36015. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  36016. }
  36017. serializationObject.position = mesh.position.asArray();
  36018. if (mesh.rotationQuaternion) {
  36019. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  36020. }
  36021. else if (mesh.rotation) {
  36022. serializationObject.rotation = mesh.rotation.asArray();
  36023. }
  36024. serializationObject.scaling = mesh.scaling.asArray();
  36025. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  36026. serializationObject.isEnabled = mesh.isEnabled();
  36027. serializationObject.isVisible = mesh.isVisible;
  36028. serializationObject.infiniteDistance = mesh.infiniteDistance;
  36029. serializationObject.pickable = mesh.isPickable;
  36030. serializationObject.receiveShadows = mesh.receiveShadows;
  36031. serializationObject.billboardMode = mesh.billboardMode;
  36032. serializationObject.visibility = mesh.visibility;
  36033. serializationObject.checkCollisions = mesh.checkCollisions;
  36034. // Parent
  36035. if (mesh.parent) {
  36036. serializationObject.parentId = mesh.parent.id;
  36037. }
  36038. // Geometry
  36039. var geometry = mesh._geometry;
  36040. if (geometry) {
  36041. var geometryId = geometry.id;
  36042. serializationObject.geometryId = geometryId;
  36043. if (!mesh.getScene().getGeometryByID(geometryId)) {
  36044. // 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
  36045. serializeGeometry(geometry, serializationScene.geometries);
  36046. }
  36047. // SubMeshes
  36048. serializationObject.subMeshes = [];
  36049. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  36050. var subMesh = mesh.subMeshes[subIndex];
  36051. serializationObject.subMeshes.push({
  36052. materialIndex: subMesh.materialIndex,
  36053. verticesStart: subMesh.verticesStart,
  36054. verticesCount: subMesh.verticesCount,
  36055. indexStart: subMesh.indexStart,
  36056. indexCount: subMesh.indexCount
  36057. });
  36058. }
  36059. }
  36060. // Material
  36061. if (mesh.material) {
  36062. serializationObject.materialId = mesh.material.id;
  36063. }
  36064. else {
  36065. mesh.material = null;
  36066. }
  36067. // Skeleton
  36068. if (mesh.skeleton) {
  36069. serializationObject.skeletonId = mesh.skeleton.id;
  36070. }
  36071. // Physics
  36072. //TODO implement correct serialization for physics impostors.
  36073. if (mesh.getPhysicsImpostor()) {
  36074. serializationObject.physicsMass = mesh.getPhysicsMass();
  36075. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  36076. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  36077. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  36078. }
  36079. // Instances
  36080. serializationObject.instances = [];
  36081. for (var index = 0; index < mesh.instances.length; index++) {
  36082. var instance = mesh.instances[index];
  36083. var serializationInstance = {
  36084. name: instance.name,
  36085. position: instance.position.asArray(),
  36086. scaling: instance.scaling.asArray()
  36087. };
  36088. if (instance.rotationQuaternion) {
  36089. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  36090. }
  36091. else if (instance.rotation) {
  36092. serializationInstance.rotation = instance.rotation.asArray();
  36093. }
  36094. serializationObject.instances.push(serializationInstance);
  36095. // Animations
  36096. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  36097. serializationInstance.ranges = instance.serializeAnimationRanges();
  36098. }
  36099. // Animations
  36100. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  36101. serializationObject.ranges = mesh.serializeAnimationRanges();
  36102. // Layer mask
  36103. serializationObject.layerMask = mesh.layerMask;
  36104. return serializationObject;
  36105. };
  36106. var finalizeSingleMesh = function (mesh, serializationObject) {
  36107. //only works if the mesh is already loaded
  36108. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  36109. //serialize material
  36110. if (mesh.material) {
  36111. if (mesh.material instanceof BABYLON.StandardMaterial) {
  36112. serializationObject.materials = serializationObject.materials || [];
  36113. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  36114. serializationObject.materials.push(mesh.material.serialize());
  36115. }
  36116. }
  36117. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  36118. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  36119. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  36120. serializationObject.multiMaterials.push(mesh.material.serialize());
  36121. }
  36122. }
  36123. }
  36124. //serialize geometry
  36125. var geometry = mesh._geometry;
  36126. if (geometry) {
  36127. if (!serializationObject.geometries) {
  36128. serializationObject.geometries = {};
  36129. serializationObject.geometries.boxes = [];
  36130. serializationObject.geometries.spheres = [];
  36131. serializationObject.geometries.cylinders = [];
  36132. serializationObject.geometries.toruses = [];
  36133. serializationObject.geometries.grounds = [];
  36134. serializationObject.geometries.planes = [];
  36135. serializationObject.geometries.torusKnots = [];
  36136. serializationObject.geometries.vertexData = [];
  36137. }
  36138. serializeGeometry(geometry, serializationObject.geometries);
  36139. }
  36140. // Skeletons
  36141. if (mesh.skeleton) {
  36142. serializationObject.skeletons = serializationObject.skeletons || [];
  36143. serializationObject.skeletons.push(mesh.skeleton.serialize());
  36144. }
  36145. //serialize the actual mesh
  36146. serializationObject.meshes = serializationObject.meshes || [];
  36147. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  36148. }
  36149. };
  36150. var SceneSerializer = (function () {
  36151. function SceneSerializer() {
  36152. }
  36153. SceneSerializer.ClearCache = function () {
  36154. serializedGeometries = [];
  36155. };
  36156. SceneSerializer.Serialize = function (scene) {
  36157. var serializationObject = {};
  36158. // Scene
  36159. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  36160. serializationObject.autoClear = scene.autoClear;
  36161. serializationObject.clearColor = scene.clearColor.asArray();
  36162. serializationObject.ambientColor = scene.ambientColor.asArray();
  36163. serializationObject.gravity = scene.gravity.asArray();
  36164. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  36165. serializationObject.workerCollisions = scene.workerCollisions;
  36166. // Fog
  36167. if (scene.fogMode && scene.fogMode !== 0) {
  36168. serializationObject.fogMode = scene.fogMode;
  36169. serializationObject.fogColor = scene.fogColor.asArray();
  36170. serializationObject.fogStart = scene.fogStart;
  36171. serializationObject.fogEnd = scene.fogEnd;
  36172. serializationObject.fogDensity = scene.fogDensity;
  36173. }
  36174. //Physics
  36175. if (scene.isPhysicsEnabled()) {
  36176. serializationObject.physicsEnabled = true;
  36177. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  36178. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  36179. }
  36180. // Lights
  36181. serializationObject.lights = [];
  36182. var index;
  36183. var light;
  36184. for (index = 0; index < scene.lights.length; index++) {
  36185. light = scene.lights[index];
  36186. serializationObject.lights.push(light.serialize());
  36187. }
  36188. // Cameras
  36189. serializationObject.cameras = [];
  36190. for (index = 0; index < scene.cameras.length; index++) {
  36191. var camera = scene.cameras[index];
  36192. serializationObject.cameras.push(camera.serialize());
  36193. }
  36194. if (scene.activeCamera) {
  36195. serializationObject.activeCameraID = scene.activeCamera.id;
  36196. }
  36197. // Animations
  36198. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  36199. // Materials
  36200. serializationObject.materials = [];
  36201. serializationObject.multiMaterials = [];
  36202. var material;
  36203. for (index = 0; index < scene.materials.length; index++) {
  36204. material = scene.materials[index];
  36205. serializationObject.materials.push(material.serialize());
  36206. }
  36207. // MultiMaterials
  36208. serializationObject.multiMaterials = [];
  36209. for (index = 0; index < scene.multiMaterials.length; index++) {
  36210. var multiMaterial = scene.multiMaterials[index];
  36211. serializationObject.multiMaterials.push(multiMaterial.serialize());
  36212. }
  36213. // Skeletons
  36214. serializationObject.skeletons = [];
  36215. for (index = 0; index < scene.skeletons.length; index++) {
  36216. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  36217. }
  36218. // Geometries
  36219. serializationObject.geometries = {};
  36220. serializationObject.geometries.boxes = [];
  36221. serializationObject.geometries.spheres = [];
  36222. serializationObject.geometries.cylinders = [];
  36223. serializationObject.geometries.toruses = [];
  36224. serializationObject.geometries.grounds = [];
  36225. serializationObject.geometries.planes = [];
  36226. serializationObject.geometries.torusKnots = [];
  36227. serializationObject.geometries.vertexData = [];
  36228. serializedGeometries = [];
  36229. var geometries = scene.getGeometries();
  36230. for (index = 0; index < geometries.length; index++) {
  36231. var geometry = geometries[index];
  36232. if (geometry.isReady()) {
  36233. serializeGeometry(geometry, serializationObject.geometries);
  36234. }
  36235. }
  36236. // Meshes
  36237. serializationObject.meshes = [];
  36238. for (index = 0; index < scene.meshes.length; index++) {
  36239. var abstractMesh = scene.meshes[index];
  36240. if (abstractMesh instanceof BABYLON.Mesh) {
  36241. var mesh = abstractMesh;
  36242. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  36243. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  36244. }
  36245. }
  36246. }
  36247. // Particles Systems
  36248. serializationObject.particleSystems = [];
  36249. for (index = 0; index < scene.particleSystems.length; index++) {
  36250. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  36251. }
  36252. // Lens flares
  36253. serializationObject.lensFlareSystems = [];
  36254. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  36255. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  36256. }
  36257. // Shadows
  36258. serializationObject.shadowGenerators = [];
  36259. for (index = 0; index < scene.lights.length; index++) {
  36260. light = scene.lights[index];
  36261. if (light.getShadowGenerator()) {
  36262. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  36263. }
  36264. }
  36265. return serializationObject;
  36266. };
  36267. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  36268. if (withParents === void 0) { withParents = false; }
  36269. if (withChildren === void 0) { withChildren = false; }
  36270. var serializationObject = {};
  36271. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  36272. if (withParents || withChildren) {
  36273. //deliberate for loop! not for each, appended should be processed as well.
  36274. for (var i = 0; i < toSerialize.length; ++i) {
  36275. if (withChildren) {
  36276. toSerialize[i].getDescendants().forEach(function (node) {
  36277. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  36278. toSerialize.push(node);
  36279. }
  36280. });
  36281. }
  36282. //make sure the array doesn't contain the object already
  36283. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  36284. toSerialize.push(toSerialize[i].parent);
  36285. }
  36286. }
  36287. }
  36288. toSerialize.forEach(function (mesh) {
  36289. finalizeSingleMesh(mesh, serializationObject);
  36290. });
  36291. return serializationObject;
  36292. };
  36293. return SceneSerializer;
  36294. })();
  36295. BABYLON.SceneSerializer = SceneSerializer;
  36296. })(BABYLON || (BABYLON = {}));
  36297. var BABYLON;
  36298. (function (BABYLON) {
  36299. // Unique ID when we import meshes from Babylon to CSG
  36300. var currentCSGMeshId = 0;
  36301. // # class Vertex
  36302. // Represents a vertex of a polygon. Use your own vertex class instead of this
  36303. // one to provide additional features like texture coordinates and vertex
  36304. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  36305. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  36306. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  36307. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  36308. // is not used anywhere else.
  36309. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  36310. var Vertex = (function () {
  36311. function Vertex(pos, normal, uv) {
  36312. this.pos = pos;
  36313. this.normal = normal;
  36314. this.uv = uv;
  36315. }
  36316. Vertex.prototype.clone = function () {
  36317. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  36318. };
  36319. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  36320. // orientation of a polygon is flipped.
  36321. Vertex.prototype.flip = function () {
  36322. this.normal = this.normal.scale(-1);
  36323. };
  36324. // Create a new vertex between this vertex and `other` by linearly
  36325. // interpolating all properties using a parameter of `t`. Subclasses should
  36326. // override this to interpolate additional properties.
  36327. Vertex.prototype.interpolate = function (other, t) {
  36328. 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));
  36329. };
  36330. return Vertex;
  36331. })();
  36332. // # class Plane
  36333. // Represents a plane in 3D space.
  36334. var Plane = (function () {
  36335. function Plane(normal, w) {
  36336. this.normal = normal;
  36337. this.w = w;
  36338. }
  36339. Plane.FromPoints = function (a, b, c) {
  36340. var v0 = c.subtract(a);
  36341. var v1 = b.subtract(a);
  36342. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  36343. return null;
  36344. }
  36345. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  36346. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  36347. };
  36348. Plane.prototype.clone = function () {
  36349. return new Plane(this.normal.clone(), this.w);
  36350. };
  36351. Plane.prototype.flip = function () {
  36352. this.normal.scaleInPlace(-1);
  36353. this.w = -this.w;
  36354. };
  36355. // Split `polygon` by this plane if needed, then put the polygon or polygon
  36356. // fragments in the appropriate lists. Coplanar polygons go into either
  36357. // `coplanarFront` or `coplanarBack` depending on their orientation with
  36358. // respect to this plane. Polygons in front or in back of this plane go into
  36359. // either `front` or `back`.
  36360. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  36361. var COPLANAR = 0;
  36362. var FRONT = 1;
  36363. var BACK = 2;
  36364. var SPANNING = 3;
  36365. // Classify each point as well as the entire polygon into one of the above
  36366. // four classes.
  36367. var polygonType = 0;
  36368. var types = [];
  36369. var i;
  36370. var t;
  36371. for (i = 0; i < polygon.vertices.length; i++) {
  36372. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  36373. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  36374. polygonType |= type;
  36375. types.push(type);
  36376. }
  36377. // Put the polygon in the correct list, splitting it when necessary.
  36378. switch (polygonType) {
  36379. case COPLANAR:
  36380. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  36381. break;
  36382. case FRONT:
  36383. front.push(polygon);
  36384. break;
  36385. case BACK:
  36386. back.push(polygon);
  36387. break;
  36388. case SPANNING:
  36389. var f = [], b = [];
  36390. for (i = 0; i < polygon.vertices.length; i++) {
  36391. var j = (i + 1) % polygon.vertices.length;
  36392. var ti = types[i], tj = types[j];
  36393. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  36394. if (ti !== BACK)
  36395. f.push(vi);
  36396. if (ti !== FRONT)
  36397. b.push(ti !== BACK ? vi.clone() : vi);
  36398. if ((ti | tj) === SPANNING) {
  36399. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  36400. var v = vi.interpolate(vj, t);
  36401. f.push(v);
  36402. b.push(v.clone());
  36403. }
  36404. }
  36405. var poly;
  36406. if (f.length >= 3) {
  36407. poly = new Polygon(f, polygon.shared);
  36408. if (poly.plane)
  36409. front.push(poly);
  36410. }
  36411. if (b.length >= 3) {
  36412. poly = new Polygon(b, polygon.shared);
  36413. if (poly.plane)
  36414. back.push(poly);
  36415. }
  36416. break;
  36417. }
  36418. };
  36419. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  36420. // point is on the plane.
  36421. Plane.EPSILON = 1e-5;
  36422. return Plane;
  36423. })();
  36424. // # class Polygon
  36425. // Represents a convex polygon. The vertices used to initialize a polygon must
  36426. // be coplanar and form a convex loop.
  36427. //
  36428. // Each convex polygon has a `shared` property, which is shared between all
  36429. // polygons that are clones of each other or were split from the same polygon.
  36430. // This can be used to define per-polygon properties (such as surface color).
  36431. var Polygon = (function () {
  36432. function Polygon(vertices, shared) {
  36433. this.vertices = vertices;
  36434. this.shared = shared;
  36435. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  36436. }
  36437. Polygon.prototype.clone = function () {
  36438. var vertices = this.vertices.map(function (v) { return v.clone(); });
  36439. return new Polygon(vertices, this.shared);
  36440. };
  36441. Polygon.prototype.flip = function () {
  36442. this.vertices.reverse().map(function (v) { v.flip(); });
  36443. this.plane.flip();
  36444. };
  36445. return Polygon;
  36446. })();
  36447. // # class Node
  36448. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  36449. // by picking a polygon to split along. That polygon (and all other coplanar
  36450. // polygons) are added directly to that node and the other polygons are added to
  36451. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  36452. // no distinction between internal and leaf nodes.
  36453. var Node = (function () {
  36454. function Node(polygons) {
  36455. this.plane = null;
  36456. this.front = null;
  36457. this.back = null;
  36458. this.polygons = [];
  36459. if (polygons) {
  36460. this.build(polygons);
  36461. }
  36462. }
  36463. Node.prototype.clone = function () {
  36464. var node = new Node();
  36465. node.plane = this.plane && this.plane.clone();
  36466. node.front = this.front && this.front.clone();
  36467. node.back = this.back && this.back.clone();
  36468. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  36469. return node;
  36470. };
  36471. // Convert solid space to empty space and empty space to solid space.
  36472. Node.prototype.invert = function () {
  36473. for (var i = 0; i < this.polygons.length; i++) {
  36474. this.polygons[i].flip();
  36475. }
  36476. if (this.plane) {
  36477. this.plane.flip();
  36478. }
  36479. if (this.front) {
  36480. this.front.invert();
  36481. }
  36482. if (this.back) {
  36483. this.back.invert();
  36484. }
  36485. var temp = this.front;
  36486. this.front = this.back;
  36487. this.back = temp;
  36488. };
  36489. // Recursively remove all polygons in `polygons` that are inside this BSP
  36490. // tree.
  36491. Node.prototype.clipPolygons = function (polygons) {
  36492. if (!this.plane)
  36493. return polygons.slice();
  36494. var front = [], back = [];
  36495. for (var i = 0; i < polygons.length; i++) {
  36496. this.plane.splitPolygon(polygons[i], front, back, front, back);
  36497. }
  36498. if (this.front) {
  36499. front = this.front.clipPolygons(front);
  36500. }
  36501. if (this.back) {
  36502. back = this.back.clipPolygons(back);
  36503. }
  36504. else {
  36505. back = [];
  36506. }
  36507. return front.concat(back);
  36508. };
  36509. // Remove all polygons in this BSP tree that are inside the other BSP tree
  36510. // `bsp`.
  36511. Node.prototype.clipTo = function (bsp) {
  36512. this.polygons = bsp.clipPolygons(this.polygons);
  36513. if (this.front)
  36514. this.front.clipTo(bsp);
  36515. if (this.back)
  36516. this.back.clipTo(bsp);
  36517. };
  36518. // Return a list of all polygons in this BSP tree.
  36519. Node.prototype.allPolygons = function () {
  36520. var polygons = this.polygons.slice();
  36521. if (this.front)
  36522. polygons = polygons.concat(this.front.allPolygons());
  36523. if (this.back)
  36524. polygons = polygons.concat(this.back.allPolygons());
  36525. return polygons;
  36526. };
  36527. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  36528. // new polygons are filtered down to the bottom of the tree and become new
  36529. // nodes there. Each set of polygons is partitioned using the first polygon
  36530. // (no heuristic is used to pick a good split).
  36531. Node.prototype.build = function (polygons) {
  36532. if (!polygons.length)
  36533. return;
  36534. if (!this.plane)
  36535. this.plane = polygons[0].plane.clone();
  36536. var front = [], back = [];
  36537. for (var i = 0; i < polygons.length; i++) {
  36538. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  36539. }
  36540. if (front.length) {
  36541. if (!this.front)
  36542. this.front = new Node();
  36543. this.front.build(front);
  36544. }
  36545. if (back.length) {
  36546. if (!this.back)
  36547. this.back = new Node();
  36548. this.back.build(back);
  36549. }
  36550. };
  36551. return Node;
  36552. })();
  36553. var CSG = (function () {
  36554. function CSG() {
  36555. this.polygons = new Array();
  36556. }
  36557. // Convert BABYLON.Mesh to BABYLON.CSG
  36558. CSG.FromMesh = function (mesh) {
  36559. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  36560. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  36561. if (mesh instanceof BABYLON.Mesh) {
  36562. mesh.computeWorldMatrix(true);
  36563. matrix = mesh.getWorldMatrix();
  36564. meshPosition = mesh.position.clone();
  36565. meshRotation = mesh.rotation.clone();
  36566. if (mesh.rotationQuaternion) {
  36567. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  36568. }
  36569. meshScaling = mesh.scaling.clone();
  36570. }
  36571. else {
  36572. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  36573. }
  36574. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36575. var subMeshes = mesh.subMeshes;
  36576. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  36577. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  36578. vertices = [];
  36579. for (var j = 0; j < 3; j++) {
  36580. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  36581. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  36582. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  36583. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  36584. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  36585. vertex = new Vertex(position, normal, uv);
  36586. vertices.push(vertex);
  36587. }
  36588. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  36589. // To handle the case of degenerated triangle
  36590. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  36591. if (polygon.plane)
  36592. polygons.push(polygon);
  36593. }
  36594. }
  36595. var csg = CSG.FromPolygons(polygons);
  36596. csg.matrix = matrix;
  36597. csg.position = meshPosition;
  36598. csg.rotation = meshRotation;
  36599. csg.scaling = meshScaling;
  36600. csg.rotationQuaternion = meshRotationQuaternion;
  36601. currentCSGMeshId++;
  36602. return csg;
  36603. };
  36604. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  36605. CSG.FromPolygons = function (polygons) {
  36606. var csg = new CSG();
  36607. csg.polygons = polygons;
  36608. return csg;
  36609. };
  36610. CSG.prototype.clone = function () {
  36611. var csg = new CSG();
  36612. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  36613. csg.copyTransformAttributes(this);
  36614. return csg;
  36615. };
  36616. CSG.prototype.toPolygons = function () {
  36617. return this.polygons;
  36618. };
  36619. CSG.prototype.union = function (csg) {
  36620. var a = new Node(this.clone().polygons);
  36621. var b = new Node(csg.clone().polygons);
  36622. a.clipTo(b);
  36623. b.clipTo(a);
  36624. b.invert();
  36625. b.clipTo(a);
  36626. b.invert();
  36627. a.build(b.allPolygons());
  36628. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  36629. };
  36630. CSG.prototype.unionInPlace = function (csg) {
  36631. var a = new Node(this.polygons);
  36632. var b = new Node(csg.polygons);
  36633. a.clipTo(b);
  36634. b.clipTo(a);
  36635. b.invert();
  36636. b.clipTo(a);
  36637. b.invert();
  36638. a.build(b.allPolygons());
  36639. this.polygons = a.allPolygons();
  36640. };
  36641. CSG.prototype.subtract = function (csg) {
  36642. var a = new Node(this.clone().polygons);
  36643. var b = new Node(csg.clone().polygons);
  36644. a.invert();
  36645. a.clipTo(b);
  36646. b.clipTo(a);
  36647. b.invert();
  36648. b.clipTo(a);
  36649. b.invert();
  36650. a.build(b.allPolygons());
  36651. a.invert();
  36652. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  36653. };
  36654. CSG.prototype.subtractInPlace = function (csg) {
  36655. var a = new Node(this.polygons);
  36656. var b = new Node(csg.polygons);
  36657. a.invert();
  36658. a.clipTo(b);
  36659. b.clipTo(a);
  36660. b.invert();
  36661. b.clipTo(a);
  36662. b.invert();
  36663. a.build(b.allPolygons());
  36664. a.invert();
  36665. this.polygons = a.allPolygons();
  36666. };
  36667. CSG.prototype.intersect = function (csg) {
  36668. var a = new Node(this.clone().polygons);
  36669. var b = new Node(csg.clone().polygons);
  36670. a.invert();
  36671. b.clipTo(a);
  36672. b.invert();
  36673. a.clipTo(b);
  36674. b.clipTo(a);
  36675. a.build(b.allPolygons());
  36676. a.invert();
  36677. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  36678. };
  36679. CSG.prototype.intersectInPlace = function (csg) {
  36680. var a = new Node(this.polygons);
  36681. var b = new Node(csg.polygons);
  36682. a.invert();
  36683. b.clipTo(a);
  36684. b.invert();
  36685. a.clipTo(b);
  36686. b.clipTo(a);
  36687. a.build(b.allPolygons());
  36688. a.invert();
  36689. this.polygons = a.allPolygons();
  36690. };
  36691. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  36692. // not modified.
  36693. CSG.prototype.inverse = function () {
  36694. var csg = this.clone();
  36695. csg.inverseInPlace();
  36696. return csg;
  36697. };
  36698. CSG.prototype.inverseInPlace = function () {
  36699. this.polygons.map(function (p) { p.flip(); });
  36700. };
  36701. // This is used to keep meshes transformations so they can be restored
  36702. // when we build back a Babylon Mesh
  36703. // NB : All CSG operations are performed in world coordinates
  36704. CSG.prototype.copyTransformAttributes = function (csg) {
  36705. this.matrix = csg.matrix;
  36706. this.position = csg.position;
  36707. this.rotation = csg.rotation;
  36708. this.scaling = csg.scaling;
  36709. this.rotationQuaternion = csg.rotationQuaternion;
  36710. return this;
  36711. };
  36712. // Build Raw mesh from CSG
  36713. // Coordinates here are in world space
  36714. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  36715. var matrix = this.matrix.clone();
  36716. matrix.invert();
  36717. 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;
  36718. if (keepSubMeshes) {
  36719. // Sort Polygons, since subMeshes are indices range
  36720. polygons.sort(function (a, b) {
  36721. if (a.shared.meshId === b.shared.meshId) {
  36722. return a.shared.subMeshId - b.shared.subMeshId;
  36723. }
  36724. else {
  36725. return a.shared.meshId - b.shared.meshId;
  36726. }
  36727. });
  36728. }
  36729. for (var i = 0, il = polygons.length; i < il; i++) {
  36730. polygon = polygons[i];
  36731. // Building SubMeshes
  36732. if (!subMesh_dict[polygon.shared.meshId]) {
  36733. subMesh_dict[polygon.shared.meshId] = {};
  36734. }
  36735. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  36736. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  36737. indexStart: +Infinity,
  36738. indexEnd: -Infinity,
  36739. materialIndex: polygon.shared.materialIndex
  36740. };
  36741. }
  36742. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  36743. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  36744. polygonIndices[0] = 0;
  36745. polygonIndices[1] = j - 1;
  36746. polygonIndices[2] = j;
  36747. for (var k = 0; k < 3; k++) {
  36748. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  36749. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  36750. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  36751. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  36752. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  36753. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  36754. // Check if 2 points can be merged
  36755. if (!(typeof vertex_idx !== 'undefined' &&
  36756. normals[vertex_idx * 3] === localNormal.x &&
  36757. normals[vertex_idx * 3 + 1] === localNormal.y &&
  36758. normals[vertex_idx * 3 + 2] === localNormal.z &&
  36759. uvs[vertex_idx * 2] === uv.x &&
  36760. uvs[vertex_idx * 2 + 1] === uv.y)) {
  36761. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  36762. uvs.push(uv.x, uv.y);
  36763. normals.push(normal.x, normal.y, normal.z);
  36764. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  36765. }
  36766. indices.push(vertex_idx);
  36767. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  36768. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  36769. currentIndex++;
  36770. }
  36771. }
  36772. }
  36773. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  36774. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  36775. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  36776. mesh.setIndices(indices);
  36777. if (keepSubMeshes) {
  36778. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  36779. var materialIndexOffset = 0, materialMaxIndex;
  36780. mesh.subMeshes = new Array();
  36781. for (var m in subMesh_dict) {
  36782. materialMaxIndex = -1;
  36783. for (var sm in subMesh_dict[m]) {
  36784. subMesh_obj = subMesh_dict[m][sm];
  36785. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  36786. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  36787. }
  36788. materialIndexOffset += ++materialMaxIndex;
  36789. }
  36790. }
  36791. return mesh;
  36792. };
  36793. // Build Mesh from CSG taking material and transforms into account
  36794. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  36795. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  36796. mesh.material = material;
  36797. mesh.position.copyFrom(this.position);
  36798. mesh.rotation.copyFrom(this.rotation);
  36799. if (this.rotationQuaternion) {
  36800. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  36801. }
  36802. mesh.scaling.copyFrom(this.scaling);
  36803. mesh.computeWorldMatrix(true);
  36804. return mesh;
  36805. };
  36806. return CSG;
  36807. })();
  36808. BABYLON.CSG = CSG;
  36809. })(BABYLON || (BABYLON = {}));
  36810. var BABYLON;
  36811. (function (BABYLON) {
  36812. var VRDistortionCorrectionPostProcess = (function (_super) {
  36813. __extends(VRDistortionCorrectionPostProcess, _super);
  36814. //ANY
  36815. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  36816. var _this = this;
  36817. _super.call(this, name, "vrDistortionCorrection", [
  36818. 'LensCenter',
  36819. 'Scale',
  36820. 'ScaleIn',
  36821. 'HmdWarpParam'
  36822. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  36823. this._isRightEye = isRightEye;
  36824. this._distortionFactors = vrMetrics.distortionK;
  36825. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  36826. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  36827. this.onSizeChanged = function () {
  36828. _this.aspectRatio = _this.width * .5 / _this.height;
  36829. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  36830. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  36831. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  36832. };
  36833. this.onApply = function (effect) {
  36834. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  36835. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  36836. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  36837. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  36838. };
  36839. }
  36840. return VRDistortionCorrectionPostProcess;
  36841. })(BABYLON.PostProcess);
  36842. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  36843. })(BABYLON || (BABYLON = {}));
  36844. // Mainly based on these 2 articles :
  36845. // 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
  36846. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  36847. var BABYLON;
  36848. (function (BABYLON) {
  36849. (function (JoystickAxis) {
  36850. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  36851. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  36852. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  36853. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  36854. var JoystickAxis = BABYLON.JoystickAxis;
  36855. var VirtualJoystick = (function () {
  36856. function VirtualJoystick(leftJoystick) {
  36857. var _this = this;
  36858. if (leftJoystick) {
  36859. this._leftJoystick = true;
  36860. }
  36861. else {
  36862. this._leftJoystick = false;
  36863. }
  36864. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  36865. VirtualJoystick._globalJoystickIndex++;
  36866. // By default left & right arrow keys are moving the X
  36867. // and up & down keys are moving the Y
  36868. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  36869. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  36870. this.reverseLeftRight = false;
  36871. this.reverseUpDown = false;
  36872. // collections of pointers
  36873. this._touches = new BABYLON.SmartCollection();
  36874. this.deltaPosition = BABYLON.Vector3.Zero();
  36875. this._joystickSensibility = 25;
  36876. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  36877. this._rotationSpeed = 25;
  36878. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  36879. this._rotateOnAxisRelativeToMesh = false;
  36880. this._onResize = function (evt) {
  36881. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  36882. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  36883. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  36884. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  36885. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  36886. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  36887. };
  36888. // injecting a canvas element on top of the canvas 3D game
  36889. if (!VirtualJoystick.vjCanvas) {
  36890. window.addEventListener("resize", this._onResize, false);
  36891. VirtualJoystick.vjCanvas = document.createElement("canvas");
  36892. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  36893. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  36894. VirtualJoystick.vjCanvas.width = window.innerWidth;
  36895. VirtualJoystick.vjCanvas.height = window.innerHeight;
  36896. VirtualJoystick.vjCanvas.style.width = "100%";
  36897. VirtualJoystick.vjCanvas.style.height = "100%";
  36898. VirtualJoystick.vjCanvas.style.position = "absolute";
  36899. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  36900. VirtualJoystick.vjCanvas.style.top = "0px";
  36901. VirtualJoystick.vjCanvas.style.left = "0px";
  36902. VirtualJoystick.vjCanvas.style.zIndex = "5";
  36903. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  36904. // Support for jQuery PEP polyfill
  36905. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  36906. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  36907. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  36908. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  36909. document.body.appendChild(VirtualJoystick.vjCanvas);
  36910. }
  36911. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  36912. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  36913. this.pressed = false;
  36914. // default joystick color
  36915. this._joystickColor = "cyan";
  36916. this._joystickPointerID = -1;
  36917. // current joystick position
  36918. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  36919. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  36920. // origin joystick position
  36921. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  36922. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  36923. this._onPointerDownHandlerRef = function (evt) {
  36924. _this._onPointerDown(evt);
  36925. };
  36926. this._onPointerMoveHandlerRef = function (evt) {
  36927. _this._onPointerMove(evt);
  36928. };
  36929. this._onPointerOutHandlerRef = function (evt) {
  36930. _this._onPointerUp(evt);
  36931. };
  36932. this._onPointerUpHandlerRef = function (evt) {
  36933. _this._onPointerUp(evt);
  36934. };
  36935. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  36936. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  36937. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  36938. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  36939. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  36940. evt.preventDefault(); // Disables system menu
  36941. }, false);
  36942. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  36943. }
  36944. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  36945. this._joystickSensibility = newJoystickSensibility;
  36946. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  36947. };
  36948. VirtualJoystick.prototype._onPointerDown = function (e) {
  36949. var positionOnScreenCondition;
  36950. e.preventDefault();
  36951. if (this._leftJoystick === true) {
  36952. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  36953. }
  36954. else {
  36955. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  36956. }
  36957. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  36958. // First contact will be dedicated to the virtual joystick
  36959. this._joystickPointerID = e.pointerId;
  36960. this._joystickPointerStartPos.x = e.clientX;
  36961. this._joystickPointerStartPos.y = e.clientY;
  36962. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  36963. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  36964. this._deltaJoystickVector.x = 0;
  36965. this._deltaJoystickVector.y = 0;
  36966. this.pressed = true;
  36967. this._touches.add(e.pointerId.toString(), e);
  36968. }
  36969. else {
  36970. // You can only trigger the action buttons with a joystick declared
  36971. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  36972. this._action();
  36973. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  36974. }
  36975. }
  36976. };
  36977. VirtualJoystick.prototype._onPointerMove = function (e) {
  36978. // If the current pointer is the one associated to the joystick (first touch contact)
  36979. if (this._joystickPointerID == e.pointerId) {
  36980. this._joystickPointerPos.x = e.clientX;
  36981. this._joystickPointerPos.y = e.clientY;
  36982. this._deltaJoystickVector = this._joystickPointerPos.clone();
  36983. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  36984. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  36985. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  36986. switch (this._axisTargetedByLeftAndRight) {
  36987. case JoystickAxis.X:
  36988. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  36989. break;
  36990. case JoystickAxis.Y:
  36991. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  36992. break;
  36993. case JoystickAxis.Z:
  36994. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  36995. break;
  36996. }
  36997. var directionUpDown = this.reverseUpDown ? 1 : -1;
  36998. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  36999. switch (this._axisTargetedByUpAndDown) {
  37000. case JoystickAxis.X:
  37001. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  37002. break;
  37003. case JoystickAxis.Y:
  37004. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  37005. break;
  37006. case JoystickAxis.Z:
  37007. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  37008. break;
  37009. }
  37010. }
  37011. else {
  37012. if (this._touches.item(e.pointerId.toString())) {
  37013. this._touches.item(e.pointerId.toString()).x = e.clientX;
  37014. this._touches.item(e.pointerId.toString()).y = e.clientY;
  37015. }
  37016. }
  37017. };
  37018. VirtualJoystick.prototype._onPointerUp = function (e) {
  37019. if (this._joystickPointerID == e.pointerId) {
  37020. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  37021. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  37022. this._joystickPointerID = -1;
  37023. this.pressed = false;
  37024. }
  37025. else {
  37026. var touch = this._touches.item(e.pointerId.toString());
  37027. if (touch) {
  37028. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  37029. }
  37030. }
  37031. this._deltaJoystickVector.x = 0;
  37032. this._deltaJoystickVector.y = 0;
  37033. this._touches.remove(e.pointerId.toString());
  37034. };
  37035. /**
  37036. * Change the color of the virtual joystick
  37037. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  37038. */
  37039. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  37040. this._joystickColor = newColor;
  37041. };
  37042. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  37043. this._action = action;
  37044. };
  37045. // Define which axis you'd like to control for left & right
  37046. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  37047. switch (axis) {
  37048. case JoystickAxis.X:
  37049. case JoystickAxis.Y:
  37050. case JoystickAxis.Z:
  37051. this._axisTargetedByLeftAndRight = axis;
  37052. break;
  37053. default:
  37054. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  37055. break;
  37056. }
  37057. };
  37058. // Define which axis you'd like to control for up & down
  37059. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  37060. switch (axis) {
  37061. case JoystickAxis.X:
  37062. case JoystickAxis.Y:
  37063. case JoystickAxis.Z:
  37064. this._axisTargetedByUpAndDown = axis;
  37065. break;
  37066. default:
  37067. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  37068. break;
  37069. }
  37070. };
  37071. VirtualJoystick.prototype._clearCanvas = function () {
  37072. if (this._leftJoystick) {
  37073. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  37074. }
  37075. else {
  37076. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  37077. }
  37078. };
  37079. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  37080. var _this = this;
  37081. if (this.pressed) {
  37082. this._touches.forEach(function (touch) {
  37083. if (touch.pointerId === _this._joystickPointerID) {
  37084. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  37085. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  37086. VirtualJoystick.vjCanvasContext.beginPath();
  37087. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  37088. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  37089. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  37090. VirtualJoystick.vjCanvasContext.stroke();
  37091. VirtualJoystick.vjCanvasContext.closePath();
  37092. VirtualJoystick.vjCanvasContext.beginPath();
  37093. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  37094. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  37095. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  37096. VirtualJoystick.vjCanvasContext.stroke();
  37097. VirtualJoystick.vjCanvasContext.closePath();
  37098. VirtualJoystick.vjCanvasContext.beginPath();
  37099. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  37100. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  37101. VirtualJoystick.vjCanvasContext.stroke();
  37102. VirtualJoystick.vjCanvasContext.closePath();
  37103. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  37104. }
  37105. else {
  37106. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  37107. VirtualJoystick.vjCanvasContext.beginPath();
  37108. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  37109. VirtualJoystick.vjCanvasContext.beginPath();
  37110. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  37111. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  37112. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  37113. VirtualJoystick.vjCanvasContext.stroke();
  37114. VirtualJoystick.vjCanvasContext.closePath();
  37115. touch.prevX = touch.x;
  37116. touch.prevY = touch.y;
  37117. }
  37118. ;
  37119. });
  37120. }
  37121. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  37122. };
  37123. VirtualJoystick.prototype.releaseCanvas = function () {
  37124. if (VirtualJoystick.vjCanvas) {
  37125. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  37126. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  37127. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  37128. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  37129. window.removeEventListener("resize", this._onResize);
  37130. document.body.removeChild(VirtualJoystick.vjCanvas);
  37131. VirtualJoystick.vjCanvas = null;
  37132. }
  37133. };
  37134. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  37135. VirtualJoystick._globalJoystickIndex = 0;
  37136. return VirtualJoystick;
  37137. })();
  37138. BABYLON.VirtualJoystick = VirtualJoystick;
  37139. })(BABYLON || (BABYLON = {}));
  37140. var BABYLON;
  37141. (function (BABYLON) {
  37142. // We're mainly based on the logic defined into the FreeCamera code
  37143. var VirtualJoysticksCamera = (function (_super) {
  37144. __extends(VirtualJoysticksCamera, _super);
  37145. function VirtualJoysticksCamera(name, position, scene) {
  37146. _super.call(this, name, position, scene);
  37147. this.inputs.addVirtualJoystick();
  37148. }
  37149. return VirtualJoysticksCamera;
  37150. })(BABYLON.FreeCamera);
  37151. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  37152. })(BABYLON || (BABYLON = {}));
  37153. var BABYLON;
  37154. (function (BABYLON) {
  37155. var AnaglyphPostProcess = (function (_super) {
  37156. __extends(AnaglyphPostProcess, _super);
  37157. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  37158. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  37159. }
  37160. return AnaglyphPostProcess;
  37161. })(BABYLON.PostProcess);
  37162. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  37163. })(BABYLON || (BABYLON = {}));
  37164. var BABYLON;
  37165. (function (BABYLON) {
  37166. var OutlineRenderer = (function () {
  37167. function OutlineRenderer(scene) {
  37168. this._scene = scene;
  37169. }
  37170. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  37171. var _this = this;
  37172. if (useOverlay === void 0) { useOverlay = false; }
  37173. var scene = this._scene;
  37174. var engine = this._scene.getEngine();
  37175. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  37176. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  37177. return;
  37178. }
  37179. var mesh = subMesh.getRenderingMesh();
  37180. var material = subMesh.getMaterial();
  37181. engine.enableEffect(this._effect);
  37182. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  37183. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  37184. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  37185. // Bones
  37186. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37187. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  37188. }
  37189. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  37190. // Alpha test
  37191. if (material && material.needAlphaTesting()) {
  37192. var alphaTexture = material.getAlphaTestTexture();
  37193. this._effect.setTexture("diffuseSampler", alphaTexture);
  37194. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  37195. }
  37196. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  37197. };
  37198. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  37199. var defines = [];
  37200. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  37201. var mesh = subMesh.getMesh();
  37202. var material = subMesh.getMaterial();
  37203. // Alpha test
  37204. if (material && material.needAlphaTesting()) {
  37205. defines.push("#define ALPHATEST");
  37206. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37207. attribs.push(BABYLON.VertexBuffer.UVKind);
  37208. defines.push("#define UV1");
  37209. }
  37210. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37211. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37212. defines.push("#define UV2");
  37213. }
  37214. }
  37215. // Bones
  37216. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37217. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37218. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37219. if (mesh.numBoneInfluencers > 4) {
  37220. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  37221. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  37222. }
  37223. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  37224. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  37225. }
  37226. else {
  37227. defines.push("#define NUM_BONE_INFLUENCERS 0");
  37228. }
  37229. // Instances
  37230. if (useInstances) {
  37231. defines.push("#define INSTANCES");
  37232. attribs.push("world0");
  37233. attribs.push("world1");
  37234. attribs.push("world2");
  37235. attribs.push("world3");
  37236. }
  37237. // Get correct effect
  37238. var join = defines.join("\n");
  37239. if (this._cachedDefines !== join) {
  37240. this._cachedDefines = join;
  37241. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  37242. }
  37243. return this._effect.isReady();
  37244. };
  37245. return OutlineRenderer;
  37246. })();
  37247. BABYLON.OutlineRenderer = OutlineRenderer;
  37248. })(BABYLON || (BABYLON = {}));
  37249. var BABYLON;
  37250. (function (BABYLON) {
  37251. var MeshAssetTask = (function () {
  37252. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  37253. this.name = name;
  37254. this.meshesNames = meshesNames;
  37255. this.rootUrl = rootUrl;
  37256. this.sceneFilename = sceneFilename;
  37257. this.isCompleted = false;
  37258. }
  37259. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37260. var _this = this;
  37261. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  37262. _this.loadedMeshes = meshes;
  37263. _this.loadedParticleSystems = particleSystems;
  37264. _this.loadedSkeletons = skeletons;
  37265. _this.isCompleted = true;
  37266. if (_this.onSuccess) {
  37267. _this.onSuccess(_this);
  37268. }
  37269. onSuccess();
  37270. }, null, function () {
  37271. if (_this.onError) {
  37272. _this.onError(_this);
  37273. }
  37274. onError();
  37275. });
  37276. };
  37277. return MeshAssetTask;
  37278. })();
  37279. BABYLON.MeshAssetTask = MeshAssetTask;
  37280. var TextFileAssetTask = (function () {
  37281. function TextFileAssetTask(name, url) {
  37282. this.name = name;
  37283. this.url = url;
  37284. this.isCompleted = false;
  37285. }
  37286. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37287. var _this = this;
  37288. BABYLON.Tools.LoadFile(this.url, function (data) {
  37289. _this.text = data;
  37290. _this.isCompleted = true;
  37291. if (_this.onSuccess) {
  37292. _this.onSuccess(_this);
  37293. }
  37294. onSuccess();
  37295. }, null, scene.database, false, function () {
  37296. if (_this.onError) {
  37297. _this.onError(_this);
  37298. }
  37299. onError();
  37300. });
  37301. };
  37302. return TextFileAssetTask;
  37303. })();
  37304. BABYLON.TextFileAssetTask = TextFileAssetTask;
  37305. var BinaryFileAssetTask = (function () {
  37306. function BinaryFileAssetTask(name, url) {
  37307. this.name = name;
  37308. this.url = url;
  37309. this.isCompleted = false;
  37310. }
  37311. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37312. var _this = this;
  37313. BABYLON.Tools.LoadFile(this.url, function (data) {
  37314. _this.data = data;
  37315. _this.isCompleted = true;
  37316. if (_this.onSuccess) {
  37317. _this.onSuccess(_this);
  37318. }
  37319. onSuccess();
  37320. }, null, scene.database, true, function () {
  37321. if (_this.onError) {
  37322. _this.onError(_this);
  37323. }
  37324. onError();
  37325. });
  37326. };
  37327. return BinaryFileAssetTask;
  37328. })();
  37329. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  37330. var ImageAssetTask = (function () {
  37331. function ImageAssetTask(name, url) {
  37332. this.name = name;
  37333. this.url = url;
  37334. this.isCompleted = false;
  37335. }
  37336. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37337. var _this = this;
  37338. var img = new Image();
  37339. img.onload = function () {
  37340. _this.image = img;
  37341. _this.isCompleted = true;
  37342. if (_this.onSuccess) {
  37343. _this.onSuccess(_this);
  37344. }
  37345. onSuccess();
  37346. };
  37347. img.onerror = function () {
  37348. if (_this.onError) {
  37349. _this.onError(_this);
  37350. }
  37351. onError();
  37352. };
  37353. img.src = this.url;
  37354. };
  37355. return ImageAssetTask;
  37356. })();
  37357. BABYLON.ImageAssetTask = ImageAssetTask;
  37358. var TextureAssetTask = (function () {
  37359. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  37360. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37361. this.name = name;
  37362. this.url = url;
  37363. this.noMipmap = noMipmap;
  37364. this.invertY = invertY;
  37365. this.samplingMode = samplingMode;
  37366. this.isCompleted = false;
  37367. }
  37368. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37369. var _this = this;
  37370. var onload = function () {
  37371. _this.isCompleted = true;
  37372. if (_this.onSuccess) {
  37373. _this.onSuccess(_this);
  37374. }
  37375. onSuccess();
  37376. };
  37377. var onerror = function () {
  37378. if (_this.onError) {
  37379. _this.onError(_this);
  37380. }
  37381. onError();
  37382. };
  37383. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  37384. };
  37385. return TextureAssetTask;
  37386. })();
  37387. BABYLON.TextureAssetTask = TextureAssetTask;
  37388. var AssetsManager = (function () {
  37389. function AssetsManager(scene) {
  37390. this._tasks = new Array();
  37391. this._waitingTasksCount = 0;
  37392. this.useDefaultLoadingScreen = true;
  37393. this._scene = scene;
  37394. }
  37395. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  37396. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  37397. this._tasks.push(task);
  37398. return task;
  37399. };
  37400. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  37401. var task = new TextFileAssetTask(taskName, url);
  37402. this._tasks.push(task);
  37403. return task;
  37404. };
  37405. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  37406. var task = new BinaryFileAssetTask(taskName, url);
  37407. this._tasks.push(task);
  37408. return task;
  37409. };
  37410. AssetsManager.prototype.addImageTask = function (taskName, url) {
  37411. var task = new ImageAssetTask(taskName, url);
  37412. this._tasks.push(task);
  37413. return task;
  37414. };
  37415. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  37416. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37417. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  37418. this._tasks.push(task);
  37419. return task;
  37420. };
  37421. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  37422. this._waitingTasksCount--;
  37423. if (this._waitingTasksCount === 0) {
  37424. if (this.onFinish) {
  37425. this.onFinish(this._tasks);
  37426. }
  37427. this._scene.getEngine().hideLoadingUI();
  37428. }
  37429. };
  37430. AssetsManager.prototype._runTask = function (task) {
  37431. var _this = this;
  37432. task.run(this._scene, function () {
  37433. if (_this.onTaskSuccess) {
  37434. _this.onTaskSuccess(task);
  37435. }
  37436. _this._decreaseWaitingTasksCount();
  37437. }, function () {
  37438. if (_this.onTaskError) {
  37439. _this.onTaskError(task);
  37440. }
  37441. _this._decreaseWaitingTasksCount();
  37442. });
  37443. };
  37444. AssetsManager.prototype.reset = function () {
  37445. this._tasks = new Array();
  37446. return this;
  37447. };
  37448. AssetsManager.prototype.load = function () {
  37449. this._waitingTasksCount = this._tasks.length;
  37450. if (this._waitingTasksCount === 0) {
  37451. if (this.onFinish) {
  37452. this.onFinish(this._tasks);
  37453. }
  37454. return this;
  37455. }
  37456. if (this.useDefaultLoadingScreen) {
  37457. this._scene.getEngine().displayLoadingUI();
  37458. }
  37459. for (var index = 0; index < this._tasks.length; index++) {
  37460. var task = this._tasks[index];
  37461. this._runTask(task);
  37462. }
  37463. return this;
  37464. };
  37465. return AssetsManager;
  37466. })();
  37467. BABYLON.AssetsManager = AssetsManager;
  37468. })(BABYLON || (BABYLON = {}));
  37469. var BABYLON;
  37470. (function (BABYLON) {
  37471. var VRCameraMetrics = (function () {
  37472. function VRCameraMetrics() {
  37473. this.compensateDistortion = true;
  37474. }
  37475. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  37476. get: function () {
  37477. return this.hResolution / (2 * this.vResolution);
  37478. },
  37479. enumerable: true,
  37480. configurable: true
  37481. });
  37482. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  37483. get: function () {
  37484. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  37485. },
  37486. enumerable: true,
  37487. configurable: true
  37488. });
  37489. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  37490. get: function () {
  37491. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  37492. var h = (4 * meters) / this.hScreenSize;
  37493. return BABYLON.Matrix.Translation(h, 0, 0);
  37494. },
  37495. enumerable: true,
  37496. configurable: true
  37497. });
  37498. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  37499. get: function () {
  37500. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  37501. var h = (4 * meters) / this.hScreenSize;
  37502. return BABYLON.Matrix.Translation(-h, 0, 0);
  37503. },
  37504. enumerable: true,
  37505. configurable: true
  37506. });
  37507. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  37508. get: function () {
  37509. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  37510. },
  37511. enumerable: true,
  37512. configurable: true
  37513. });
  37514. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  37515. get: function () {
  37516. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  37517. },
  37518. enumerable: true,
  37519. configurable: true
  37520. });
  37521. VRCameraMetrics.GetDefault = function () {
  37522. var result = new VRCameraMetrics();
  37523. result.hResolution = 1280;
  37524. result.vResolution = 800;
  37525. result.hScreenSize = 0.149759993;
  37526. result.vScreenSize = 0.0935999975;
  37527. result.vScreenCenter = 0.0467999987,
  37528. result.eyeToScreenDistance = 0.0410000011;
  37529. result.lensSeparationDistance = 0.0635000020;
  37530. result.interpupillaryDistance = 0.0640000030;
  37531. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  37532. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  37533. result.postProcessScaleFactor = 1.714605507808412;
  37534. result.lensCenterOffset = 0.151976421;
  37535. return result;
  37536. };
  37537. return VRCameraMetrics;
  37538. })();
  37539. BABYLON.VRCameraMetrics = VRCameraMetrics;
  37540. })(BABYLON || (BABYLON = {}));
  37541. var BABYLON;
  37542. (function (BABYLON) {
  37543. var VRDeviceOrientationFreeCamera = (function (_super) {
  37544. __extends(VRDeviceOrientationFreeCamera, _super);
  37545. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  37546. if (compensateDistortion === void 0) { compensateDistortion = true; }
  37547. _super.call(this, name, position, scene);
  37548. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  37549. metrics.compensateDistortion = compensateDistortion;
  37550. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  37551. this.inputs.addVRDeviceOrientation();
  37552. }
  37553. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  37554. return "VRDeviceOrientationFreeCamera";
  37555. };
  37556. return VRDeviceOrientationFreeCamera;
  37557. })(BABYLON.FreeCamera);
  37558. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  37559. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  37560. __extends(VRDeviceOrientationArcRotateCamera, _super);
  37561. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion) {
  37562. if (compensateDistortion === void 0) { compensateDistortion = true; }
  37563. _super.call(this, name, alpha, beta, radius, target, scene);
  37564. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  37565. metrics.compensateDistortion = compensateDistortion;
  37566. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  37567. this.inputs.addVRDeviceOrientation();
  37568. }
  37569. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  37570. return "VRDeviceOrientationArcRotateCamera";
  37571. };
  37572. return VRDeviceOrientationArcRotateCamera;
  37573. })(BABYLON.ArcRotateCamera);
  37574. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  37575. })(BABYLON || (BABYLON = {}));
  37576. var BABYLON;
  37577. (function (BABYLON) {
  37578. var WebVRFreeCamera = (function (_super) {
  37579. __extends(WebVRFreeCamera, _super);
  37580. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  37581. if (compensateDistortion === void 0) { compensateDistortion = true; }
  37582. _super.call(this, name, position, scene);
  37583. this._hmdDevice = null;
  37584. this._sensorDevice = null;
  37585. this._cacheState = null;
  37586. this._cacheQuaternion = new BABYLON.Quaternion();
  37587. this._cacheRotation = BABYLON.Vector3.Zero();
  37588. this._vrEnabled = false;
  37589. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  37590. metrics.compensateDistortion = compensateDistortion;
  37591. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  37592. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  37593. }
  37594. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  37595. var size = devices.length;
  37596. var i = 0;
  37597. // Reset devices.
  37598. this._sensorDevice = null;
  37599. this._hmdDevice = null;
  37600. // Search for a HmdDevice.
  37601. while (i < size && this._hmdDevice === null) {
  37602. if (devices[i] instanceof HMDVRDevice) {
  37603. this._hmdDevice = devices[i];
  37604. }
  37605. i++;
  37606. }
  37607. i = 0;
  37608. while (i < size && this._sensorDevice === null) {
  37609. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  37610. this._sensorDevice = devices[i];
  37611. }
  37612. i++;
  37613. }
  37614. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  37615. };
  37616. WebVRFreeCamera.prototype._checkInputs = function () {
  37617. if (this._vrEnabled) {
  37618. this._cacheState = this._sensorDevice.getState();
  37619. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  37620. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  37621. this.rotation.x = -this._cacheRotation.x;
  37622. this.rotation.y = -this._cacheRotation.y;
  37623. this.rotation.z = this._cacheRotation.z;
  37624. }
  37625. _super.prototype._checkInputs.call(this);
  37626. };
  37627. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  37628. _super.prototype.attachControl.call(this, element, noPreventDefault);
  37629. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  37630. if (navigator.getVRDevices) {
  37631. navigator.getVRDevices().then(this._getWebVRDevices);
  37632. }
  37633. else if (navigator.mozGetVRDevices) {
  37634. navigator.mozGetVRDevices(this._getWebVRDevices);
  37635. }
  37636. };
  37637. WebVRFreeCamera.prototype.detachControl = function (element) {
  37638. _super.prototype.detachControl.call(this, element);
  37639. this._vrEnabled = false;
  37640. };
  37641. WebVRFreeCamera.prototype.getTypeName = function () {
  37642. return "WebVRFreeCamera";
  37643. };
  37644. return WebVRFreeCamera;
  37645. })(BABYLON.FreeCamera);
  37646. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  37647. })(BABYLON || (BABYLON = {}));
  37648. var BABYLON;
  37649. (function (BABYLON) {
  37650. // Standard optimizations
  37651. var SceneOptimization = (function () {
  37652. function SceneOptimization(priority) {
  37653. if (priority === void 0) { priority = 0; }
  37654. this.priority = priority;
  37655. this.apply = function (scene) {
  37656. return true; // Return true if everything that can be done was applied
  37657. };
  37658. }
  37659. return SceneOptimization;
  37660. })();
  37661. BABYLON.SceneOptimization = SceneOptimization;
  37662. var TextureOptimization = (function (_super) {
  37663. __extends(TextureOptimization, _super);
  37664. function TextureOptimization(priority, maximumSize) {
  37665. var _this = this;
  37666. if (priority === void 0) { priority = 0; }
  37667. if (maximumSize === void 0) { maximumSize = 1024; }
  37668. _super.call(this, priority);
  37669. this.priority = priority;
  37670. this.maximumSize = maximumSize;
  37671. this.apply = function (scene) {
  37672. var allDone = true;
  37673. for (var index = 0; index < scene.textures.length; index++) {
  37674. var texture = scene.textures[index];
  37675. if (!texture.canRescale) {
  37676. continue;
  37677. }
  37678. var currentSize = texture.getSize();
  37679. var maxDimension = Math.max(currentSize.width, currentSize.height);
  37680. if (maxDimension > _this.maximumSize) {
  37681. texture.scale(0.5);
  37682. allDone = false;
  37683. }
  37684. }
  37685. return allDone;
  37686. };
  37687. }
  37688. return TextureOptimization;
  37689. })(SceneOptimization);
  37690. BABYLON.TextureOptimization = TextureOptimization;
  37691. var HardwareScalingOptimization = (function (_super) {
  37692. __extends(HardwareScalingOptimization, _super);
  37693. function HardwareScalingOptimization(priority, maximumScale) {
  37694. var _this = this;
  37695. if (priority === void 0) { priority = 0; }
  37696. if (maximumScale === void 0) { maximumScale = 2; }
  37697. _super.call(this, priority);
  37698. this.priority = priority;
  37699. this.maximumScale = maximumScale;
  37700. this._currentScale = 1;
  37701. this.apply = function (scene) {
  37702. _this._currentScale++;
  37703. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  37704. return _this._currentScale >= _this.maximumScale;
  37705. };
  37706. }
  37707. return HardwareScalingOptimization;
  37708. })(SceneOptimization);
  37709. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  37710. var ShadowsOptimization = (function (_super) {
  37711. __extends(ShadowsOptimization, _super);
  37712. function ShadowsOptimization() {
  37713. _super.apply(this, arguments);
  37714. this.apply = function (scene) {
  37715. scene.shadowsEnabled = false;
  37716. return true;
  37717. };
  37718. }
  37719. return ShadowsOptimization;
  37720. })(SceneOptimization);
  37721. BABYLON.ShadowsOptimization = ShadowsOptimization;
  37722. var PostProcessesOptimization = (function (_super) {
  37723. __extends(PostProcessesOptimization, _super);
  37724. function PostProcessesOptimization() {
  37725. _super.apply(this, arguments);
  37726. this.apply = function (scene) {
  37727. scene.postProcessesEnabled = false;
  37728. return true;
  37729. };
  37730. }
  37731. return PostProcessesOptimization;
  37732. })(SceneOptimization);
  37733. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  37734. var LensFlaresOptimization = (function (_super) {
  37735. __extends(LensFlaresOptimization, _super);
  37736. function LensFlaresOptimization() {
  37737. _super.apply(this, arguments);
  37738. this.apply = function (scene) {
  37739. scene.lensFlaresEnabled = false;
  37740. return true;
  37741. };
  37742. }
  37743. return LensFlaresOptimization;
  37744. })(SceneOptimization);
  37745. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  37746. var ParticlesOptimization = (function (_super) {
  37747. __extends(ParticlesOptimization, _super);
  37748. function ParticlesOptimization() {
  37749. _super.apply(this, arguments);
  37750. this.apply = function (scene) {
  37751. scene.particlesEnabled = false;
  37752. return true;
  37753. };
  37754. }
  37755. return ParticlesOptimization;
  37756. })(SceneOptimization);
  37757. BABYLON.ParticlesOptimization = ParticlesOptimization;
  37758. var RenderTargetsOptimization = (function (_super) {
  37759. __extends(RenderTargetsOptimization, _super);
  37760. function RenderTargetsOptimization() {
  37761. _super.apply(this, arguments);
  37762. this.apply = function (scene) {
  37763. scene.renderTargetsEnabled = false;
  37764. return true;
  37765. };
  37766. }
  37767. return RenderTargetsOptimization;
  37768. })(SceneOptimization);
  37769. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  37770. var MergeMeshesOptimization = (function (_super) {
  37771. __extends(MergeMeshesOptimization, _super);
  37772. function MergeMeshesOptimization() {
  37773. var _this = this;
  37774. _super.apply(this, arguments);
  37775. this._canBeMerged = function (abstractMesh) {
  37776. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  37777. return false;
  37778. }
  37779. var mesh = abstractMesh;
  37780. if (!mesh.isVisible || !mesh.isEnabled()) {
  37781. return false;
  37782. }
  37783. if (mesh.instances.length > 0) {
  37784. return false;
  37785. }
  37786. if (mesh.skeleton || mesh.hasLODLevels) {
  37787. return false;
  37788. }
  37789. if (mesh.parent) {
  37790. return false;
  37791. }
  37792. return true;
  37793. };
  37794. this.apply = function (scene, updateSelectionTree) {
  37795. var globalPool = scene.meshes.slice(0);
  37796. var globalLength = globalPool.length;
  37797. for (var index = 0; index < globalLength; index++) {
  37798. var currentPool = new Array();
  37799. var current = globalPool[index];
  37800. // Checks
  37801. if (!_this._canBeMerged(current)) {
  37802. continue;
  37803. }
  37804. currentPool.push(current);
  37805. // Find compatible meshes
  37806. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  37807. var otherMesh = globalPool[subIndex];
  37808. if (!_this._canBeMerged(otherMesh)) {
  37809. continue;
  37810. }
  37811. if (otherMesh.material !== current.material) {
  37812. continue;
  37813. }
  37814. if (otherMesh.checkCollisions !== current.checkCollisions) {
  37815. continue;
  37816. }
  37817. currentPool.push(otherMesh);
  37818. globalLength--;
  37819. globalPool.splice(subIndex, 1);
  37820. subIndex--;
  37821. }
  37822. if (currentPool.length < 2) {
  37823. continue;
  37824. }
  37825. // Merge meshes
  37826. BABYLON.Mesh.MergeMeshes(currentPool);
  37827. }
  37828. if (updateSelectionTree != undefined) {
  37829. if (updateSelectionTree) {
  37830. scene.createOrUpdateSelectionOctree();
  37831. }
  37832. }
  37833. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  37834. scene.createOrUpdateSelectionOctree();
  37835. }
  37836. return true;
  37837. };
  37838. }
  37839. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  37840. get: function () {
  37841. return MergeMeshesOptimization._UpdateSelectionTree;
  37842. },
  37843. set: function (value) {
  37844. MergeMeshesOptimization._UpdateSelectionTree = value;
  37845. },
  37846. enumerable: true,
  37847. configurable: true
  37848. });
  37849. MergeMeshesOptimization._UpdateSelectionTree = false;
  37850. return MergeMeshesOptimization;
  37851. })(SceneOptimization);
  37852. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  37853. // Options
  37854. var SceneOptimizerOptions = (function () {
  37855. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  37856. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  37857. if (trackerDuration === void 0) { trackerDuration = 2000; }
  37858. this.targetFrameRate = targetFrameRate;
  37859. this.trackerDuration = trackerDuration;
  37860. this.optimizations = new Array();
  37861. }
  37862. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  37863. var result = new SceneOptimizerOptions(targetFrameRate);
  37864. var priority = 0;
  37865. result.optimizations.push(new MergeMeshesOptimization(priority));
  37866. result.optimizations.push(new ShadowsOptimization(priority));
  37867. result.optimizations.push(new LensFlaresOptimization(priority));
  37868. // Next priority
  37869. priority++;
  37870. result.optimizations.push(new PostProcessesOptimization(priority));
  37871. result.optimizations.push(new ParticlesOptimization(priority));
  37872. // Next priority
  37873. priority++;
  37874. result.optimizations.push(new TextureOptimization(priority, 1024));
  37875. return result;
  37876. };
  37877. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  37878. var result = new SceneOptimizerOptions(targetFrameRate);
  37879. var priority = 0;
  37880. result.optimizations.push(new MergeMeshesOptimization(priority));
  37881. result.optimizations.push(new ShadowsOptimization(priority));
  37882. result.optimizations.push(new LensFlaresOptimization(priority));
  37883. // Next priority
  37884. priority++;
  37885. result.optimizations.push(new PostProcessesOptimization(priority));
  37886. result.optimizations.push(new ParticlesOptimization(priority));
  37887. // Next priority
  37888. priority++;
  37889. result.optimizations.push(new TextureOptimization(priority, 512));
  37890. // Next priority
  37891. priority++;
  37892. result.optimizations.push(new RenderTargetsOptimization(priority));
  37893. // Next priority
  37894. priority++;
  37895. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  37896. return result;
  37897. };
  37898. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  37899. var result = new SceneOptimizerOptions(targetFrameRate);
  37900. var priority = 0;
  37901. result.optimizations.push(new MergeMeshesOptimization(priority));
  37902. result.optimizations.push(new ShadowsOptimization(priority));
  37903. result.optimizations.push(new LensFlaresOptimization(priority));
  37904. // Next priority
  37905. priority++;
  37906. result.optimizations.push(new PostProcessesOptimization(priority));
  37907. result.optimizations.push(new ParticlesOptimization(priority));
  37908. // Next priority
  37909. priority++;
  37910. result.optimizations.push(new TextureOptimization(priority, 256));
  37911. // Next priority
  37912. priority++;
  37913. result.optimizations.push(new RenderTargetsOptimization(priority));
  37914. // Next priority
  37915. priority++;
  37916. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  37917. return result;
  37918. };
  37919. return SceneOptimizerOptions;
  37920. })();
  37921. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  37922. // Scene optimizer tool
  37923. var SceneOptimizer = (function () {
  37924. function SceneOptimizer() {
  37925. }
  37926. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  37927. // TODO: add an epsilon
  37928. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  37929. if (onSuccess) {
  37930. onSuccess();
  37931. }
  37932. return;
  37933. }
  37934. // Apply current level of optimizations
  37935. var allDone = true;
  37936. var noOptimizationApplied = true;
  37937. for (var index = 0; index < options.optimizations.length; index++) {
  37938. var optimization = options.optimizations[index];
  37939. if (optimization.priority === currentPriorityLevel) {
  37940. noOptimizationApplied = false;
  37941. allDone = allDone && optimization.apply(scene);
  37942. }
  37943. }
  37944. // If no optimization was applied, this is a failure :(
  37945. if (noOptimizationApplied) {
  37946. if (onFailure) {
  37947. onFailure();
  37948. }
  37949. return;
  37950. }
  37951. // If all optimizations were done, move to next level
  37952. if (allDone) {
  37953. currentPriorityLevel++;
  37954. }
  37955. // Let's the system running for a specific amount of time before checking FPS
  37956. scene.executeWhenReady(function () {
  37957. setTimeout(function () {
  37958. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  37959. }, options.trackerDuration);
  37960. });
  37961. };
  37962. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  37963. if (!options) {
  37964. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  37965. }
  37966. // Let's the system running for a specific amount of time before checking FPS
  37967. scene.executeWhenReady(function () {
  37968. setTimeout(function () {
  37969. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  37970. }, options.trackerDuration);
  37971. });
  37972. };
  37973. return SceneOptimizer;
  37974. })();
  37975. BABYLON.SceneOptimizer = SceneOptimizer;
  37976. })(BABYLON || (BABYLON = {}));
  37977. var BABYLON;
  37978. (function (BABYLON) {
  37979. var Internals;
  37980. (function (Internals) {
  37981. var MeshLODLevel = (function () {
  37982. function MeshLODLevel(distance, mesh) {
  37983. this.distance = distance;
  37984. this.mesh = mesh;
  37985. }
  37986. return MeshLODLevel;
  37987. })();
  37988. Internals.MeshLODLevel = MeshLODLevel;
  37989. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  37990. })(BABYLON || (BABYLON = {}));
  37991. var BABYLON;
  37992. (function (BABYLON) {
  37993. var RawTexture = (function (_super) {
  37994. __extends(RawTexture, _super);
  37995. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  37996. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37997. if (invertY === void 0) { invertY = false; }
  37998. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37999. _super.call(this, null, scene, !generateMipMaps, invertY);
  38000. this.format = format;
  38001. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  38002. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38003. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38004. }
  38005. RawTexture.prototype.update = function (data) {
  38006. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  38007. };
  38008. // Statics
  38009. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  38010. if (generateMipMaps === void 0) { generateMipMaps = true; }
  38011. if (invertY === void 0) { invertY = false; }
  38012. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38013. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  38014. };
  38015. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  38016. if (generateMipMaps === void 0) { generateMipMaps = true; }
  38017. if (invertY === void 0) { invertY = false; }
  38018. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38019. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  38020. };
  38021. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  38022. if (generateMipMaps === void 0) { generateMipMaps = true; }
  38023. if (invertY === void 0) { invertY = false; }
  38024. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38025. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  38026. };
  38027. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  38028. if (generateMipMaps === void 0) { generateMipMaps = true; }
  38029. if (invertY === void 0) { invertY = false; }
  38030. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38031. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  38032. };
  38033. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  38034. if (generateMipMaps === void 0) { generateMipMaps = true; }
  38035. if (invertY === void 0) { invertY = false; }
  38036. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38037. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  38038. };
  38039. return RawTexture;
  38040. })(BABYLON.Texture);
  38041. BABYLON.RawTexture = RawTexture;
  38042. })(BABYLON || (BABYLON = {}));
  38043. var BABYLON;
  38044. (function (BABYLON) {
  38045. var IndexedVector2 = (function (_super) {
  38046. __extends(IndexedVector2, _super);
  38047. function IndexedVector2(original, index) {
  38048. _super.call(this, original.x, original.y);
  38049. this.index = index;
  38050. }
  38051. return IndexedVector2;
  38052. })(BABYLON.Vector2);
  38053. var PolygonPoints = (function () {
  38054. function PolygonPoints() {
  38055. this.elements = new Array();
  38056. }
  38057. PolygonPoints.prototype.add = function (originalPoints) {
  38058. var _this = this;
  38059. var result = new Array();
  38060. originalPoints.forEach(function (point) {
  38061. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  38062. var newPoint = new IndexedVector2(point, _this.elements.length);
  38063. result.push(newPoint);
  38064. _this.elements.push(newPoint);
  38065. }
  38066. });
  38067. return result;
  38068. };
  38069. PolygonPoints.prototype.computeBounds = function () {
  38070. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  38071. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  38072. this.elements.forEach(function (point) {
  38073. // x
  38074. if (point.x < lmin.x) {
  38075. lmin.x = point.x;
  38076. }
  38077. else if (point.x > lmax.x) {
  38078. lmax.x = point.x;
  38079. }
  38080. // y
  38081. if (point.y < lmin.y) {
  38082. lmin.y = point.y;
  38083. }
  38084. else if (point.y > lmax.y) {
  38085. lmax.y = point.y;
  38086. }
  38087. });
  38088. return {
  38089. min: lmin,
  38090. max: lmax,
  38091. width: lmax.x - lmin.x,
  38092. height: lmax.y - lmin.y
  38093. };
  38094. };
  38095. return PolygonPoints;
  38096. })();
  38097. var Polygon = (function () {
  38098. function Polygon() {
  38099. }
  38100. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  38101. return [
  38102. new BABYLON.Vector2(xmin, ymin),
  38103. new BABYLON.Vector2(xmax, ymin),
  38104. new BABYLON.Vector2(xmax, ymax),
  38105. new BABYLON.Vector2(xmin, ymax)
  38106. ];
  38107. };
  38108. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  38109. if (cx === void 0) { cx = 0; }
  38110. if (cy === void 0) { cy = 0; }
  38111. if (numberOfSides === void 0) { numberOfSides = 32; }
  38112. var result = new Array();
  38113. var angle = 0;
  38114. var increment = (Math.PI * 2) / numberOfSides;
  38115. for (var i = 0; i < numberOfSides; i++) {
  38116. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  38117. angle -= increment;
  38118. }
  38119. return result;
  38120. };
  38121. Polygon.Parse = function (input) {
  38122. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  38123. var i, result = [];
  38124. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  38125. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  38126. }
  38127. return result;
  38128. };
  38129. Polygon.StartingAt = function (x, y) {
  38130. return BABYLON.Path2.StartingAt(x, y);
  38131. };
  38132. return Polygon;
  38133. })();
  38134. BABYLON.Polygon = Polygon;
  38135. var PolygonMeshBuilder = (function () {
  38136. function PolygonMeshBuilder(name, contours, scene) {
  38137. this._points = new PolygonPoints();
  38138. this._outlinepoints = new PolygonPoints();
  38139. this._holes = [];
  38140. if (!("poly2tri" in window)) {
  38141. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  38142. }
  38143. this._name = name;
  38144. this._scene = scene;
  38145. var points;
  38146. if (contours instanceof BABYLON.Path2) {
  38147. points = contours.getPoints();
  38148. }
  38149. else {
  38150. points = contours;
  38151. }
  38152. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  38153. this._outlinepoints.add(points);
  38154. }
  38155. PolygonMeshBuilder.prototype.addHole = function (hole) {
  38156. this._swctx.addHole(this._points.add(hole));
  38157. var holepoints = new PolygonPoints();
  38158. holepoints.add(hole);
  38159. this._holes.push(holepoints);
  38160. return this;
  38161. };
  38162. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  38163. var _this = this;
  38164. if (updatable === void 0) { updatable = false; }
  38165. var result = new BABYLON.Mesh(this._name, this._scene);
  38166. var normals = [];
  38167. var positions = [];
  38168. var uvs = [];
  38169. var bounds = this._points.computeBounds();
  38170. this._points.elements.forEach(function (p) {
  38171. normals.push(0, 1.0, 0);
  38172. positions.push(p.x, 0, p.y);
  38173. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  38174. });
  38175. var indices = [];
  38176. this._swctx.triangulate();
  38177. this._swctx.getTriangles().forEach(function (triangle) {
  38178. triangle.getPoints().forEach(function (point) {
  38179. indices.push(point.index);
  38180. });
  38181. });
  38182. if (depth > 0) {
  38183. var positionscount = (positions.length / 3); //get the current pointcount
  38184. this._points.elements.forEach(function (p) {
  38185. normals.push(0, -1.0, 0);
  38186. positions.push(p.x, -depth, p.y);
  38187. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  38188. });
  38189. var p1; //we need to change order of point so the triangles are made in the rigth way.
  38190. var p2;
  38191. var poscounter = 0;
  38192. this._swctx.getTriangles().forEach(function (triangle) {
  38193. triangle.getPoints().forEach(function (point) {
  38194. switch (poscounter) {
  38195. case 0:
  38196. p1 = point;
  38197. break;
  38198. case 1:
  38199. p2 = point;
  38200. break;
  38201. case 2:
  38202. indices.push(point.index + positionscount);
  38203. indices.push(p2.index + positionscount);
  38204. indices.push(p1.index + positionscount);
  38205. poscounter = -1;
  38206. break;
  38207. }
  38208. poscounter++;
  38209. //indices.push((<IndexedVector2>point).index + positionscount);
  38210. });
  38211. });
  38212. //Add the sides
  38213. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  38214. this._holes.forEach(function (hole) {
  38215. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  38216. });
  38217. }
  38218. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  38219. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  38220. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  38221. result.setIndices(indices);
  38222. return result;
  38223. };
  38224. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  38225. var StartIndex = positions.length / 3;
  38226. var ulength = 0;
  38227. for (var i = 0; i < points.elements.length; i++) {
  38228. var p = points.elements[i];
  38229. var p1;
  38230. if ((i + 1) > points.elements.length - 1) {
  38231. p1 = points.elements[0];
  38232. }
  38233. else {
  38234. p1 = points.elements[i + 1];
  38235. }
  38236. positions.push(p.x, 0, p.y);
  38237. positions.push(p.x, -depth, p.y);
  38238. positions.push(p1.x, 0, p1.y);
  38239. positions.push(p1.x, -depth, p1.y);
  38240. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  38241. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  38242. var v3 = v2.subtract(v1);
  38243. var v4 = new BABYLON.Vector3(0, 1, 0);
  38244. var vn = BABYLON.Vector3.Cross(v3, v4);
  38245. vn = vn.normalize();
  38246. uvs.push(ulength / bounds.width, 0);
  38247. uvs.push(ulength / bounds.width, 1);
  38248. ulength += v3.length();
  38249. uvs.push((ulength / bounds.width), 0);
  38250. uvs.push((ulength / bounds.width), 1);
  38251. if (!flip) {
  38252. normals.push(-vn.x, -vn.y, -vn.z);
  38253. normals.push(-vn.x, -vn.y, -vn.z);
  38254. normals.push(-vn.x, -vn.y, -vn.z);
  38255. normals.push(-vn.x, -vn.y, -vn.z);
  38256. indices.push(StartIndex);
  38257. indices.push(StartIndex + 1);
  38258. indices.push(StartIndex + 2);
  38259. indices.push(StartIndex + 1);
  38260. indices.push(StartIndex + 3);
  38261. indices.push(StartIndex + 2);
  38262. }
  38263. else {
  38264. normals.push(vn.x, vn.y, vn.z);
  38265. normals.push(vn.x, vn.y, vn.z);
  38266. normals.push(vn.x, vn.y, vn.z);
  38267. normals.push(vn.x, vn.y, vn.z);
  38268. indices.push(StartIndex);
  38269. indices.push(StartIndex + 2);
  38270. indices.push(StartIndex + 1);
  38271. indices.push(StartIndex + 1);
  38272. indices.push(StartIndex + 2);
  38273. indices.push(StartIndex + 3);
  38274. }
  38275. StartIndex += 4;
  38276. }
  38277. ;
  38278. };
  38279. return PolygonMeshBuilder;
  38280. })();
  38281. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  38282. })(BABYLON || (BABYLON = {}));
  38283. var BABYLON;
  38284. (function (BABYLON) {
  38285. var Octree = (function () {
  38286. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  38287. if (maxDepth === void 0) { maxDepth = 2; }
  38288. this.maxDepth = maxDepth;
  38289. this.dynamicContent = new Array();
  38290. this._maxBlockCapacity = maxBlockCapacity || 64;
  38291. this._selectionContent = new BABYLON.SmartArray(1024);
  38292. this._creationFunc = creationFunc;
  38293. }
  38294. // Methods
  38295. Octree.prototype.update = function (worldMin, worldMax, entries) {
  38296. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  38297. };
  38298. Octree.prototype.addMesh = function (entry) {
  38299. for (var index = 0; index < this.blocks.length; index++) {
  38300. var block = this.blocks[index];
  38301. block.addEntry(entry);
  38302. }
  38303. };
  38304. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  38305. this._selectionContent.reset();
  38306. for (var index = 0; index < this.blocks.length; index++) {
  38307. var block = this.blocks[index];
  38308. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  38309. }
  38310. if (allowDuplicate) {
  38311. this._selectionContent.concat(this.dynamicContent);
  38312. }
  38313. else {
  38314. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  38315. }
  38316. return this._selectionContent;
  38317. };
  38318. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  38319. this._selectionContent.reset();
  38320. for (var index = 0; index < this.blocks.length; index++) {
  38321. var block = this.blocks[index];
  38322. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  38323. }
  38324. if (allowDuplicate) {
  38325. this._selectionContent.concat(this.dynamicContent);
  38326. }
  38327. else {
  38328. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  38329. }
  38330. return this._selectionContent;
  38331. };
  38332. Octree.prototype.intersectsRay = function (ray) {
  38333. this._selectionContent.reset();
  38334. for (var index = 0; index < this.blocks.length; index++) {
  38335. var block = this.blocks[index];
  38336. block.intersectsRay(ray, this._selectionContent);
  38337. }
  38338. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  38339. return this._selectionContent;
  38340. };
  38341. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  38342. target.blocks = new Array();
  38343. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  38344. // Segmenting space
  38345. for (var x = 0; x < 2; x++) {
  38346. for (var y = 0; y < 2; y++) {
  38347. for (var z = 0; z < 2; z++) {
  38348. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  38349. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  38350. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  38351. block.addEntries(entries);
  38352. target.blocks.push(block);
  38353. }
  38354. }
  38355. }
  38356. };
  38357. Octree.CreationFuncForMeshes = function (entry, block) {
  38358. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  38359. block.entries.push(entry);
  38360. }
  38361. };
  38362. Octree.CreationFuncForSubMeshes = function (entry, block) {
  38363. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  38364. block.entries.push(entry);
  38365. }
  38366. };
  38367. return Octree;
  38368. })();
  38369. BABYLON.Octree = Octree;
  38370. })(BABYLON || (BABYLON = {}));
  38371. var BABYLON;
  38372. (function (BABYLON) {
  38373. var OctreeBlock = (function () {
  38374. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  38375. this.entries = new Array();
  38376. this._boundingVectors = new Array();
  38377. this._capacity = capacity;
  38378. this._depth = depth;
  38379. this._maxDepth = maxDepth;
  38380. this._creationFunc = creationFunc;
  38381. this._minPoint = minPoint;
  38382. this._maxPoint = maxPoint;
  38383. this._boundingVectors.push(minPoint.clone());
  38384. this._boundingVectors.push(maxPoint.clone());
  38385. this._boundingVectors.push(minPoint.clone());
  38386. this._boundingVectors[2].x = maxPoint.x;
  38387. this._boundingVectors.push(minPoint.clone());
  38388. this._boundingVectors[3].y = maxPoint.y;
  38389. this._boundingVectors.push(minPoint.clone());
  38390. this._boundingVectors[4].z = maxPoint.z;
  38391. this._boundingVectors.push(maxPoint.clone());
  38392. this._boundingVectors[5].z = minPoint.z;
  38393. this._boundingVectors.push(maxPoint.clone());
  38394. this._boundingVectors[6].x = minPoint.x;
  38395. this._boundingVectors.push(maxPoint.clone());
  38396. this._boundingVectors[7].y = minPoint.y;
  38397. }
  38398. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  38399. // Property
  38400. get: function () {
  38401. return this._capacity;
  38402. },
  38403. enumerable: true,
  38404. configurable: true
  38405. });
  38406. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  38407. get: function () {
  38408. return this._minPoint;
  38409. },
  38410. enumerable: true,
  38411. configurable: true
  38412. });
  38413. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  38414. get: function () {
  38415. return this._maxPoint;
  38416. },
  38417. enumerable: true,
  38418. configurable: true
  38419. });
  38420. // Methods
  38421. OctreeBlock.prototype.addEntry = function (entry) {
  38422. if (this.blocks) {
  38423. for (var index = 0; index < this.blocks.length; index++) {
  38424. var block = this.blocks[index];
  38425. block.addEntry(entry);
  38426. }
  38427. return;
  38428. }
  38429. this._creationFunc(entry, this);
  38430. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  38431. this.createInnerBlocks();
  38432. }
  38433. };
  38434. OctreeBlock.prototype.addEntries = function (entries) {
  38435. for (var index = 0; index < entries.length; index++) {
  38436. var mesh = entries[index];
  38437. this.addEntry(mesh);
  38438. }
  38439. };
  38440. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  38441. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  38442. if (this.blocks) {
  38443. for (var index = 0; index < this.blocks.length; index++) {
  38444. var block = this.blocks[index];
  38445. block.select(frustumPlanes, selection, allowDuplicate);
  38446. }
  38447. return;
  38448. }
  38449. if (allowDuplicate) {
  38450. selection.concat(this.entries);
  38451. }
  38452. else {
  38453. selection.concatWithNoDuplicate(this.entries);
  38454. }
  38455. }
  38456. };
  38457. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  38458. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  38459. if (this.blocks) {
  38460. for (var index = 0; index < this.blocks.length; index++) {
  38461. var block = this.blocks[index];
  38462. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  38463. }
  38464. return;
  38465. }
  38466. if (allowDuplicate) {
  38467. selection.concat(this.entries);
  38468. }
  38469. else {
  38470. selection.concatWithNoDuplicate(this.entries);
  38471. }
  38472. }
  38473. };
  38474. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  38475. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  38476. if (this.blocks) {
  38477. for (var index = 0; index < this.blocks.length; index++) {
  38478. var block = this.blocks[index];
  38479. block.intersectsRay(ray, selection);
  38480. }
  38481. return;
  38482. }
  38483. selection.concatWithNoDuplicate(this.entries);
  38484. }
  38485. };
  38486. OctreeBlock.prototype.createInnerBlocks = function () {
  38487. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  38488. };
  38489. return OctreeBlock;
  38490. })();
  38491. BABYLON.OctreeBlock = OctreeBlock;
  38492. })(BABYLON || (BABYLON = {}));
  38493. var BABYLON;
  38494. (function (BABYLON) {
  38495. var BlurPostProcess = (function (_super) {
  38496. __extends(BlurPostProcess, _super);
  38497. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  38498. var _this = this;
  38499. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  38500. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  38501. this.direction = direction;
  38502. this.blurWidth = blurWidth;
  38503. this.onApply = function (effect) {
  38504. effect.setFloat2("screenSize", _this.width, _this.height);
  38505. effect.setVector2("direction", _this.direction);
  38506. effect.setFloat("blurWidth", _this.blurWidth);
  38507. };
  38508. }
  38509. return BlurPostProcess;
  38510. })(BABYLON.PostProcess);
  38511. BABYLON.BlurPostProcess = BlurPostProcess;
  38512. })(BABYLON || (BABYLON = {}));
  38513. var BABYLON;
  38514. (function (BABYLON) {
  38515. var RefractionPostProcess = (function (_super) {
  38516. __extends(RefractionPostProcess, _super);
  38517. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  38518. var _this = this;
  38519. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  38520. this.color = color;
  38521. this.depth = depth;
  38522. this.colorLevel = colorLevel;
  38523. this.onActivate = function (cam) {
  38524. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  38525. };
  38526. this.onApply = function (effect) {
  38527. effect.setColor3("baseColor", _this.color);
  38528. effect.setFloat("depth", _this.depth);
  38529. effect.setFloat("colorLevel", _this.colorLevel);
  38530. effect.setTexture("refractionSampler", _this._refRexture);
  38531. };
  38532. }
  38533. // Methods
  38534. RefractionPostProcess.prototype.dispose = function (camera) {
  38535. if (this._refRexture) {
  38536. this._refRexture.dispose();
  38537. }
  38538. _super.prototype.dispose.call(this, camera);
  38539. };
  38540. return RefractionPostProcess;
  38541. })(BABYLON.PostProcess);
  38542. BABYLON.RefractionPostProcess = RefractionPostProcess;
  38543. })(BABYLON || (BABYLON = {}));
  38544. var BABYLON;
  38545. (function (BABYLON) {
  38546. var BlackAndWhitePostProcess = (function (_super) {
  38547. __extends(BlackAndWhitePostProcess, _super);
  38548. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  38549. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  38550. }
  38551. return BlackAndWhitePostProcess;
  38552. })(BABYLON.PostProcess);
  38553. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  38554. })(BABYLON || (BABYLON = {}));
  38555. var BABYLON;
  38556. (function (BABYLON) {
  38557. var ConvolutionPostProcess = (function (_super) {
  38558. __extends(ConvolutionPostProcess, _super);
  38559. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  38560. var _this = this;
  38561. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  38562. this.kernel = kernel;
  38563. this.onApply = function (effect) {
  38564. effect.setFloat2("screenSize", _this.width, _this.height);
  38565. effect.setArray("kernel", _this.kernel);
  38566. };
  38567. }
  38568. // Statics
  38569. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  38570. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  38571. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  38572. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  38573. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  38574. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  38575. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  38576. return ConvolutionPostProcess;
  38577. })(BABYLON.PostProcess);
  38578. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  38579. })(BABYLON || (BABYLON = {}));
  38580. var BABYLON;
  38581. (function (BABYLON) {
  38582. var FilterPostProcess = (function (_super) {
  38583. __extends(FilterPostProcess, _super);
  38584. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  38585. var _this = this;
  38586. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  38587. this.kernelMatrix = kernelMatrix;
  38588. this.onApply = function (effect) {
  38589. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  38590. };
  38591. }
  38592. return FilterPostProcess;
  38593. })(BABYLON.PostProcess);
  38594. BABYLON.FilterPostProcess = FilterPostProcess;
  38595. })(BABYLON || (BABYLON = {}));
  38596. var BABYLON;
  38597. (function (BABYLON) {
  38598. var FxaaPostProcess = (function (_super) {
  38599. __extends(FxaaPostProcess, _super);
  38600. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  38601. var _this = this;
  38602. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  38603. this.onSizeChanged = function () {
  38604. _this.texelWidth = 1.0 / _this.width;
  38605. _this.texelHeight = 1.0 / _this.height;
  38606. };
  38607. this.onApply = function (effect) {
  38608. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  38609. };
  38610. }
  38611. return FxaaPostProcess;
  38612. })(BABYLON.PostProcess);
  38613. BABYLON.FxaaPostProcess = FxaaPostProcess;
  38614. })(BABYLON || (BABYLON = {}));
  38615. var BABYLON;
  38616. (function (BABYLON) {
  38617. var StereoscopicInterlacePostProcess = (function (_super) {
  38618. __extends(StereoscopicInterlacePostProcess, _super);
  38619. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  38620. var _this = this;
  38621. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  38622. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  38623. this.onSizeChanged = function () {
  38624. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  38625. };
  38626. this.onApply = function (effect) {
  38627. effect.setTextureFromPostProcess("camASampler", postProcessA);
  38628. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  38629. };
  38630. }
  38631. return StereoscopicInterlacePostProcess;
  38632. })(BABYLON.PostProcess);
  38633. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  38634. })(BABYLON || (BABYLON = {}));
  38635. var BABYLON;
  38636. (function (BABYLON) {
  38637. var LensFlare = (function () {
  38638. function LensFlare(size, position, color, imgUrl, system) {
  38639. this.size = size;
  38640. this.position = position;
  38641. this.dispose = function () {
  38642. if (this.texture) {
  38643. this.texture.dispose();
  38644. }
  38645. // Remove from scene
  38646. var index = this._system.lensFlares.indexOf(this);
  38647. this._system.lensFlares.splice(index, 1);
  38648. };
  38649. this.color = color || new BABYLON.Color3(1, 1, 1);
  38650. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  38651. this._system = system;
  38652. system.lensFlares.push(this);
  38653. }
  38654. return LensFlare;
  38655. })();
  38656. BABYLON.LensFlare = LensFlare;
  38657. })(BABYLON || (BABYLON = {}));
  38658. var BABYLON;
  38659. (function (BABYLON) {
  38660. var LensFlareSystem = (function () {
  38661. function LensFlareSystem(name, emitter, scene) {
  38662. this.name = name;
  38663. this.lensFlares = new Array();
  38664. this.borderLimit = 300;
  38665. this.layerMask = 0x0FFFFFFF;
  38666. this._vertexDeclaration = [2];
  38667. this._vertexStrideSize = 2 * 4;
  38668. this._isEnabled = true;
  38669. this._scene = scene;
  38670. this._emitter = emitter;
  38671. this.id = name;
  38672. scene.lensFlareSystems.push(this);
  38673. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  38674. // VBO
  38675. var vertices = [];
  38676. vertices.push(1, 1);
  38677. vertices.push(-1, 1);
  38678. vertices.push(-1, -1);
  38679. vertices.push(1, -1);
  38680. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  38681. // Indices
  38682. var indices = [];
  38683. indices.push(0);
  38684. indices.push(1);
  38685. indices.push(2);
  38686. indices.push(0);
  38687. indices.push(2);
  38688. indices.push(3);
  38689. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  38690. // Effects
  38691. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  38692. }
  38693. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  38694. get: function () {
  38695. return this._isEnabled;
  38696. },
  38697. set: function (value) {
  38698. this._isEnabled = value;
  38699. },
  38700. enumerable: true,
  38701. configurable: true
  38702. });
  38703. LensFlareSystem.prototype.getScene = function () {
  38704. return this._scene;
  38705. };
  38706. LensFlareSystem.prototype.getEmitter = function () {
  38707. return this._emitter;
  38708. };
  38709. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  38710. this._emitter = newEmitter;
  38711. };
  38712. LensFlareSystem.prototype.getEmitterPosition = function () {
  38713. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  38714. };
  38715. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  38716. var position = this.getEmitterPosition();
  38717. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  38718. this._positionX = position.x;
  38719. this._positionY = position.y;
  38720. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  38721. if (position.z > 0) {
  38722. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  38723. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  38724. return true;
  38725. }
  38726. }
  38727. return false;
  38728. };
  38729. LensFlareSystem.prototype._isVisible = function () {
  38730. if (!this._isEnabled) {
  38731. return false;
  38732. }
  38733. var emitterPosition = this.getEmitterPosition();
  38734. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  38735. var distance = direction.length();
  38736. direction.normalize();
  38737. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  38738. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  38739. return !pickInfo.hit || pickInfo.distance > distance;
  38740. };
  38741. LensFlareSystem.prototype.render = function () {
  38742. if (!this._effect.isReady())
  38743. return false;
  38744. var engine = this._scene.getEngine();
  38745. var viewport = this._scene.activeCamera.viewport;
  38746. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  38747. // Position
  38748. if (!this.computeEffectivePosition(globalViewport)) {
  38749. return false;
  38750. }
  38751. // Visibility
  38752. if (!this._isVisible()) {
  38753. return false;
  38754. }
  38755. // Intensity
  38756. var awayX;
  38757. var awayY;
  38758. if (this._positionX < this.borderLimit + globalViewport.x) {
  38759. awayX = this.borderLimit + globalViewport.x - this._positionX;
  38760. }
  38761. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  38762. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  38763. }
  38764. else {
  38765. awayX = 0;
  38766. }
  38767. if (this._positionY < this.borderLimit + globalViewport.y) {
  38768. awayY = this.borderLimit + globalViewport.y - this._positionY;
  38769. }
  38770. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  38771. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  38772. }
  38773. else {
  38774. awayY = 0;
  38775. }
  38776. var away = (awayX > awayY) ? awayX : awayY;
  38777. if (away > this.borderLimit) {
  38778. away = this.borderLimit;
  38779. }
  38780. var intensity = 1.0 - (away / this.borderLimit);
  38781. if (intensity < 0) {
  38782. return false;
  38783. }
  38784. if (intensity > 1.0) {
  38785. intensity = 1.0;
  38786. }
  38787. // Position
  38788. var centerX = globalViewport.x + globalViewport.width / 2;
  38789. var centerY = globalViewport.y + globalViewport.height / 2;
  38790. var distX = centerX - this._positionX;
  38791. var distY = centerY - this._positionY;
  38792. // Effects
  38793. engine.enableEffect(this._effect);
  38794. engine.setState(false);
  38795. engine.setDepthBuffer(false);
  38796. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  38797. // VBOs
  38798. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  38799. // Flares
  38800. for (var index = 0; index < this.lensFlares.length; index++) {
  38801. var flare = this.lensFlares[index];
  38802. var x = centerX - (distX * flare.position);
  38803. var y = centerY - (distY * flare.position);
  38804. var cw = flare.size;
  38805. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  38806. var cx = 2 * (x / globalViewport.width) - 1.0;
  38807. var cy = 1.0 - 2 * (y / globalViewport.height);
  38808. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  38809. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  38810. // Texture
  38811. this._effect.setTexture("textureSampler", flare.texture);
  38812. // Color
  38813. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  38814. // Draw order
  38815. engine.draw(true, 0, 6);
  38816. }
  38817. engine.setDepthBuffer(true);
  38818. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  38819. return true;
  38820. };
  38821. LensFlareSystem.prototype.dispose = function () {
  38822. if (this._vertexBuffer) {
  38823. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  38824. this._vertexBuffer = null;
  38825. }
  38826. if (this._indexBuffer) {
  38827. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38828. this._indexBuffer = null;
  38829. }
  38830. while (this.lensFlares.length) {
  38831. this.lensFlares[0].dispose();
  38832. }
  38833. // Remove from scene
  38834. var index = this._scene.lensFlareSystems.indexOf(this);
  38835. this._scene.lensFlareSystems.splice(index, 1);
  38836. };
  38837. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  38838. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  38839. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  38840. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  38841. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  38842. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  38843. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  38844. var parsedFlare = parsedLensFlareSystem.flares[index];
  38845. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  38846. }
  38847. return lensFlareSystem;
  38848. };
  38849. LensFlareSystem.prototype.serialize = function () {
  38850. var serializationObject = {};
  38851. serializationObject.id = this.id;
  38852. serializationObject.name = this.name;
  38853. serializationObject.emitterId = this.getEmitter().id;
  38854. serializationObject.borderLimit = this.borderLimit;
  38855. serializationObject.flares = [];
  38856. for (var index = 0; index < this.lensFlares.length; index++) {
  38857. var flare = this.lensFlares[index];
  38858. serializationObject.flares.push({
  38859. size: flare.size,
  38860. position: flare.position,
  38861. color: flare.color.asArray(),
  38862. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  38863. });
  38864. }
  38865. return serializationObject;
  38866. };
  38867. return LensFlareSystem;
  38868. })();
  38869. BABYLON.LensFlareSystem = LensFlareSystem;
  38870. })(BABYLON || (BABYLON = {}));
  38871. var BABYLON;
  38872. (function (BABYLON) {
  38873. // We're mainly based on the logic defined into the FreeCamera code
  38874. var DeviceOrientationCamera = (function (_super) {
  38875. __extends(DeviceOrientationCamera, _super);
  38876. //-- end properties for backward compatibility for inputs
  38877. function DeviceOrientationCamera(name, position, scene) {
  38878. _super.call(this, name, position, scene);
  38879. this.inputs.addDeviceOrientation();
  38880. }
  38881. Object.defineProperty(DeviceOrientationCamera.prototype, "angularSensibility", {
  38882. //-- Begin properties for backward compatibility for inputs
  38883. get: function () {
  38884. var gamepad = this.inputs.attached["deviceOrientation"];
  38885. if (gamepad)
  38886. return gamepad.angularSensibility;
  38887. },
  38888. set: function (value) {
  38889. var gamepad = this.inputs.attached["deviceOrientation"];
  38890. if (gamepad)
  38891. gamepad.angularSensibility = value;
  38892. },
  38893. enumerable: true,
  38894. configurable: true
  38895. });
  38896. Object.defineProperty(DeviceOrientationCamera.prototype, "moveSensibility", {
  38897. get: function () {
  38898. var gamepad = this.inputs.attached["deviceOrientation"];
  38899. if (gamepad)
  38900. return gamepad.moveSensibility;
  38901. },
  38902. set: function (value) {
  38903. var gamepad = this.inputs.attached["deviceOrientation"];
  38904. if (gamepad)
  38905. gamepad.moveSensibility = value;
  38906. },
  38907. enumerable: true,
  38908. configurable: true
  38909. });
  38910. DeviceOrientationCamera.prototype.getTypeName = function () {
  38911. return "DeviceOrientationCamera";
  38912. };
  38913. return DeviceOrientationCamera;
  38914. })(BABYLON.FreeCamera);
  38915. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  38916. })(BABYLON || (BABYLON = {}));
  38917. var BABYLON;
  38918. (function (BABYLON) {
  38919. // We're mainly based on the logic defined into the FreeCamera code
  38920. var UniversalCamera = (function (_super) {
  38921. __extends(UniversalCamera, _super);
  38922. //-- end properties for backward compatibility for inputs
  38923. function UniversalCamera(name, position, scene) {
  38924. _super.call(this, name, position, scene);
  38925. this.inputs.addGamepad();
  38926. }
  38927. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  38928. //-- Begin properties for backward compatibility for inputs
  38929. get: function () {
  38930. var gamepad = this.inputs.attached["gamepad"];
  38931. if (gamepad)
  38932. return gamepad.gamepadAngularSensibility;
  38933. },
  38934. set: function (value) {
  38935. var gamepad = this.inputs.attached["gamepad"];
  38936. if (gamepad)
  38937. gamepad.gamepadAngularSensibility = value;
  38938. },
  38939. enumerable: true,
  38940. configurable: true
  38941. });
  38942. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  38943. get: function () {
  38944. var gamepad = this.inputs.attached["gamepad"];
  38945. if (gamepad)
  38946. return gamepad.gamepadMoveSensibility;
  38947. },
  38948. set: function (value) {
  38949. var gamepad = this.inputs.attached["gamepad"];
  38950. if (gamepad)
  38951. gamepad.gamepadMoveSensibility = value;
  38952. },
  38953. enumerable: true,
  38954. configurable: true
  38955. });
  38956. UniversalCamera.prototype.getTypeName = function () {
  38957. return "UniversalCamera";
  38958. };
  38959. return UniversalCamera;
  38960. })(BABYLON.TouchCamera);
  38961. BABYLON.UniversalCamera = UniversalCamera;
  38962. })(BABYLON || (BABYLON = {}));
  38963. var BABYLON;
  38964. (function (BABYLON) {
  38965. var Gamepads = (function () {
  38966. function Gamepads(ongamedpadconnected) {
  38967. var _this = this;
  38968. this.babylonGamepads = [];
  38969. this.oneGamepadConnected = false;
  38970. this.isMonitoring = false;
  38971. this.gamepadEventSupported = 'GamepadEvent' in window;
  38972. this.gamepadSupportAvailable = (navigator.getGamepads ||
  38973. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  38974. this._callbackGamepadConnected = ongamedpadconnected;
  38975. if (this.gamepadSupportAvailable) {
  38976. // Checking if the gamepad connected event is supported (like in Firefox)
  38977. if (this.gamepadEventSupported) {
  38978. this._onGamepadConnectedEvent = function (evt) {
  38979. _this._onGamepadConnected(evt);
  38980. };
  38981. this._onGamepadDisonnectedEvent = function (evt) {
  38982. _this._onGamepadDisconnected(evt);
  38983. };
  38984. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  38985. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  38986. }
  38987. else {
  38988. this._startMonitoringGamepads();
  38989. }
  38990. }
  38991. }
  38992. Gamepads.prototype.dispose = function () {
  38993. if (Gamepads.gamepadDOMInfo) {
  38994. document.body.removeChild(Gamepads.gamepadDOMInfo);
  38995. }
  38996. if (this._onGamepadConnectedEvent) {
  38997. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  38998. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  38999. this._onGamepadConnectedEvent = null;
  39000. this._onGamepadDisonnectedEvent = null;
  39001. }
  39002. };
  39003. Gamepads.prototype._onGamepadConnected = function (evt) {
  39004. var newGamepad = this._addNewGamepad(evt.gamepad);
  39005. if (this._callbackGamepadConnected)
  39006. this._callbackGamepadConnected(newGamepad);
  39007. this._startMonitoringGamepads();
  39008. };
  39009. Gamepads.prototype._addNewGamepad = function (gamepad) {
  39010. if (!this.oneGamepadConnected) {
  39011. this.oneGamepadConnected = true;
  39012. if (Gamepads.gamepadDOMInfo) {
  39013. document.body.removeChild(Gamepads.gamepadDOMInfo);
  39014. Gamepads.gamepadDOMInfo = null;
  39015. }
  39016. }
  39017. var newGamepad;
  39018. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  39019. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  39020. }
  39021. else {
  39022. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  39023. }
  39024. this.babylonGamepads.push(newGamepad);
  39025. return newGamepad;
  39026. };
  39027. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  39028. // Remove the gamepad from the list of gamepads to monitor.
  39029. for (var i in this.babylonGamepads) {
  39030. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  39031. this.babylonGamepads.splice(+i, 1);
  39032. break;
  39033. }
  39034. }
  39035. // If no gamepads are left, stop the polling loop.
  39036. if (this.babylonGamepads.length == 0) {
  39037. this._stopMonitoringGamepads();
  39038. }
  39039. };
  39040. Gamepads.prototype._startMonitoringGamepads = function () {
  39041. if (!this.isMonitoring) {
  39042. this.isMonitoring = true;
  39043. this._checkGamepadsStatus();
  39044. }
  39045. };
  39046. Gamepads.prototype._stopMonitoringGamepads = function () {
  39047. this.isMonitoring = false;
  39048. };
  39049. Gamepads.prototype._checkGamepadsStatus = function () {
  39050. var _this = this;
  39051. // updating gamepad objects
  39052. this._updateGamepadObjects();
  39053. for (var i in this.babylonGamepads) {
  39054. this.babylonGamepads[i].update();
  39055. }
  39056. if (this.isMonitoring) {
  39057. if (window.requestAnimationFrame) {
  39058. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  39059. }
  39060. else if (window.mozRequestAnimationFrame) {
  39061. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  39062. }
  39063. else if (window.webkitRequestAnimationFrame) {
  39064. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  39065. }
  39066. }
  39067. };
  39068. // This function is called only on Chrome, which does not yet support
  39069. // connection/disconnection events, but requires you to monitor
  39070. // an array for changes.
  39071. Gamepads.prototype._updateGamepadObjects = function () {
  39072. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  39073. for (var i = 0; i < gamepads.length; i++) {
  39074. if (gamepads[i]) {
  39075. if (!(gamepads[i].index in this.babylonGamepads)) {
  39076. var newGamepad = this._addNewGamepad(gamepads[i]);
  39077. if (this._callbackGamepadConnected) {
  39078. this._callbackGamepadConnected(newGamepad);
  39079. }
  39080. }
  39081. else {
  39082. this.babylonGamepads[i].browserGamepad = gamepads[i];
  39083. }
  39084. }
  39085. }
  39086. };
  39087. return Gamepads;
  39088. })();
  39089. BABYLON.Gamepads = Gamepads;
  39090. var StickValues = (function () {
  39091. function StickValues(x, y) {
  39092. this.x = x;
  39093. this.y = y;
  39094. }
  39095. return StickValues;
  39096. })();
  39097. BABYLON.StickValues = StickValues;
  39098. var Gamepad = (function () {
  39099. function Gamepad(id, index, browserGamepad) {
  39100. this.id = id;
  39101. this.index = index;
  39102. this.browserGamepad = browserGamepad;
  39103. if (this.browserGamepad.axes.length >= 2) {
  39104. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  39105. }
  39106. if (this.browserGamepad.axes.length >= 4) {
  39107. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  39108. }
  39109. }
  39110. Gamepad.prototype.onleftstickchanged = function (callback) {
  39111. this._onleftstickchanged = callback;
  39112. };
  39113. Gamepad.prototype.onrightstickchanged = function (callback) {
  39114. this._onrightstickchanged = callback;
  39115. };
  39116. Object.defineProperty(Gamepad.prototype, "leftStick", {
  39117. get: function () {
  39118. return this._leftStick;
  39119. },
  39120. set: function (newValues) {
  39121. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  39122. this._onleftstickchanged(newValues);
  39123. }
  39124. this._leftStick = newValues;
  39125. },
  39126. enumerable: true,
  39127. configurable: true
  39128. });
  39129. Object.defineProperty(Gamepad.prototype, "rightStick", {
  39130. get: function () {
  39131. return this._rightStick;
  39132. },
  39133. set: function (newValues) {
  39134. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  39135. this._onrightstickchanged(newValues);
  39136. }
  39137. this._rightStick = newValues;
  39138. },
  39139. enumerable: true,
  39140. configurable: true
  39141. });
  39142. Gamepad.prototype.update = function () {
  39143. if (this._leftStick) {
  39144. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  39145. }
  39146. if (this._rightStick) {
  39147. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  39148. }
  39149. };
  39150. return Gamepad;
  39151. })();
  39152. BABYLON.Gamepad = Gamepad;
  39153. var GenericPad = (function (_super) {
  39154. __extends(GenericPad, _super);
  39155. function GenericPad(id, index, gamepad) {
  39156. _super.call(this, id, index, gamepad);
  39157. this.id = id;
  39158. this.index = index;
  39159. this.gamepad = gamepad;
  39160. this._buttons = new Array(gamepad.buttons.length);
  39161. }
  39162. GenericPad.prototype.onbuttondown = function (callback) {
  39163. this._onbuttondown = callback;
  39164. };
  39165. GenericPad.prototype.onbuttonup = function (callback) {
  39166. this._onbuttonup = callback;
  39167. };
  39168. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  39169. if (newValue !== currentValue) {
  39170. if (this._onbuttondown && newValue === 1) {
  39171. this._onbuttondown(buttonIndex);
  39172. }
  39173. if (this._onbuttonup && newValue === 0) {
  39174. this._onbuttonup(buttonIndex);
  39175. }
  39176. }
  39177. return newValue;
  39178. };
  39179. GenericPad.prototype.update = function () {
  39180. _super.prototype.update.call(this);
  39181. for (var index = 0; index < this._buttons.length; index++) {
  39182. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  39183. }
  39184. };
  39185. return GenericPad;
  39186. })(Gamepad);
  39187. BABYLON.GenericPad = GenericPad;
  39188. (function (Xbox360Button) {
  39189. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  39190. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  39191. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  39192. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  39193. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  39194. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  39195. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  39196. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  39197. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  39198. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  39199. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  39200. var Xbox360Button = BABYLON.Xbox360Button;
  39201. (function (Xbox360Dpad) {
  39202. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  39203. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  39204. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  39205. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  39206. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  39207. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  39208. var Xbox360Pad = (function (_super) {
  39209. __extends(Xbox360Pad, _super);
  39210. function Xbox360Pad() {
  39211. _super.apply(this, arguments);
  39212. this._leftTrigger = 0;
  39213. this._rightTrigger = 0;
  39214. this._buttonA = 0;
  39215. this._buttonB = 0;
  39216. this._buttonX = 0;
  39217. this._buttonY = 0;
  39218. this._buttonBack = 0;
  39219. this._buttonStart = 0;
  39220. this._buttonLB = 0;
  39221. this._buttonRB = 0;
  39222. this._buttonLeftStick = 0;
  39223. this._buttonRightStick = 0;
  39224. this._dPadUp = 0;
  39225. this._dPadDown = 0;
  39226. this._dPadLeft = 0;
  39227. this._dPadRight = 0;
  39228. }
  39229. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  39230. this._onlefttriggerchanged = callback;
  39231. };
  39232. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  39233. this._onrighttriggerchanged = callback;
  39234. };
  39235. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  39236. get: function () {
  39237. return this._leftTrigger;
  39238. },
  39239. set: function (newValue) {
  39240. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  39241. this._onlefttriggerchanged(newValue);
  39242. }
  39243. this._leftTrigger = newValue;
  39244. },
  39245. enumerable: true,
  39246. configurable: true
  39247. });
  39248. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  39249. get: function () {
  39250. return this._rightTrigger;
  39251. },
  39252. set: function (newValue) {
  39253. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  39254. this._onrighttriggerchanged(newValue);
  39255. }
  39256. this._rightTrigger = newValue;
  39257. },
  39258. enumerable: true,
  39259. configurable: true
  39260. });
  39261. Xbox360Pad.prototype.onbuttondown = function (callback) {
  39262. this._onbuttondown = callback;
  39263. };
  39264. Xbox360Pad.prototype.onbuttonup = function (callback) {
  39265. this._onbuttonup = callback;
  39266. };
  39267. Xbox360Pad.prototype.ondpaddown = function (callback) {
  39268. this._ondpaddown = callback;
  39269. };
  39270. Xbox360Pad.prototype.ondpadup = function (callback) {
  39271. this._ondpadup = callback;
  39272. };
  39273. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  39274. if (newValue !== currentValue) {
  39275. if (this._onbuttondown && newValue === 1) {
  39276. this._onbuttondown(buttonType);
  39277. }
  39278. if (this._onbuttonup && newValue === 0) {
  39279. this._onbuttonup(buttonType);
  39280. }
  39281. }
  39282. return newValue;
  39283. };
  39284. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  39285. if (newValue !== currentValue) {
  39286. if (this._ondpaddown && newValue === 1) {
  39287. this._ondpaddown(buttonType);
  39288. }
  39289. if (this._ondpadup && newValue === 0) {
  39290. this._ondpadup(buttonType);
  39291. }
  39292. }
  39293. return newValue;
  39294. };
  39295. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  39296. get: function () {
  39297. return this._buttonA;
  39298. },
  39299. set: function (value) {
  39300. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  39301. },
  39302. enumerable: true,
  39303. configurable: true
  39304. });
  39305. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  39306. get: function () {
  39307. return this._buttonB;
  39308. },
  39309. set: function (value) {
  39310. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  39311. },
  39312. enumerable: true,
  39313. configurable: true
  39314. });
  39315. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  39316. get: function () {
  39317. return this._buttonX;
  39318. },
  39319. set: function (value) {
  39320. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  39321. },
  39322. enumerable: true,
  39323. configurable: true
  39324. });
  39325. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  39326. get: function () {
  39327. return this._buttonY;
  39328. },
  39329. set: function (value) {
  39330. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  39331. },
  39332. enumerable: true,
  39333. configurable: true
  39334. });
  39335. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  39336. get: function () {
  39337. return this._buttonStart;
  39338. },
  39339. set: function (value) {
  39340. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  39341. },
  39342. enumerable: true,
  39343. configurable: true
  39344. });
  39345. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  39346. get: function () {
  39347. return this._buttonBack;
  39348. },
  39349. set: function (value) {
  39350. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  39351. },
  39352. enumerable: true,
  39353. configurable: true
  39354. });
  39355. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  39356. get: function () {
  39357. return this._buttonLB;
  39358. },
  39359. set: function (value) {
  39360. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  39361. },
  39362. enumerable: true,
  39363. configurable: true
  39364. });
  39365. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  39366. get: function () {
  39367. return this._buttonRB;
  39368. },
  39369. set: function (value) {
  39370. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  39371. },
  39372. enumerable: true,
  39373. configurable: true
  39374. });
  39375. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  39376. get: function () {
  39377. return this._buttonLeftStick;
  39378. },
  39379. set: function (value) {
  39380. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  39381. },
  39382. enumerable: true,
  39383. configurable: true
  39384. });
  39385. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  39386. get: function () {
  39387. return this._buttonRightStick;
  39388. },
  39389. set: function (value) {
  39390. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  39391. },
  39392. enumerable: true,
  39393. configurable: true
  39394. });
  39395. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  39396. get: function () {
  39397. return this._dPadUp;
  39398. },
  39399. set: function (value) {
  39400. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  39401. },
  39402. enumerable: true,
  39403. configurable: true
  39404. });
  39405. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  39406. get: function () {
  39407. return this._dPadDown;
  39408. },
  39409. set: function (value) {
  39410. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  39411. },
  39412. enumerable: true,
  39413. configurable: true
  39414. });
  39415. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  39416. get: function () {
  39417. return this._dPadLeft;
  39418. },
  39419. set: function (value) {
  39420. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  39421. },
  39422. enumerable: true,
  39423. configurable: true
  39424. });
  39425. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  39426. get: function () {
  39427. return this._dPadRight;
  39428. },
  39429. set: function (value) {
  39430. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  39431. },
  39432. enumerable: true,
  39433. configurable: true
  39434. });
  39435. Xbox360Pad.prototype.update = function () {
  39436. _super.prototype.update.call(this);
  39437. this.buttonA = this.browserGamepad.buttons[0].value;
  39438. this.buttonB = this.browserGamepad.buttons[1].value;
  39439. this.buttonX = this.browserGamepad.buttons[2].value;
  39440. this.buttonY = this.browserGamepad.buttons[3].value;
  39441. this.buttonLB = this.browserGamepad.buttons[4].value;
  39442. this.buttonRB = this.browserGamepad.buttons[5].value;
  39443. this.leftTrigger = this.browserGamepad.buttons[6].value;
  39444. this.rightTrigger = this.browserGamepad.buttons[7].value;
  39445. this.buttonBack = this.browserGamepad.buttons[8].value;
  39446. this.buttonStart = this.browserGamepad.buttons[9].value;
  39447. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  39448. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  39449. this.dPadUp = this.browserGamepad.buttons[12].value;
  39450. this.dPadDown = this.browserGamepad.buttons[13].value;
  39451. this.dPadLeft = this.browserGamepad.buttons[14].value;
  39452. this.dPadRight = this.browserGamepad.buttons[15].value;
  39453. };
  39454. return Xbox360Pad;
  39455. })(Gamepad);
  39456. BABYLON.Xbox360Pad = Xbox360Pad;
  39457. })(BABYLON || (BABYLON = {}));
  39458. var BABYLON;
  39459. (function (BABYLON) {
  39460. // We're mainly based on the logic defined into the FreeCamera code
  39461. var GamepadCamera = (function (_super) {
  39462. __extends(GamepadCamera, _super);
  39463. //-- end properties for backward compatibility for inputs
  39464. function GamepadCamera(name, position, scene) {
  39465. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  39466. _super.call(this, name, position, scene);
  39467. }
  39468. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  39469. //-- Begin properties for backward compatibility for inputs
  39470. get: function () {
  39471. var gamepad = this.inputs.attached["gamepad"];
  39472. if (gamepad)
  39473. return gamepad.gamepadAngularSensibility;
  39474. },
  39475. set: function (value) {
  39476. var gamepad = this.inputs.attached["gamepad"];
  39477. if (gamepad)
  39478. gamepad.gamepadAngularSensibility = value;
  39479. },
  39480. enumerable: true,
  39481. configurable: true
  39482. });
  39483. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  39484. get: function () {
  39485. var gamepad = this.inputs.attached["gamepad"];
  39486. if (gamepad)
  39487. return gamepad.gamepadMoveSensibility;
  39488. },
  39489. set: function (value) {
  39490. var gamepad = this.inputs.attached["gamepad"];
  39491. if (gamepad)
  39492. gamepad.gamepadMoveSensibility = value;
  39493. },
  39494. enumerable: true,
  39495. configurable: true
  39496. });
  39497. GamepadCamera.prototype.getTypeName = function () {
  39498. return "GamepadCamera";
  39499. };
  39500. return GamepadCamera;
  39501. })(BABYLON.UniversalCamera);
  39502. BABYLON.GamepadCamera = GamepadCamera;
  39503. })(BABYLON || (BABYLON = {}));
  39504. var BABYLON;
  39505. (function (BABYLON) {
  39506. var Analyser = (function () {
  39507. function Analyser(scene) {
  39508. this.SMOOTHING = 0.75;
  39509. this.FFT_SIZE = 512;
  39510. this.BARGRAPHAMPLITUDE = 256;
  39511. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  39512. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  39513. this._scene = scene;
  39514. this._audioEngine = BABYLON.Engine.audioEngine;
  39515. if (this._audioEngine.canUseWebAudio) {
  39516. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  39517. this._webAudioAnalyser.minDecibels = -140;
  39518. this._webAudioAnalyser.maxDecibels = 0;
  39519. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  39520. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  39521. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  39522. }
  39523. }
  39524. Analyser.prototype.getFrequencyBinCount = function () {
  39525. if (this._audioEngine.canUseWebAudio) {
  39526. return this._webAudioAnalyser.frequencyBinCount;
  39527. }
  39528. else {
  39529. return 0;
  39530. }
  39531. };
  39532. Analyser.prototype.getByteFrequencyData = function () {
  39533. if (this._audioEngine.canUseWebAudio) {
  39534. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  39535. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  39536. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  39537. }
  39538. return this._byteFreqs;
  39539. };
  39540. Analyser.prototype.getByteTimeDomainData = function () {
  39541. if (this._audioEngine.canUseWebAudio) {
  39542. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  39543. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  39544. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  39545. }
  39546. return this._byteTime;
  39547. };
  39548. Analyser.prototype.getFloatFrequencyData = function () {
  39549. if (this._audioEngine.canUseWebAudio) {
  39550. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  39551. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  39552. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  39553. }
  39554. return this._floatFreqs;
  39555. };
  39556. Analyser.prototype.drawDebugCanvas = function () {
  39557. var _this = this;
  39558. if (this._audioEngine.canUseWebAudio) {
  39559. if (!this._debugCanvas) {
  39560. this._debugCanvas = document.createElement("canvas");
  39561. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  39562. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  39563. this._debugCanvas.style.position = "absolute";
  39564. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  39565. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  39566. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  39567. document.body.appendChild(this._debugCanvas);
  39568. this._registerFunc = function () {
  39569. _this.drawDebugCanvas();
  39570. };
  39571. this._scene.registerBeforeRender(this._registerFunc);
  39572. }
  39573. if (this._registerFunc) {
  39574. var workingArray = this.getByteFrequencyData();
  39575. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  39576. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  39577. // Draw the frequency domain chart.
  39578. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  39579. var value = workingArray[i];
  39580. var percent = value / this.BARGRAPHAMPLITUDE;
  39581. var height = this.DEBUGCANVASSIZE.height * percent;
  39582. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  39583. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  39584. var hue = i / this.getFrequencyBinCount() * 360;
  39585. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  39586. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  39587. }
  39588. }
  39589. }
  39590. };
  39591. Analyser.prototype.stopDebugCanvas = function () {
  39592. if (this._debugCanvas) {
  39593. this._scene.unregisterBeforeRender(this._registerFunc);
  39594. this._registerFunc = null;
  39595. document.body.removeChild(this._debugCanvas);
  39596. this._debugCanvas = null;
  39597. this._debugCanvasContext = null;
  39598. }
  39599. };
  39600. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  39601. if (this._audioEngine.canUseWebAudio) {
  39602. inputAudioNode.connect(this._webAudioAnalyser);
  39603. this._webAudioAnalyser.connect(outputAudioNode);
  39604. }
  39605. };
  39606. Analyser.prototype.dispose = function () {
  39607. if (this._audioEngine.canUseWebAudio) {
  39608. this._webAudioAnalyser.disconnect();
  39609. }
  39610. };
  39611. return Analyser;
  39612. })();
  39613. BABYLON.Analyser = Analyser;
  39614. })(BABYLON || (BABYLON = {}));
  39615. var BABYLON;
  39616. (function (BABYLON) {
  39617. var DepthRenderer = (function () {
  39618. function DepthRenderer(scene, type) {
  39619. var _this = this;
  39620. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  39621. this._viewMatrix = BABYLON.Matrix.Zero();
  39622. this._projectionMatrix = BABYLON.Matrix.Zero();
  39623. this._transformMatrix = BABYLON.Matrix.Zero();
  39624. this._worldViewProjection = BABYLON.Matrix.Zero();
  39625. this._scene = scene;
  39626. var engine = scene.getEngine();
  39627. // Render target
  39628. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  39629. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39630. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39631. this._depthMap.refreshRate = 1;
  39632. this._depthMap.renderParticles = false;
  39633. this._depthMap.renderList = null;
  39634. // set default depth value to 1.0 (far away)
  39635. this._depthMap.onClear = function (engine) {
  39636. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  39637. };
  39638. // Custom render function
  39639. var renderSubMesh = function (subMesh) {
  39640. var mesh = subMesh.getRenderingMesh();
  39641. var scene = _this._scene;
  39642. var engine = scene.getEngine();
  39643. // Culling
  39644. engine.setState(subMesh.getMaterial().backFaceCulling);
  39645. // Managing instances
  39646. var batch = mesh._getInstancesRenderList(subMesh._id);
  39647. if (batch.mustReturn) {
  39648. return;
  39649. }
  39650. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  39651. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  39652. engine.enableEffect(_this._effect);
  39653. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  39654. var material = subMesh.getMaterial();
  39655. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  39656. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  39657. // Alpha test
  39658. if (material && material.needAlphaTesting()) {
  39659. var alphaTexture = material.getAlphaTestTexture();
  39660. _this._effect.setTexture("diffuseSampler", alphaTexture);
  39661. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  39662. }
  39663. // Bones
  39664. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  39665. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  39666. }
  39667. // Draw
  39668. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  39669. }
  39670. };
  39671. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  39672. var index;
  39673. for (index = 0; index < opaqueSubMeshes.length; index++) {
  39674. renderSubMesh(opaqueSubMeshes.data[index]);
  39675. }
  39676. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  39677. renderSubMesh(alphaTestSubMeshes.data[index]);
  39678. }
  39679. };
  39680. }
  39681. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  39682. var material = subMesh.getMaterial();
  39683. if (material.disableDepthWrite) {
  39684. return false;
  39685. }
  39686. var defines = [];
  39687. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39688. var mesh = subMesh.getMesh();
  39689. var scene = mesh.getScene();
  39690. // Alpha test
  39691. if (material && material.needAlphaTesting()) {
  39692. defines.push("#define ALPHATEST");
  39693. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39694. attribs.push(BABYLON.VertexBuffer.UVKind);
  39695. defines.push("#define UV1");
  39696. }
  39697. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39698. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39699. defines.push("#define UV2");
  39700. }
  39701. }
  39702. // Bones
  39703. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  39704. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39705. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39706. if (mesh.numBoneInfluencers > 4) {
  39707. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39708. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39709. }
  39710. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  39711. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  39712. }
  39713. else {
  39714. defines.push("#define NUM_BONE_INFLUENCERS 0");
  39715. }
  39716. // Instances
  39717. if (useInstances) {
  39718. defines.push("#define INSTANCES");
  39719. attribs.push("world0");
  39720. attribs.push("world1");
  39721. attribs.push("world2");
  39722. attribs.push("world3");
  39723. }
  39724. // Get correct effect
  39725. var join = defines.join("\n");
  39726. if (this._cachedDefines !== join) {
  39727. this._cachedDefines = join;
  39728. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  39729. }
  39730. return this._effect.isReady();
  39731. };
  39732. DepthRenderer.prototype.getDepthMap = function () {
  39733. return this._depthMap;
  39734. };
  39735. // Methods
  39736. DepthRenderer.prototype.dispose = function () {
  39737. this._depthMap.dispose();
  39738. };
  39739. return DepthRenderer;
  39740. })();
  39741. BABYLON.DepthRenderer = DepthRenderer;
  39742. })(BABYLON || (BABYLON = {}));
  39743. var BABYLON;
  39744. (function (BABYLON) {
  39745. var SSAORenderingPipeline = (function (_super) {
  39746. __extends(SSAORenderingPipeline, _super);
  39747. /**
  39748. * @constructor
  39749. * @param {string} name - The rendering pipeline name
  39750. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  39751. * @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 }
  39752. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  39753. */
  39754. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  39755. var _this = this;
  39756. _super.call(this, scene.getEngine(), name);
  39757. // Members
  39758. /**
  39759. * The PassPostProcess id in the pipeline that contains the original scene color
  39760. * @type {string}
  39761. */
  39762. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  39763. /**
  39764. * The SSAO PostProcess id in the pipeline
  39765. * @type {string}
  39766. */
  39767. this.SSAORenderEffect = "SSAORenderEffect";
  39768. /**
  39769. * The horizontal blur PostProcess id in the pipeline
  39770. * @type {string}
  39771. */
  39772. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  39773. /**
  39774. * The vertical blur PostProcess id in the pipeline
  39775. * @type {string}
  39776. */
  39777. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  39778. /**
  39779. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  39780. * @type {string}
  39781. */
  39782. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  39783. /**
  39784. * The output strength of the SSAO post-process. Default value is 1.0.
  39785. * @type {number}
  39786. */
  39787. this.totalStrength = 1.0;
  39788. /**
  39789. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  39790. * @type {number}
  39791. */
  39792. this.radius = 0.0001;
  39793. /**
  39794. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  39795. * Must not be equal to fallOff and superior to fallOff.
  39796. * Default value is 0.975
  39797. * @type {number}
  39798. */
  39799. this.area = 0.0075;
  39800. /**
  39801. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  39802. * Must not be equal to area and inferior to area.
  39803. * Default value is 0.0
  39804. * @type {number}
  39805. */
  39806. this.fallOff = 0.000001;
  39807. /**
  39808. * The base color of the SSAO post-process
  39809. * The final result is "base + ssao" between [0, 1]
  39810. * @type {number}
  39811. */
  39812. this.base = 0.5;
  39813. this._firstUpdate = true;
  39814. this._scene = scene;
  39815. // Set up assets
  39816. this._createRandomTexture();
  39817. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  39818. var ssaoRatio = ratio.ssaoRatio || ratio;
  39819. var combineRatio = ratio.combineRatio || ratio;
  39820. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  39821. this._createSSAOPostProcess(ssaoRatio);
  39822. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  39823. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  39824. this._createSSAOCombinePostProcess(combineRatio);
  39825. // Set up pipeline
  39826. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  39827. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  39828. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  39829. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  39830. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  39831. // Finish
  39832. scene.postProcessRenderPipelineManager.addPipeline(this);
  39833. if (cameras)
  39834. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  39835. }
  39836. // Public Methods
  39837. /**
  39838. * Returns the horizontal blur PostProcess
  39839. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  39840. */
  39841. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  39842. return this._blurHPostProcess;
  39843. };
  39844. /**
  39845. * Returns the vertical blur PostProcess
  39846. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  39847. */
  39848. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  39849. return this._blurVPostProcess;
  39850. };
  39851. /**
  39852. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  39853. */
  39854. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  39855. if (disableDepthRender === void 0) { disableDepthRender = false; }
  39856. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  39857. this._originalColorPostProcess = undefined;
  39858. this._ssaoPostProcess = undefined;
  39859. this._blurHPostProcess = undefined;
  39860. this._blurVPostProcess = undefined;
  39861. this._ssaoCombinePostProcess = undefined;
  39862. this._randomTexture.dispose();
  39863. if (disableDepthRender)
  39864. this._scene.disableDepthRenderer();
  39865. };
  39866. // Private Methods
  39867. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  39868. var _this = this;
  39869. var numSamples = 16;
  39870. var sampleSphere = [
  39871. 0.5381, 0.1856, -0.4319,
  39872. 0.1379, 0.2486, 0.4430,
  39873. 0.3371, 0.5679, -0.0057,
  39874. -0.6999, -0.0451, -0.0019,
  39875. 0.0689, -0.1598, -0.8547,
  39876. 0.0560, 0.0069, -0.1843,
  39877. -0.0146, 0.1402, 0.0762,
  39878. 0.0100, -0.1924, -0.0344,
  39879. -0.3577, -0.5301, -0.4358,
  39880. -0.3169, 0.1063, 0.0158,
  39881. 0.0103, -0.5869, 0.0046,
  39882. -0.0897, -0.4940, 0.3287,
  39883. 0.7119, -0.0154, -0.0918,
  39884. -0.0533, 0.0596, -0.5411,
  39885. 0.0352, -0.0631, 0.5460,
  39886. -0.4776, 0.2847, -0.0271
  39887. ];
  39888. var samplesFactor = 1.0 / numSamples;
  39889. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  39890. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  39891. "area", "fallOff", "base"
  39892. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  39893. this._ssaoPostProcess.onApply = function (effect) {
  39894. if (_this._firstUpdate) {
  39895. effect.setArray3("sampleSphere", sampleSphere);
  39896. effect.setFloat("samplesFactor", samplesFactor);
  39897. effect.setFloat("randTextureTiles", 4.0);
  39898. _this._firstUpdate = false;
  39899. }
  39900. effect.setFloat("totalStrength", _this.totalStrength);
  39901. effect.setFloat("radius", _this.radius);
  39902. effect.setFloat("area", _this.area);
  39903. effect.setFloat("fallOff", _this.fallOff);
  39904. effect.setFloat("base", _this.base);
  39905. effect.setTexture("textureSampler", _this._depthTexture);
  39906. effect.setTexture("randomSampler", _this._randomTexture);
  39907. };
  39908. };
  39909. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  39910. var _this = this;
  39911. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  39912. this._ssaoCombinePostProcess.onApply = function (effect) {
  39913. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  39914. };
  39915. };
  39916. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  39917. var size = 512;
  39918. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  39919. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  39920. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  39921. var context = this._randomTexture.getContext();
  39922. var rand = function (min, max) {
  39923. return Math.random() * (max - min) + min;
  39924. };
  39925. var randVector = BABYLON.Vector3.Zero();
  39926. for (var x = 0; x < size; x++) {
  39927. for (var y = 0; y < size; y++) {
  39928. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  39929. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  39930. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  39931. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  39932. context.fillRect(x, y, 1, 1);
  39933. }
  39934. }
  39935. this._randomTexture.update(false);
  39936. };
  39937. return SSAORenderingPipeline;
  39938. })(BABYLON.PostProcessRenderPipeline);
  39939. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  39940. })(BABYLON || (BABYLON = {}));
  39941. var BABYLON;
  39942. (function (BABYLON) {
  39943. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  39944. var VolumetricLightScatteringPostProcess = (function (_super) {
  39945. __extends(VolumetricLightScatteringPostProcess, _super);
  39946. /**
  39947. * @constructor
  39948. * @param {string} name - The post-process name
  39949. * @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)
  39950. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  39951. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  39952. * @param {number} samples - The post-process quality, default 100
  39953. * @param {number} samplingMode - The post-process filtering mode
  39954. * @param {BABYLON.Engine} engine - The babylon engine
  39955. * @param {boolean} reusable - If the post-process is reusable
  39956. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  39957. */
  39958. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  39959. var _this = this;
  39960. if (samples === void 0) { samples = 100; }
  39961. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  39962. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  39963. this._screenCoordinates = BABYLON.Vector2.Zero();
  39964. /**
  39965. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  39966. * @type {Vector3}
  39967. */
  39968. this.customMeshPosition = BABYLON.Vector3.Zero();
  39969. /**
  39970. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  39971. * @type {boolean}
  39972. */
  39973. this.useCustomMeshPosition = false;
  39974. /**
  39975. * If the post-process should inverse the light scattering direction
  39976. * @type {boolean}
  39977. */
  39978. this.invert = true;
  39979. /**
  39980. * Array containing the excluded meshes not rendered in the internal pass
  39981. */
  39982. this.excludedMeshes = new Array();
  39983. /**
  39984. * Controls the overall intensity of the post-process
  39985. * @type {number}
  39986. */
  39987. this.exposure = 0.3;
  39988. /**
  39989. * Dissipates each sample's contribution in range [0, 1]
  39990. * @type {number}
  39991. */
  39992. this.decay = 0.96815;
  39993. /**
  39994. * Controls the overall intensity of each sample
  39995. * @type {number}
  39996. */
  39997. this.weight = 0.58767;
  39998. /**
  39999. * Controls the density of each sample
  40000. * @type {number}
  40001. */
  40002. this.density = 0.926;
  40003. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  40004. var engine = scene.getEngine();
  40005. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  40006. // Configure mesh
  40007. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  40008. // Configure
  40009. this._createPass(scene, ratio.passRatio || ratio);
  40010. this.onActivate = function (camera) {
  40011. if (!_this.isSupported) {
  40012. _this.dispose(camera);
  40013. }
  40014. _this.onActivate = null;
  40015. };
  40016. this.onApply = function (effect) {
  40017. _this._updateMeshScreenCoordinates(scene);
  40018. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  40019. effect.setFloat("exposure", _this.exposure);
  40020. effect.setFloat("decay", _this.decay);
  40021. effect.setFloat("weight", _this.weight);
  40022. effect.setFloat("density", _this.density);
  40023. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  40024. };
  40025. }
  40026. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  40027. get: function () {
  40028. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  40029. return false;
  40030. },
  40031. set: function (useDiffuseColor) {
  40032. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  40033. },
  40034. enumerable: true,
  40035. configurable: true
  40036. });
  40037. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  40038. var mesh = subMesh.getMesh();
  40039. // Render this.mesh as default
  40040. if (mesh === this.mesh) {
  40041. return mesh.material.isReady(mesh);
  40042. }
  40043. var defines = [];
  40044. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40045. var material = subMesh.getMaterial();
  40046. var needUV = false;
  40047. // Alpha test
  40048. if (material) {
  40049. if (material.needAlphaTesting()) {
  40050. defines.push("#define ALPHATEST");
  40051. }
  40052. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  40053. attribs.push(BABYLON.VertexBuffer.UVKind);
  40054. defines.push("#define UV1");
  40055. }
  40056. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  40057. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40058. defines.push("#define UV2");
  40059. }
  40060. }
  40061. // Bones
  40062. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  40063. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40064. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40065. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  40066. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  40067. }
  40068. else {
  40069. defines.push("#define NUM_BONE_INFLUENCERS 0");
  40070. }
  40071. // Instances
  40072. if (useInstances) {
  40073. defines.push("#define INSTANCES");
  40074. attribs.push("world0");
  40075. attribs.push("world1");
  40076. attribs.push("world2");
  40077. attribs.push("world3");
  40078. }
  40079. // Get correct effect
  40080. var join = defines.join("\n");
  40081. if (this._cachedDefines !== join) {
  40082. this._cachedDefines = join;
  40083. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  40084. }
  40085. return this._volumetricLightScatteringPass.isReady();
  40086. };
  40087. /**
  40088. * Sets the new light position for light scattering effect
  40089. * @param {BABYLON.Vector3} The new custom light position
  40090. */
  40091. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  40092. this.customMeshPosition = position;
  40093. };
  40094. /**
  40095. * Returns the light position for light scattering effect
  40096. * @return {BABYLON.Vector3} The custom light position
  40097. */
  40098. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  40099. return this.customMeshPosition;
  40100. };
  40101. /**
  40102. * Disposes the internal assets and detaches the post-process from the camera
  40103. */
  40104. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  40105. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  40106. if (rttIndex !== -1) {
  40107. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  40108. }
  40109. this._volumetricLightScatteringRTT.dispose();
  40110. _super.prototype.dispose.call(this, camera);
  40111. };
  40112. /**
  40113. * Returns the render target texture used by the post-process
  40114. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  40115. */
  40116. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  40117. return this._volumetricLightScatteringRTT;
  40118. };
  40119. // Private methods
  40120. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  40121. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  40122. return true;
  40123. }
  40124. return false;
  40125. };
  40126. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  40127. var _this = this;
  40128. var engine = scene.getEngine();
  40129. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  40130. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40131. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40132. this._volumetricLightScatteringRTT.renderList = null;
  40133. this._volumetricLightScatteringRTT.renderParticles = false;
  40134. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  40135. // Custom render function for submeshes
  40136. var renderSubMesh = function (subMesh) {
  40137. var mesh = subMesh.getRenderingMesh();
  40138. if (_this._meshExcluded(mesh)) {
  40139. return;
  40140. }
  40141. var scene = mesh.getScene();
  40142. var engine = scene.getEngine();
  40143. // Culling
  40144. engine.setState(subMesh.getMaterial().backFaceCulling);
  40145. // Managing instances
  40146. var batch = mesh._getInstancesRenderList(subMesh._id);
  40147. if (batch.mustReturn) {
  40148. return;
  40149. }
  40150. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  40151. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  40152. var effect = _this._volumetricLightScatteringPass;
  40153. if (mesh === _this.mesh) {
  40154. effect = subMesh.getMaterial().getEffect();
  40155. }
  40156. engine.enableEffect(effect);
  40157. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  40158. if (mesh === _this.mesh) {
  40159. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  40160. }
  40161. else {
  40162. var material = subMesh.getMaterial();
  40163. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  40164. // Alpha test
  40165. if (material && material.needAlphaTesting()) {
  40166. var alphaTexture = material.getAlphaTestTexture();
  40167. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  40168. if (alphaTexture) {
  40169. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  40170. }
  40171. }
  40172. // Bones
  40173. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  40174. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  40175. }
  40176. }
  40177. // Draw
  40178. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  40179. }
  40180. };
  40181. // Render target texture callbacks
  40182. var savedSceneClearColor;
  40183. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  40184. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  40185. savedSceneClearColor = scene.clearColor;
  40186. scene.clearColor = sceneClearColor;
  40187. };
  40188. this._volumetricLightScatteringRTT.onAfterRender = function () {
  40189. scene.clearColor = savedSceneClearColor;
  40190. };
  40191. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  40192. var engine = scene.getEngine();
  40193. var index;
  40194. for (index = 0; index < opaqueSubMeshes.length; index++) {
  40195. renderSubMesh(opaqueSubMeshes.data[index]);
  40196. }
  40197. engine.setAlphaTesting(true);
  40198. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  40199. renderSubMesh(alphaTestSubMeshes.data[index]);
  40200. }
  40201. engine.setAlphaTesting(false);
  40202. if (transparentSubMeshes.length) {
  40203. // Sort sub meshes
  40204. for (index = 0; index < transparentSubMeshes.length; index++) {
  40205. var submesh = transparentSubMeshes.data[index];
  40206. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  40207. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  40208. }
  40209. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  40210. sortedArray.sort(function (a, b) {
  40211. // Alpha index first
  40212. if (a._alphaIndex > b._alphaIndex) {
  40213. return 1;
  40214. }
  40215. if (a._alphaIndex < b._alphaIndex) {
  40216. return -1;
  40217. }
  40218. // Then distance to camera
  40219. if (a._distanceToCamera < b._distanceToCamera) {
  40220. return 1;
  40221. }
  40222. if (a._distanceToCamera > b._distanceToCamera) {
  40223. return -1;
  40224. }
  40225. return 0;
  40226. });
  40227. // Render sub meshes
  40228. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  40229. for (index = 0; index < sortedArray.length; index++) {
  40230. renderSubMesh(sortedArray[index]);
  40231. }
  40232. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40233. }
  40234. };
  40235. };
  40236. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  40237. var transform = scene.getTransformMatrix();
  40238. var meshPosition;
  40239. if (this.useCustomMeshPosition) {
  40240. meshPosition = this.customMeshPosition;
  40241. }
  40242. else if (this.attachedNode) {
  40243. meshPosition = this.attachedNode.position;
  40244. }
  40245. else {
  40246. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  40247. }
  40248. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  40249. this._screenCoordinates.x = pos.x / this._viewPort.width;
  40250. this._screenCoordinates.y = pos.y / this._viewPort.height;
  40251. if (this.invert)
  40252. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  40253. };
  40254. // Static methods
  40255. /**
  40256. * Creates a default mesh for the Volumeric Light Scattering post-process
  40257. * @param {string} The mesh name
  40258. * @param {BABYLON.Scene} The scene where to create the mesh
  40259. * @return {BABYLON.Mesh} the default mesh
  40260. */
  40261. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  40262. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  40263. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  40264. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  40265. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  40266. mesh.material = material;
  40267. return mesh;
  40268. };
  40269. __decorate([
  40270. BABYLON.serializeAsVector3()
  40271. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  40272. __decorate([
  40273. BABYLON.serialize()
  40274. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  40275. __decorate([
  40276. BABYLON.serialize()
  40277. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  40278. __decorate([
  40279. BABYLON.serializeAsMeshReference()
  40280. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  40281. __decorate([
  40282. BABYLON.serialize()
  40283. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  40284. __decorate([
  40285. BABYLON.serialize()
  40286. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  40287. __decorate([
  40288. BABYLON.serialize()
  40289. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  40290. __decorate([
  40291. BABYLON.serialize()
  40292. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  40293. __decorate([
  40294. BABYLON.serialize()
  40295. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  40296. return VolumetricLightScatteringPostProcess;
  40297. })(BABYLON.PostProcess);
  40298. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  40299. })(BABYLON || (BABYLON = {}));
  40300. // BABYLON.JS Chromatic Aberration GLSL Shader
  40301. // Author: Olivier Guyot
  40302. // Separates very slightly R, G and B colors on the edges of the screen
  40303. // Inspired by Francois Tarlier & Martins Upitis
  40304. var BABYLON;
  40305. (function (BABYLON) {
  40306. var LensRenderingPipeline = (function (_super) {
  40307. __extends(LensRenderingPipeline, _super);
  40308. /**
  40309. * @constructor
  40310. *
  40311. * Effect parameters are as follow:
  40312. * {
  40313. * chromatic_aberration: number; // from 0 to x (1 for realism)
  40314. * edge_blur: number; // from 0 to x (1 for realism)
  40315. * distortion: number; // from 0 to x (1 for realism)
  40316. * grain_amount: number; // from 0 to 1
  40317. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  40318. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  40319. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  40320. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  40321. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  40322. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  40323. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  40324. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  40325. * }
  40326. * Note: if an effect parameter is unset, effect is disabled
  40327. *
  40328. * @param {string} name - The rendering pipeline name
  40329. * @param {object} parameters - An object containing all parameters (see above)
  40330. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  40331. * @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)
  40332. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  40333. */
  40334. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  40335. var _this = this;
  40336. if (ratio === void 0) { ratio = 1.0; }
  40337. _super.call(this, scene.getEngine(), name);
  40338. // Lens effects can be of the following:
  40339. // - chromatic aberration (slight shift of RGB colors)
  40340. // - blur on the edge of the lens
  40341. // - lens distortion
  40342. // - depth-of-field blur & highlights enhancing
  40343. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  40344. // - grain effect (noise or custom texture)
  40345. // Two additional texture samplers are needed:
  40346. // - depth map (for depth-of-field)
  40347. // - grain texture
  40348. /**
  40349. * The chromatic aberration PostProcess id in the pipeline
  40350. * @type {string}
  40351. */
  40352. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  40353. /**
  40354. * The highlights enhancing PostProcess id in the pipeline
  40355. * @type {string}
  40356. */
  40357. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  40358. /**
  40359. * The depth-of-field PostProcess id in the pipeline
  40360. * @type {string}
  40361. */
  40362. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  40363. this._scene = scene;
  40364. // Fetch texture samplers
  40365. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  40366. if (parameters.grain_texture) {
  40367. this._grainTexture = parameters.grain_texture;
  40368. }
  40369. else {
  40370. this._createGrainTexture();
  40371. }
  40372. // save parameters
  40373. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  40374. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  40375. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  40376. this._distortion = parameters.distortion ? parameters.distortion : 0;
  40377. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  40378. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  40379. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  40380. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  40381. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  40382. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  40383. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  40384. // Create effects
  40385. this._createChromaticAberrationPostProcess(ratio);
  40386. this._createHighlightsPostProcess(ratio);
  40387. this._createDepthOfFieldPostProcess(ratio / 4);
  40388. // Set up pipeline
  40389. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  40390. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  40391. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  40392. if (this._highlightsGain === -1) {
  40393. this._disableEffect(this.HighlightsEnhancingEffect, null);
  40394. }
  40395. // Finish
  40396. scene.postProcessRenderPipelineManager.addPipeline(this);
  40397. if (cameras) {
  40398. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  40399. }
  40400. }
  40401. // public methods (self explanatory)
  40402. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  40403. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  40404. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  40405. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  40406. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  40407. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  40408. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  40409. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  40410. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  40411. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  40412. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  40413. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  40414. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  40415. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  40416. };
  40417. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  40418. this._highlightsPostProcess.updateEffect();
  40419. };
  40420. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  40421. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  40422. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  40423. this._highlightsGain = amount;
  40424. };
  40425. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  40426. if (this._highlightsGain === -1) {
  40427. this._highlightsGain = 1.0;
  40428. }
  40429. this._highlightsThreshold = amount;
  40430. };
  40431. LensRenderingPipeline.prototype.disableHighlights = function () {
  40432. this._highlightsGain = -1;
  40433. };
  40434. /**
  40435. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  40436. */
  40437. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  40438. if (disableDepthRender === void 0) { disableDepthRender = false; }
  40439. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  40440. this._chromaticAberrationPostProcess = undefined;
  40441. this._highlightsPostProcess = undefined;
  40442. this._depthOfFieldPostProcess = undefined;
  40443. this._grainTexture.dispose();
  40444. if (disableDepthRender)
  40445. this._scene.disableDepthRenderer();
  40446. };
  40447. // colors shifting and distortion
  40448. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  40449. var _this = this;
  40450. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  40451. [], // samplers
  40452. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  40453. this._chromaticAberrationPostProcess.onApply = function (effect) {
  40454. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  40455. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  40456. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  40457. };
  40458. };
  40459. // highlights enhancing
  40460. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  40461. var _this = this;
  40462. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  40463. [], // samplers
  40464. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  40465. this._highlightsPostProcess.onApply = function (effect) {
  40466. effect.setFloat('gain', _this._highlightsGain);
  40467. effect.setFloat('threshold', _this._highlightsThreshold);
  40468. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  40469. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  40470. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  40471. };
  40472. };
  40473. // colors shifting and distortion
  40474. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  40475. var _this = this;
  40476. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  40477. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  40478. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  40479. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  40480. this._depthOfFieldPostProcess.onApply = function (effect) {
  40481. effect.setTexture("depthSampler", _this._depthTexture);
  40482. effect.setTexture("grainSampler", _this._grainTexture);
  40483. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  40484. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  40485. effect.setFloat('grain_amount', _this._grainAmount);
  40486. effect.setBool('blur_noise', _this._blurNoise);
  40487. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  40488. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  40489. effect.setFloat('distortion', _this._distortion);
  40490. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  40491. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  40492. effect.setFloat('aperture', _this._dofAperture);
  40493. effect.setFloat('darken', _this._dofDarken);
  40494. effect.setFloat('edge_blur', _this._edgeBlur);
  40495. effect.setBool('highlights', (_this._highlightsGain !== -1));
  40496. effect.setFloat('near', _this._scene.activeCamera.minZ);
  40497. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  40498. };
  40499. };
  40500. // creates a black and white random noise texture, 512x512
  40501. LensRenderingPipeline.prototype._createGrainTexture = function () {
  40502. var size = 512;
  40503. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40504. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  40505. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  40506. var context = this._grainTexture.getContext();
  40507. var rand = function (min, max) {
  40508. return Math.random() * (max - min) + min;
  40509. };
  40510. var value;
  40511. for (var x = 0; x < size; x++) {
  40512. for (var y = 0; y < size; y++) {
  40513. value = Math.floor(rand(0.42, 0.58) * 255);
  40514. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  40515. context.fillRect(x, y, 1, 1);
  40516. }
  40517. }
  40518. this._grainTexture.update(false);
  40519. };
  40520. return LensRenderingPipeline;
  40521. })(BABYLON.PostProcessRenderPipeline);
  40522. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  40523. })(BABYLON || (BABYLON = {}));
  40524. //
  40525. // This post-process allows the modification of rendered colors by using
  40526. // a 'look-up table' (LUT). This effect is also called Color Grading.
  40527. //
  40528. // The object needs to be provided an url to a texture containing the color
  40529. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  40530. // Use an image editing software to tweak the LUT to match your needs.
  40531. //
  40532. // For an example of a color LUT, see here:
  40533. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  40534. // For explanations on color grading, see here:
  40535. // http://udn.epicgames.com/Three/ColorGrading.html
  40536. //
  40537. var BABYLON;
  40538. (function (BABYLON) {
  40539. var ColorCorrectionPostProcess = (function (_super) {
  40540. __extends(ColorCorrectionPostProcess, _super);
  40541. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  40542. var _this = this;
  40543. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  40544. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  40545. this._colorTableTexture.anisotropicFilteringLevel = 1;
  40546. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40547. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40548. this.onApply = function (effect) {
  40549. effect.setTexture("colorTable", _this._colorTableTexture);
  40550. };
  40551. }
  40552. return ColorCorrectionPostProcess;
  40553. })(BABYLON.PostProcess);
  40554. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  40555. })(BABYLON || (BABYLON = {}));
  40556. var BABYLON;
  40557. (function (BABYLON) {
  40558. var AnaglyphFreeCamera = (function (_super) {
  40559. __extends(AnaglyphFreeCamera, _super);
  40560. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  40561. _super.call(this, name, position, scene);
  40562. this.interaxialDistance = interaxialDistance;
  40563. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  40564. }
  40565. AnaglyphFreeCamera.prototype.getTypeName = function () {
  40566. return "AnaglyphFreeCamera";
  40567. };
  40568. return AnaglyphFreeCamera;
  40569. })(BABYLON.FreeCamera);
  40570. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  40571. var AnaglyphArcRotateCamera = (function (_super) {
  40572. __extends(AnaglyphArcRotateCamera, _super);
  40573. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  40574. _super.call(this, name, alpha, beta, radius, target, scene);
  40575. this.interaxialDistance = interaxialDistance;
  40576. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  40577. }
  40578. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  40579. return "AnaglyphArcRotateCamera";
  40580. };
  40581. return AnaglyphArcRotateCamera;
  40582. })(BABYLON.ArcRotateCamera);
  40583. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  40584. var AnaglyphGamepadCamera = (function (_super) {
  40585. __extends(AnaglyphGamepadCamera, _super);
  40586. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  40587. _super.call(this, name, position, scene);
  40588. this.interaxialDistance = interaxialDistance;
  40589. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  40590. }
  40591. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  40592. return "AnaglyphGamepadCamera";
  40593. };
  40594. return AnaglyphGamepadCamera;
  40595. })(BABYLON.GamepadCamera);
  40596. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  40597. var AnaglyphUniversalCamera = (function (_super) {
  40598. __extends(AnaglyphUniversalCamera, _super);
  40599. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  40600. _super.call(this, name, position, scene);
  40601. this.interaxialDistance = interaxialDistance;
  40602. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  40603. }
  40604. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  40605. return "AnaglyphUniversalCamera";
  40606. };
  40607. return AnaglyphUniversalCamera;
  40608. })(BABYLON.UniversalCamera);
  40609. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  40610. var StereoscopicFreeCamera = (function (_super) {
  40611. __extends(StereoscopicFreeCamera, _super);
  40612. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  40613. _super.call(this, name, position, scene);
  40614. this.interaxialDistance = interaxialDistance;
  40615. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  40616. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  40617. }
  40618. StereoscopicFreeCamera.prototype.getTypeName = function () {
  40619. return "StereoscopicFreeCamera";
  40620. };
  40621. return StereoscopicFreeCamera;
  40622. })(BABYLON.FreeCamera);
  40623. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  40624. var StereoscopicArcRotateCamera = (function (_super) {
  40625. __extends(StereoscopicArcRotateCamera, _super);
  40626. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  40627. _super.call(this, name, alpha, beta, radius, target, scene);
  40628. this.interaxialDistance = interaxialDistance;
  40629. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  40630. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  40631. }
  40632. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  40633. return "StereoscopicArcRotateCamera";
  40634. };
  40635. return StereoscopicArcRotateCamera;
  40636. })(BABYLON.ArcRotateCamera);
  40637. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  40638. var StereoscopicGamepadCamera = (function (_super) {
  40639. __extends(StereoscopicGamepadCamera, _super);
  40640. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  40641. _super.call(this, name, position, scene);
  40642. this.interaxialDistance = interaxialDistance;
  40643. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  40644. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  40645. }
  40646. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  40647. return "StereoscopicGamepadCamera";
  40648. };
  40649. return StereoscopicGamepadCamera;
  40650. })(BABYLON.GamepadCamera);
  40651. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  40652. var StereoscopicUniversalCamera = (function (_super) {
  40653. __extends(StereoscopicUniversalCamera, _super);
  40654. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  40655. _super.call(this, name, position, scene);
  40656. this.interaxialDistance = interaxialDistance;
  40657. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  40658. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  40659. }
  40660. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  40661. return "StereoscopicUniversalCamera";
  40662. };
  40663. return StereoscopicUniversalCamera;
  40664. })(BABYLON.UniversalCamera);
  40665. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  40666. })(BABYLON || (BABYLON = {}));
  40667. var BABYLON;
  40668. (function (BABYLON) {
  40669. var HDRRenderingPipeline = (function (_super) {
  40670. __extends(HDRRenderingPipeline, _super);
  40671. /**
  40672. * @constructor
  40673. * @param {string} name - The rendering pipeline name
  40674. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  40675. * @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)
  40676. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  40677. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  40678. */
  40679. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  40680. var _this = this;
  40681. if (originalPostProcess === void 0) { originalPostProcess = null; }
  40682. _super.call(this, scene.getEngine(), name);
  40683. /**
  40684. * Public members
  40685. */
  40686. // Gaussian Blur
  40687. /**
  40688. * Gaussian blur coefficient
  40689. * @type {number}
  40690. */
  40691. this.gaussCoeff = 0.3;
  40692. /**
  40693. * Gaussian blur mean
  40694. * @type {number}
  40695. */
  40696. this.gaussMean = 1.0;
  40697. /**
  40698. * Gaussian blur standard deviation
  40699. * @type {number}
  40700. */
  40701. this.gaussStandDev = 0.8;
  40702. /**
  40703. * Gaussian blur multiplier. Multiplies the blur effect
  40704. * @type {number}
  40705. */
  40706. this.gaussMultiplier = 4.0;
  40707. // HDR
  40708. /**
  40709. * Exposure, controls the overall intensity of the pipeline
  40710. * @type {number}
  40711. */
  40712. this.exposure = 1.0;
  40713. /**
  40714. * Minimum luminance that the post-process can output. Luminance is >= 0
  40715. * @type {number}
  40716. */
  40717. this.minimumLuminance = 1.0;
  40718. /**
  40719. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  40720. * @type {number}
  40721. */
  40722. this.maximumLuminance = 1e20;
  40723. /**
  40724. * Increase rate for luminance: eye adaptation speed to dark
  40725. * @type {number}
  40726. */
  40727. this.luminanceIncreaserate = 0.5;
  40728. /**
  40729. * Decrease rate for luminance: eye adaptation speed to bright
  40730. * @type {number}
  40731. */
  40732. this.luminanceDecreaseRate = 0.5;
  40733. // Bright pass
  40734. /**
  40735. * Minimum luminance needed to compute HDR
  40736. * @type {number}
  40737. */
  40738. this.brightThreshold = 0.8;
  40739. this._needUpdate = true;
  40740. this._scene = scene;
  40741. // Bright pass
  40742. this._createBrightPassPostProcess(scene, ratio);
  40743. // Down sample X4
  40744. this._createDownSampleX4PostProcess(scene, ratio);
  40745. // Create gaussian blur post-processes
  40746. this._createGaussianBlurPostProcess(scene, ratio);
  40747. // Texture adder
  40748. this._createTextureAdderPostProcess(scene, ratio);
  40749. // Luminance generator
  40750. this._createLuminanceGeneratorPostProcess(scene);
  40751. // HDR
  40752. this._createHDRPostProcess(scene, ratio);
  40753. // Pass postprocess
  40754. if (originalPostProcess === null) {
  40755. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  40756. }
  40757. else {
  40758. this._originalPostProcess = originalPostProcess;
  40759. }
  40760. // Configure pipeline
  40761. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  40762. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  40763. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  40764. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  40765. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  40766. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  40767. var addDownSamplerPostProcess = function (id) {
  40768. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  40769. };
  40770. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  40771. addDownSamplerPostProcess(i);
  40772. }
  40773. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  40774. // Finish
  40775. scene.postProcessRenderPipelineManager.addPipeline(this);
  40776. if (cameras !== null) {
  40777. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  40778. }
  40779. this.update();
  40780. }
  40781. /**
  40782. * Tells the pipeline to update its post-processes
  40783. */
  40784. HDRRenderingPipeline.prototype.update = function () {
  40785. this._needUpdate = true;
  40786. };
  40787. /**
  40788. * Returns the current calculated luminance
  40789. */
  40790. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  40791. return this._hdrCurrentLuminance;
  40792. };
  40793. /**
  40794. * Returns the currently drawn luminance
  40795. */
  40796. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  40797. return this._hdrOutputLuminance;
  40798. };
  40799. /**
  40800. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  40801. */
  40802. HDRRenderingPipeline.prototype.dispose = function () {
  40803. this._originalPostProcess = undefined;
  40804. this._brightPassPostProcess = undefined;
  40805. this._downSampleX4PostProcess = undefined;
  40806. this._guassianBlurHPostProcess = undefined;
  40807. this._guassianBlurVPostProcess = undefined;
  40808. this._textureAdderPostProcess = undefined;
  40809. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  40810. this._downSamplePostProcesses[i] = undefined;
  40811. }
  40812. this._hdrPostProcess = undefined;
  40813. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  40814. };
  40815. /**
  40816. * Creates the HDR post-process and computes the luminance adaptation
  40817. */
  40818. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  40819. var _this = this;
  40820. var hdrLastLuminance = 0.0;
  40821. this._hdrOutputLuminance = -1.0;
  40822. this._hdrCurrentLuminance = 1.0;
  40823. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  40824. this._hdrPostProcess.onApply = function (effect) {
  40825. if (_this._hdrOutputLuminance < 0.0) {
  40826. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  40827. }
  40828. else {
  40829. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  40830. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  40831. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  40832. }
  40833. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  40834. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  40835. }
  40836. else {
  40837. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  40838. }
  40839. }
  40840. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  40841. hdrLastLuminance += scene.getEngine().getDeltaTime();
  40842. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  40843. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  40844. effect.setFloat("exposure", _this.exposure);
  40845. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  40846. _this._needUpdate = false;
  40847. };
  40848. };
  40849. /**
  40850. * Texture Adder post-process
  40851. */
  40852. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  40853. var _this = this;
  40854. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  40855. this._textureAdderPostProcess.onApply = function (effect) {
  40856. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  40857. };
  40858. };
  40859. /**
  40860. * Down sample X4 post-process
  40861. */
  40862. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  40863. var _this = this;
  40864. var downSampleX4Offsets = new Array(32);
  40865. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  40866. this._downSampleX4PostProcess.onApply = function (effect) {
  40867. if (_this._needUpdate) {
  40868. var id = 0;
  40869. for (var i = -2; i < 2; i++) {
  40870. for (var j = -2; j < 2; j++) {
  40871. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  40872. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  40873. id += 2;
  40874. }
  40875. }
  40876. }
  40877. effect.setArray2("dsOffsets", downSampleX4Offsets);
  40878. };
  40879. };
  40880. /**
  40881. * Bright pass post-process
  40882. */
  40883. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  40884. var _this = this;
  40885. var brightOffsets = new Array(8);
  40886. var brightPassCallback = function (effect) {
  40887. if (_this._needUpdate) {
  40888. var sU = (1.0 / _this._brightPassPostProcess.width);
  40889. var sV = (1.0 / _this._brightPassPostProcess.height);
  40890. brightOffsets[0] = -0.5 * sU;
  40891. brightOffsets[1] = 0.5 * sV;
  40892. brightOffsets[2] = 0.5 * sU;
  40893. brightOffsets[3] = 0.5 * sV;
  40894. brightOffsets[4] = -0.5 * sU;
  40895. brightOffsets[5] = -0.5 * sV;
  40896. brightOffsets[6] = 0.5 * sU;
  40897. brightOffsets[7] = -0.5 * sV;
  40898. }
  40899. effect.setArray2("dsOffsets", brightOffsets);
  40900. effect.setFloat("brightThreshold", _this.brightThreshold);
  40901. };
  40902. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  40903. this._brightPassPostProcess.onApply = brightPassCallback;
  40904. };
  40905. /**
  40906. * Luminance generator. Creates the luminance post-process and down sample post-processes
  40907. */
  40908. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  40909. var _this = this;
  40910. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  40911. var luminanceOffsets = new Array(8);
  40912. var downSampleOffsets = new Array(18);
  40913. var halfDestPixelSize;
  40914. this._downSamplePostProcesses = new Array(lumSteps);
  40915. // Utils for luminance
  40916. var luminanceUpdateSourceOffsets = function (width, height) {
  40917. var sU = (1.0 / width);
  40918. var sV = (1.0 / height);
  40919. luminanceOffsets[0] = -0.5 * sU;
  40920. luminanceOffsets[1] = 0.5 * sV;
  40921. luminanceOffsets[2] = 0.5 * sU;
  40922. luminanceOffsets[3] = 0.5 * sV;
  40923. luminanceOffsets[4] = -0.5 * sU;
  40924. luminanceOffsets[5] = -0.5 * sV;
  40925. luminanceOffsets[6] = 0.5 * sU;
  40926. luminanceOffsets[7] = -0.5 * sV;
  40927. };
  40928. var luminanceUpdateDestOffsets = function (width, height) {
  40929. var id = 0;
  40930. for (var x = -1; x < 2; x++) {
  40931. for (var y = -1; y < 2; y++) {
  40932. downSampleOffsets[id] = (x) / width;
  40933. downSampleOffsets[id + 1] = (y) / height;
  40934. id += 2;
  40935. }
  40936. }
  40937. };
  40938. // Luminance callback
  40939. var luminanceCallback = function (effect) {
  40940. if (_this._needUpdate) {
  40941. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  40942. }
  40943. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  40944. effect.setArray2("lumOffsets", luminanceOffsets);
  40945. };
  40946. // Down sample callbacks
  40947. var downSampleCallback = function (indice) {
  40948. var i = indice;
  40949. return function (effect) {
  40950. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  40951. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  40952. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  40953. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  40954. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  40955. effect.setArray2("dsOffsets", downSampleOffsets);
  40956. };
  40957. };
  40958. var downSampleAfterRenderCallback = function (effect) {
  40959. // Unpack result
  40960. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  40961. 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);
  40962. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  40963. };
  40964. // Create luminance post-process
  40965. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  40966. 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);
  40967. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  40968. // Create down sample post-processes
  40969. for (var i = lumSteps - 2; i >= 0; i--) {
  40970. var length = Math.pow(3, i);
  40971. ratio = { width: length, height: length };
  40972. var defines = "#define DOWN_SAMPLE\n";
  40973. if (i === 0) {
  40974. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  40975. }
  40976. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  40977. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  40978. if (i === 0) {
  40979. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  40980. }
  40981. }
  40982. };
  40983. /**
  40984. * Gaussian blur post-processes. Horizontal and Vertical
  40985. */
  40986. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  40987. var _this = this;
  40988. var blurOffsetsW = new Array(9);
  40989. var blurOffsetsH = new Array(9);
  40990. var blurWeights = new Array(9);
  40991. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  40992. // Utils for gaussian blur
  40993. var calculateBlurOffsets = function (height) {
  40994. var lastOutputDimensions = {
  40995. width: scene.getEngine().getRenderWidth(),
  40996. height: scene.getEngine().getRenderHeight()
  40997. };
  40998. for (var i = 0; i < 9; i++) {
  40999. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  41000. if (height) {
  41001. blurOffsetsH[i] = value;
  41002. }
  41003. else {
  41004. blurOffsetsW[i] = value;
  41005. }
  41006. }
  41007. };
  41008. var calculateWeights = function () {
  41009. var x = 0.0;
  41010. for (var i = 0; i < 9; i++) {
  41011. x = (i - 4.0) / 4.0;
  41012. 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));
  41013. }
  41014. };
  41015. // Callback
  41016. var gaussianBlurCallback = function (height) {
  41017. return function (effect) {
  41018. if (_this._needUpdate) {
  41019. calculateWeights();
  41020. calculateBlurOffsets(height);
  41021. }
  41022. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  41023. effect.setArray("blurWeights", blurWeights);
  41024. effect.setFloat("multiplier", _this.gaussMultiplier);
  41025. };
  41026. };
  41027. // Create horizontal gaussian blur post-processes
  41028. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  41029. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  41030. // Create vertical gaussian blur post-process
  41031. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  41032. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  41033. };
  41034. // Luminance generator
  41035. HDRRenderingPipeline.LUM_STEPS = 6;
  41036. return HDRRenderingPipeline;
  41037. })(BABYLON.PostProcessRenderPipeline);
  41038. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  41039. })(BABYLON || (BABYLON = {}));
  41040. var BABYLON;
  41041. (function (BABYLON) {
  41042. var FaceAdjacencies = (function () {
  41043. function FaceAdjacencies() {
  41044. this.edges = new Array();
  41045. this.edgesConnectedCount = 0;
  41046. }
  41047. return FaceAdjacencies;
  41048. })();
  41049. var EdgesRenderer = (function () {
  41050. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  41051. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  41052. if (epsilon === void 0) { epsilon = 0.95; }
  41053. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  41054. this.edgesWidthScalerForOrthographic = 1000.0;
  41055. this.edgesWidthScalerForPerspective = 50.0;
  41056. this._linesPositions = new Array();
  41057. this._linesNormals = new Array();
  41058. this._linesIndices = new Array();
  41059. this._buffers = new Array();
  41060. this._checkVerticesInsteadOfIndices = false;
  41061. this._source = source;
  41062. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  41063. this._epsilon = epsilon;
  41064. this._prepareRessources();
  41065. this._generateEdgesLines();
  41066. }
  41067. EdgesRenderer.prototype._prepareRessources = function () {
  41068. if (this._lineShader) {
  41069. return;
  41070. }
  41071. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  41072. attributes: ["position", "normal"],
  41073. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  41074. });
  41075. this._lineShader.disableDepthWrite = true;
  41076. this._lineShader.backFaceCulling = false;
  41077. };
  41078. EdgesRenderer.prototype.dispose = function () {
  41079. this._vb0.dispose();
  41080. this._vb1.dispose();
  41081. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  41082. this._lineShader.dispose();
  41083. };
  41084. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  41085. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  41086. return 0;
  41087. }
  41088. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  41089. return 1;
  41090. }
  41091. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  41092. return 2;
  41093. }
  41094. return -1;
  41095. };
  41096. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  41097. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  41098. return 0;
  41099. }
  41100. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  41101. return 1;
  41102. }
  41103. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  41104. return 2;
  41105. }
  41106. return -1;
  41107. };
  41108. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  41109. var needToCreateLine;
  41110. if (edge === undefined) {
  41111. needToCreateLine = true;
  41112. }
  41113. else {
  41114. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  41115. needToCreateLine = dotProduct < this._epsilon;
  41116. }
  41117. if (needToCreateLine) {
  41118. var offset = this._linesPositions.length / 3;
  41119. var normal = p0.subtract(p1);
  41120. normal.normalize();
  41121. // Positions
  41122. this._linesPositions.push(p0.x);
  41123. this._linesPositions.push(p0.y);
  41124. this._linesPositions.push(p0.z);
  41125. this._linesPositions.push(p0.x);
  41126. this._linesPositions.push(p0.y);
  41127. this._linesPositions.push(p0.z);
  41128. this._linesPositions.push(p1.x);
  41129. this._linesPositions.push(p1.y);
  41130. this._linesPositions.push(p1.z);
  41131. this._linesPositions.push(p1.x);
  41132. this._linesPositions.push(p1.y);
  41133. this._linesPositions.push(p1.z);
  41134. // Normals
  41135. this._linesNormals.push(p1.x);
  41136. this._linesNormals.push(p1.y);
  41137. this._linesNormals.push(p1.z);
  41138. this._linesNormals.push(-1);
  41139. this._linesNormals.push(p1.x);
  41140. this._linesNormals.push(p1.y);
  41141. this._linesNormals.push(p1.z);
  41142. this._linesNormals.push(1);
  41143. this._linesNormals.push(p0.x);
  41144. this._linesNormals.push(p0.y);
  41145. this._linesNormals.push(p0.z);
  41146. this._linesNormals.push(-1);
  41147. this._linesNormals.push(p0.x);
  41148. this._linesNormals.push(p0.y);
  41149. this._linesNormals.push(p0.z);
  41150. this._linesNormals.push(1);
  41151. // Indices
  41152. this._linesIndices.push(offset);
  41153. this._linesIndices.push(offset + 1);
  41154. this._linesIndices.push(offset + 2);
  41155. this._linesIndices.push(offset);
  41156. this._linesIndices.push(offset + 2);
  41157. this._linesIndices.push(offset + 3);
  41158. }
  41159. };
  41160. EdgesRenderer.prototype._generateEdgesLines = function () {
  41161. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41162. var indices = this._source.getIndices();
  41163. // First let's find adjacencies
  41164. var adjacencies = new Array();
  41165. var faceNormals = new Array();
  41166. var index;
  41167. var faceAdjacencies;
  41168. // Prepare faces
  41169. for (index = 0; index < indices.length; index += 3) {
  41170. faceAdjacencies = new FaceAdjacencies();
  41171. var p0Index = indices[index];
  41172. var p1Index = indices[index + 1];
  41173. var p2Index = indices[index + 2];
  41174. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  41175. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  41176. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  41177. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  41178. faceNormal.normalize();
  41179. faceNormals.push(faceNormal);
  41180. adjacencies.push(faceAdjacencies);
  41181. }
  41182. // Scan
  41183. for (index = 0; index < adjacencies.length; index++) {
  41184. faceAdjacencies = adjacencies[index];
  41185. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  41186. var otherFaceAdjacencies = adjacencies[otherIndex];
  41187. if (faceAdjacencies.edgesConnectedCount === 3) {
  41188. break;
  41189. }
  41190. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  41191. continue;
  41192. }
  41193. var otherP0 = indices[otherIndex * 3];
  41194. var otherP1 = indices[otherIndex * 3 + 1];
  41195. var otherP2 = indices[otherIndex * 3 + 2];
  41196. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  41197. var otherEdgeIndex;
  41198. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  41199. continue;
  41200. }
  41201. switch (edgeIndex) {
  41202. case 0:
  41203. if (this._checkVerticesInsteadOfIndices) {
  41204. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  41205. }
  41206. else {
  41207. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  41208. }
  41209. break;
  41210. case 1:
  41211. if (this._checkVerticesInsteadOfIndices) {
  41212. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  41213. }
  41214. else {
  41215. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  41216. }
  41217. break;
  41218. case 2:
  41219. if (this._checkVerticesInsteadOfIndices) {
  41220. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  41221. }
  41222. else {
  41223. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  41224. }
  41225. break;
  41226. }
  41227. if (otherEdgeIndex === -1) {
  41228. continue;
  41229. }
  41230. faceAdjacencies.edges[edgeIndex] = otherIndex;
  41231. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  41232. faceAdjacencies.edgesConnectedCount++;
  41233. otherFaceAdjacencies.edgesConnectedCount++;
  41234. if (faceAdjacencies.edgesConnectedCount === 3) {
  41235. break;
  41236. }
  41237. }
  41238. }
  41239. }
  41240. // Create lines
  41241. for (index = 0; index < adjacencies.length; index++) {
  41242. // 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
  41243. var current = adjacencies[index];
  41244. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  41245. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  41246. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  41247. }
  41248. // Merge into a single mesh
  41249. var engine = this._source.getScene().getEngine();
  41250. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  41251. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  41252. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  41253. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  41254. this._ib = engine.createIndexBuffer(this._linesIndices);
  41255. this._indicesCount = this._linesIndices.length;
  41256. };
  41257. EdgesRenderer.prototype.render = function () {
  41258. if (!this._lineShader.isReady()) {
  41259. return;
  41260. }
  41261. var scene = this._source.getScene();
  41262. var engine = scene.getEngine();
  41263. this._lineShader._preBind();
  41264. // VBOs
  41265. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  41266. scene.resetCachedMaterial();
  41267. this._lineShader.setColor4("color", this._source.edgesColor);
  41268. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  41269. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  41270. }
  41271. else {
  41272. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  41273. }
  41274. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  41275. this._lineShader.bind(this._source.getWorldMatrix());
  41276. // Draw order
  41277. engine.draw(true, 0, this._indicesCount);
  41278. this._lineShader.unbind();
  41279. engine.setDepthWrite(true);
  41280. };
  41281. return EdgesRenderer;
  41282. })();
  41283. BABYLON.EdgesRenderer = EdgesRenderer;
  41284. })(BABYLON || (BABYLON = {}));
  41285. var BABYLON;
  41286. (function (BABYLON) {
  41287. (function (TonemappingOperator) {
  41288. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  41289. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  41290. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  41291. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  41292. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  41293. var TonemappingOperator = BABYLON.TonemappingOperator;
  41294. ;
  41295. var TonemapPostProcess = (function (_super) {
  41296. __extends(TonemapPostProcess, _super);
  41297. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  41298. var _this = this;
  41299. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  41300. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41301. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  41302. this._operator = _operator;
  41303. this.exposureAdjustment = exposureAdjustment;
  41304. var defines = "#define ";
  41305. if (this._operator === TonemappingOperator.Hable)
  41306. defines += "HABLE_TONEMAPPING";
  41307. else if (this._operator === TonemappingOperator.Reinhard)
  41308. defines += "REINHARD_TONEMAPPING";
  41309. else if (this._operator === TonemappingOperator.HejiDawson)
  41310. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  41311. else if (this._operator === TonemappingOperator.Photographic)
  41312. defines += "PHOTOGRAPHIC_TONEMAPPING";
  41313. //sadly a second call to create the effect.
  41314. this.updateEffect(defines);
  41315. this.onApply = function (effect) {
  41316. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  41317. };
  41318. }
  41319. return TonemapPostProcess;
  41320. })(BABYLON.PostProcess);
  41321. BABYLON.TonemapPostProcess = TonemapPostProcess;
  41322. })(BABYLON || (BABYLON = {}));
  41323. var BABYLON;
  41324. (function (BABYLON) {
  41325. var ReflectionProbe = (function () {
  41326. function ReflectionProbe(name, size, scene, generateMipMaps) {
  41327. var _this = this;
  41328. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41329. this.name = name;
  41330. this._viewMatrix = BABYLON.Matrix.Identity();
  41331. this._target = BABYLON.Vector3.Zero();
  41332. this._add = BABYLON.Vector3.Zero();
  41333. this.position = BABYLON.Vector3.Zero();
  41334. this._scene = scene;
  41335. this._scene.reflectionProbes.push(this);
  41336. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  41337. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  41338. switch (faceIndex) {
  41339. case 0:
  41340. _this._add.copyFromFloats(1, 0, 0);
  41341. break;
  41342. case 1:
  41343. _this._add.copyFromFloats(-1, 0, 0);
  41344. break;
  41345. case 2:
  41346. _this._add.copyFromFloats(0, -1, 0);
  41347. break;
  41348. case 3:
  41349. _this._add.copyFromFloats(0, 1, 0);
  41350. break;
  41351. case 4:
  41352. _this._add.copyFromFloats(0, 0, 1);
  41353. break;
  41354. case 5:
  41355. _this._add.copyFromFloats(0, 0, -1);
  41356. break;
  41357. }
  41358. if (_this._attachedMesh) {
  41359. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  41360. }
  41361. _this.position.addToRef(_this._add, _this._target);
  41362. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  41363. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  41364. };
  41365. this._renderTargetTexture.onAfterUnbind = function () {
  41366. scene.updateTransformMatrix(true);
  41367. };
  41368. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  41369. }
  41370. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  41371. get: function () {
  41372. return this._renderTargetTexture.refreshRate;
  41373. },
  41374. set: function (value) {
  41375. this._renderTargetTexture.refreshRate = value;
  41376. },
  41377. enumerable: true,
  41378. configurable: true
  41379. });
  41380. ReflectionProbe.prototype.getScene = function () {
  41381. return this._scene;
  41382. };
  41383. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  41384. get: function () {
  41385. return this._renderTargetTexture;
  41386. },
  41387. enumerable: true,
  41388. configurable: true
  41389. });
  41390. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  41391. get: function () {
  41392. return this._renderTargetTexture.renderList;
  41393. },
  41394. enumerable: true,
  41395. configurable: true
  41396. });
  41397. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  41398. this._attachedMesh = mesh;
  41399. };
  41400. ReflectionProbe.prototype.dispose = function () {
  41401. var index = this._scene.reflectionProbes.indexOf(this);
  41402. if (index !== -1) {
  41403. // Remove from the scene if found
  41404. this._scene.reflectionProbes.splice(index, 1);
  41405. }
  41406. if (this._renderTargetTexture) {
  41407. this._renderTargetTexture.dispose();
  41408. this._renderTargetTexture = null;
  41409. }
  41410. };
  41411. return ReflectionProbe;
  41412. })();
  41413. BABYLON.ReflectionProbe = ReflectionProbe;
  41414. })(BABYLON || (BABYLON = {}));
  41415. var BABYLON;
  41416. (function (BABYLON) {
  41417. var SolidParticle = (function () {
  41418. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  41419. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  41420. this.position = BABYLON.Vector3.Zero(); // position
  41421. this.rotation = BABYLON.Vector3.Zero(); // rotation
  41422. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  41423. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  41424. this.velocity = BABYLON.Vector3.Zero(); // velocity
  41425. this.alive = true; // alive
  41426. this.idx = particleIndex;
  41427. this._pos = positionIndex;
  41428. this._model = model;
  41429. this.shapeId = shapeId;
  41430. this.idxInShape = idxInShape;
  41431. }
  41432. Object.defineProperty(SolidParticle.prototype, "scale", {
  41433. //legacy support, changed scale to scaling
  41434. get: function () {
  41435. return this.scaling;
  41436. },
  41437. set: function (scale) {
  41438. this.scaling = scale;
  41439. },
  41440. enumerable: true,
  41441. configurable: true
  41442. });
  41443. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  41444. //legacy support, changed quaternion to rotationQuaternion
  41445. get: function () {
  41446. return this.rotationQuaternion;
  41447. },
  41448. set: function (q) {
  41449. this.rotationQuaternion = q;
  41450. },
  41451. enumerable: true,
  41452. configurable: true
  41453. });
  41454. return SolidParticle;
  41455. })();
  41456. BABYLON.SolidParticle = SolidParticle;
  41457. var ModelShape = (function () {
  41458. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  41459. this.shapeID = id;
  41460. this._shape = shape;
  41461. this._shapeUV = shapeUV;
  41462. this._positionFunction = posFunction;
  41463. this._vertexFunction = vtxFunction;
  41464. }
  41465. return ModelShape;
  41466. })();
  41467. BABYLON.ModelShape = ModelShape;
  41468. })(BABYLON || (BABYLON = {}));
  41469. var BABYLON;
  41470. (function (BABYLON) {
  41471. /**
  41472. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  41473. */
  41474. var SolidParticleSystem = (function () {
  41475. /**
  41476. * Creates a SPS (Solid Particle System) object.
  41477. * `name` (String) is the SPS name, this will be the underlying mesh name.
  41478. * `scene` (Scene) is the scene in which the SPS is added.
  41479. * `updatableè (default true) : if the SPS must be updatable or immutable.
  41480. * `isPickable` (default false) : if the solid particles must be pickable.
  41481. */
  41482. function SolidParticleSystem(name, scene, options) {
  41483. // public members
  41484. /**
  41485. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  41486. * Example : var p = SPS.particles[i];
  41487. */
  41488. this.particles = new Array();
  41489. /**
  41490. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  41491. */
  41492. this.nbParticles = 0;
  41493. /**
  41494. * If the particles must ever face the camera (default false). Useful for planar particles.
  41495. */
  41496. this.billboard = false;
  41497. /**
  41498. * This a counter ofr your own usage. It's not set by any SPS functions.
  41499. */
  41500. this.counter = 0;
  41501. /**
  41502. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  41503. * Please read : http://doc.babylonjs.com/tutorials/Solid_Particle_System#garbage-collector-concerns
  41504. */
  41505. this.vars = {};
  41506. this._positions = new Array();
  41507. this._indices = new Array();
  41508. this._normals = new Array();
  41509. this._colors = new Array();
  41510. this._uvs = new Array();
  41511. this._index = 0; // indices index
  41512. this._updatable = true;
  41513. this._pickable = false;
  41514. this._isVisibilityBoxLocked = false;
  41515. this._alwaysVisible = false;
  41516. this._shapeCounter = 0;
  41517. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  41518. this._color = new BABYLON.Color4(0, 0, 0, 0);
  41519. this._computeParticleColor = true;
  41520. this._computeParticleTexture = true;
  41521. this._computeParticleRotation = true;
  41522. this._computeParticleVertex = false;
  41523. this._computeBoundingBox = false;
  41524. this._cam_axisZ = BABYLON.Vector3.Zero();
  41525. this._cam_axisY = BABYLON.Vector3.Zero();
  41526. this._cam_axisX = BABYLON.Vector3.Zero();
  41527. this._axisX = BABYLON.Axis.X;
  41528. this._axisY = BABYLON.Axis.Y;
  41529. this._axisZ = BABYLON.Axis.Z;
  41530. this._fakeCamPos = BABYLON.Vector3.Zero();
  41531. this._rotMatrix = new BABYLON.Matrix();
  41532. this._invertMatrix = new BABYLON.Matrix();
  41533. this._rotated = BABYLON.Vector3.Zero();
  41534. this._quaternion = new BABYLON.Quaternion();
  41535. this._vertex = BABYLON.Vector3.Zero();
  41536. this._normal = BABYLON.Vector3.Zero();
  41537. this._yaw = 0.0;
  41538. this._pitch = 0.0;
  41539. this._roll = 0.0;
  41540. this._halfroll = 0.0;
  41541. this._halfpitch = 0.0;
  41542. this._halfyaw = 0.0;
  41543. this._sinRoll = 0.0;
  41544. this._cosRoll = 0.0;
  41545. this._sinPitch = 0.0;
  41546. this._cosPitch = 0.0;
  41547. this._sinYaw = 0.0;
  41548. this._cosYaw = 0.0;
  41549. this._w = 0.0;
  41550. this._minimum = BABYLON.Tmp.Vector3[0];
  41551. this._maximum = BABYLON.Tmp.Vector3[1];
  41552. this.name = name;
  41553. this._scene = scene;
  41554. this._camera = scene.activeCamera;
  41555. this._pickable = options ? options.isPickable : false;
  41556. if (options && options.updatable) {
  41557. this._updatable = options.updatable;
  41558. }
  41559. else {
  41560. this._updatable = true;
  41561. }
  41562. if (this._pickable) {
  41563. this.pickedParticles = [];
  41564. }
  41565. }
  41566. /**
  41567. * Builds the SPS underlying mesh. Returns a standard Mesh.
  41568. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  41569. */
  41570. SolidParticleSystem.prototype.buildMesh = function () {
  41571. if (this.nbParticles === 0) {
  41572. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  41573. this.addShape(triangle, 1);
  41574. triangle.dispose();
  41575. }
  41576. this._positions32 = new Float32Array(this._positions);
  41577. this._uvs32 = new Float32Array(this._uvs);
  41578. this._colors32 = new Float32Array(this._colors);
  41579. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  41580. this._normals32 = new Float32Array(this._normals);
  41581. this._fixedNormal32 = new Float32Array(this._normals);
  41582. var vertexData = new BABYLON.VertexData();
  41583. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  41584. vertexData.indices = this._indices;
  41585. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  41586. if (this._uvs32) {
  41587. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  41588. ;
  41589. }
  41590. if (this._colors32) {
  41591. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  41592. }
  41593. var mesh = new BABYLON.Mesh(this.name, this._scene);
  41594. vertexData.applyToMesh(mesh, this._updatable);
  41595. this.mesh = mesh;
  41596. this.mesh.isPickable = this._pickable;
  41597. // free memory
  41598. this._positions = null;
  41599. this._normals = null;
  41600. this._uvs = null;
  41601. this._colors = null;
  41602. if (!this._updatable) {
  41603. this.particles.length = 0;
  41604. }
  41605. return mesh;
  41606. };
  41607. /**
  41608. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  41609. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  41610. * Thus the particles generated from `digest()` have their property `position` set yet.
  41611. * `mesh` (`Mesh`) is the mesh to be digested
  41612. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  41613. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  41614. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  41615. */
  41616. SolidParticleSystem.prototype.digest = function (mesh, options) {
  41617. var size = (options && options.facetNb) || 1;
  41618. var number = (options && options.number);
  41619. var delta = (options && options.delta) || 0;
  41620. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41621. var meshInd = mesh.getIndices();
  41622. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41623. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41624. var f = 0; // facet counter
  41625. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  41626. // compute size from number
  41627. if (number) {
  41628. number = (number > totalFacets) ? totalFacets : number;
  41629. size = Math.round(totalFacets / number);
  41630. delta = 0;
  41631. }
  41632. else {
  41633. size = (size > totalFacets) ? totalFacets : size;
  41634. }
  41635. var facetPos = []; // submesh positions
  41636. var facetInd = []; // submesh indices
  41637. var facetUV = []; // submesh UV
  41638. var facetCol = []; // submesh colors
  41639. var barycenter = BABYLON.Tmp.Vector3[0];
  41640. var rand;
  41641. var sizeO = size;
  41642. while (f < totalFacets) {
  41643. size = sizeO + Math.floor((1 + delta) * Math.random());
  41644. if (f > totalFacets - size) {
  41645. size = totalFacets - f;
  41646. }
  41647. // reset temp arrays
  41648. facetPos.length = 0;
  41649. facetInd.length = 0;
  41650. facetUV.length = 0;
  41651. facetCol.length = 0;
  41652. // iterate over "size" facets
  41653. var fi = 0;
  41654. for (var j = f * 3; j < (f + size) * 3; j++) {
  41655. facetInd.push(fi);
  41656. var i = meshInd[j];
  41657. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  41658. if (meshUV) {
  41659. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  41660. }
  41661. if (meshCol) {
  41662. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  41663. }
  41664. fi++;
  41665. }
  41666. // create a model shape for each single particle
  41667. var idx = this.nbParticles;
  41668. var shape = this._posToShape(facetPos);
  41669. var shapeUV = this._uvsToShapeUV(facetUV);
  41670. // compute the barycenter of the shape
  41671. var v;
  41672. for (v = 0; v < shape.length; v++) {
  41673. barycenter.addInPlace(shape[v]);
  41674. }
  41675. barycenter.scaleInPlace(1 / shape.length);
  41676. // shift the shape from its barycenter to the origin
  41677. for (v = 0; v < shape.length; v++) {
  41678. shape[v].subtractInPlace(barycenter);
  41679. }
  41680. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  41681. // add the particle in the SPS
  41682. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  41683. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  41684. // initialize the particle position
  41685. this.particles[this.nbParticles].position.addInPlace(barycenter);
  41686. this._index += shape.length;
  41687. idx++;
  41688. this.nbParticles++;
  41689. this._shapeCounter++;
  41690. f += size;
  41691. }
  41692. return this;
  41693. };
  41694. //reset copy
  41695. SolidParticleSystem.prototype._resetCopy = function () {
  41696. this._copy.position.x = 0;
  41697. this._copy.position.y = 0;
  41698. this._copy.position.z = 0;
  41699. this._copy.rotation.x = 0;
  41700. this._copy.rotation.y = 0;
  41701. this._copy.rotation.z = 0;
  41702. this._copy.rotationQuaternion = null;
  41703. this._copy.scaling.x = 1;
  41704. this._copy.scaling.y = 1;
  41705. this._copy.scaling.z = 1;
  41706. this._copy.uvs.x = 0;
  41707. this._copy.uvs.y = 0;
  41708. this._copy.uvs.z = 1;
  41709. this._copy.uvs.w = 1;
  41710. this._copy.color = null;
  41711. };
  41712. // _meshBuilder : inserts the shape model in the global SPS mesh
  41713. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  41714. var i;
  41715. var u = 0;
  41716. var c = 0;
  41717. this._resetCopy();
  41718. if (options && options.positionFunction) {
  41719. options.positionFunction(this._copy, idx, idxInShape);
  41720. }
  41721. if (this._copy.rotationQuaternion) {
  41722. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  41723. }
  41724. else {
  41725. this._yaw = this._copy.rotation.y;
  41726. this._pitch = this._copy.rotation.x;
  41727. this._roll = this._copy.rotation.z;
  41728. this._quaternionRotationYPR();
  41729. }
  41730. this._quaternionToRotationMatrix();
  41731. for (i = 0; i < shape.length; i++) {
  41732. this._vertex.x = shape[i].x;
  41733. this._vertex.y = shape[i].y;
  41734. this._vertex.z = shape[i].z;
  41735. if (options && options.vertexFunction) {
  41736. options.vertexFunction(this._copy, this._vertex, i);
  41737. }
  41738. this._vertex.x *= this._copy.scaling.x;
  41739. this._vertex.y *= this._copy.scaling.y;
  41740. this._vertex.z *= this._copy.scaling.z;
  41741. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  41742. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  41743. if (meshUV) {
  41744. 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);
  41745. u += 2;
  41746. }
  41747. if (this._copy.color) {
  41748. this._color = this._copy.color;
  41749. }
  41750. else if (meshCol && meshCol[c]) {
  41751. this._color.r = meshCol[c];
  41752. this._color.g = meshCol[c + 1];
  41753. this._color.b = meshCol[c + 2];
  41754. this._color.a = meshCol[c + 3];
  41755. }
  41756. else {
  41757. this._color.r = 1;
  41758. this._color.g = 1;
  41759. this._color.b = 1;
  41760. this._color.a = 1;
  41761. }
  41762. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  41763. c += 4;
  41764. }
  41765. for (i = 0; i < meshInd.length; i++) {
  41766. indices.push(p + meshInd[i]);
  41767. }
  41768. if (this._pickable) {
  41769. var nbfaces = meshInd.length / 3;
  41770. for (i = 0; i < nbfaces; i++) {
  41771. this.pickedParticles.push({ idx: idx, faceId: i });
  41772. }
  41773. }
  41774. };
  41775. // returns a shape array from positions array
  41776. SolidParticleSystem.prototype._posToShape = function (positions) {
  41777. var shape = [];
  41778. for (var i = 0; i < positions.length; i += 3) {
  41779. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  41780. }
  41781. return shape;
  41782. };
  41783. // returns a shapeUV array from a Vector4 uvs
  41784. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  41785. var shapeUV = [];
  41786. if (uvs) {
  41787. for (var i = 0; i < uvs.length; i++)
  41788. shapeUV.push(uvs[i]);
  41789. }
  41790. return shapeUV;
  41791. };
  41792. // adds a new particle object in the particles array
  41793. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  41794. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  41795. };
  41796. /**
  41797. * Adds some particles to the SPS from the model shape. Returns the shape id.
  41798. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  41799. * `mesh` is any `Mesh` object that will be used as a model for the solid particles.
  41800. * `nb` (positive integer) the number of particles to be created from this model
  41801. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  41802. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  41803. */
  41804. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  41805. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41806. var meshInd = mesh.getIndices();
  41807. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41808. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41809. var shape = this._posToShape(meshPos);
  41810. var shapeUV = this._uvsToShapeUV(meshUV);
  41811. var posfunc = options ? options.positionFunction : null;
  41812. var vtxfunc = options ? options.vertexFunction : null;
  41813. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  41814. // particles
  41815. var idx = this.nbParticles;
  41816. for (var i = 0; i < nb; i++) {
  41817. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  41818. if (this._updatable) {
  41819. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  41820. }
  41821. this._index += shape.length;
  41822. idx++;
  41823. }
  41824. this.nbParticles += nb;
  41825. this._shapeCounter++;
  41826. return this._shapeCounter - 1;
  41827. };
  41828. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  41829. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  41830. this._resetCopy();
  41831. if (particle._model._positionFunction) {
  41832. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  41833. }
  41834. if (this._copy.rotationQuaternion) {
  41835. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  41836. }
  41837. else {
  41838. this._yaw = this._copy.rotation.y;
  41839. this._pitch = this._copy.rotation.x;
  41840. this._roll = this._copy.rotation.z;
  41841. this._quaternionRotationYPR();
  41842. }
  41843. this._quaternionToRotationMatrix();
  41844. this._shape = particle._model._shape;
  41845. for (var pt = 0; pt < this._shape.length; pt++) {
  41846. this._vertex.x = this._shape[pt].x;
  41847. this._vertex.y = this._shape[pt].y;
  41848. this._vertex.z = this._shape[pt].z;
  41849. if (particle._model._vertexFunction) {
  41850. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  41851. }
  41852. this._vertex.x *= this._copy.scaling.x;
  41853. this._vertex.y *= this._copy.scaling.y;
  41854. this._vertex.z *= this._copy.scaling.z;
  41855. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  41856. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  41857. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  41858. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  41859. }
  41860. particle.position.x = 0;
  41861. particle.position.y = 0;
  41862. particle.position.z = 0;
  41863. particle.rotation.x = 0;
  41864. particle.rotation.y = 0;
  41865. particle.rotation.z = 0;
  41866. particle.rotationQuaternion = null;
  41867. particle.scaling.x = 1;
  41868. particle.scaling.y = 1;
  41869. particle.scaling.z = 1;
  41870. };
  41871. /**
  41872. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  41873. */
  41874. SolidParticleSystem.prototype.rebuildMesh = function () {
  41875. for (var p = 0; p < this.particles.length; p++) {
  41876. this._rebuildParticle(this.particles[p]);
  41877. }
  41878. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  41879. };
  41880. /**
  41881. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  41882. * This method calls `updateParticle()` for each particle of the SPS.
  41883. * For an animated SPS, it is usually called within the render loop.
  41884. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  41885. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  41886. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  41887. */
  41888. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  41889. if (start === void 0) { start = 0; }
  41890. if (end === void 0) { end = this.nbParticles - 1; }
  41891. if (update === void 0) { update = true; }
  41892. if (!this._updatable) {
  41893. return;
  41894. }
  41895. // custom beforeUpdate
  41896. this.beforeUpdateParticles(start, end, update);
  41897. this._cam_axisX.x = 1;
  41898. this._cam_axisX.y = 0;
  41899. this._cam_axisX.z = 0;
  41900. this._cam_axisY.x = 0;
  41901. this._cam_axisY.y = 1;
  41902. this._cam_axisY.z = 0;
  41903. this._cam_axisZ.x = 0;
  41904. this._cam_axisZ.y = 0;
  41905. this._cam_axisZ.z = 1;
  41906. // if the particles will always face the camera
  41907. if (this.billboard) {
  41908. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  41909. this._yaw = this.mesh.rotation.y;
  41910. this._pitch = this.mesh.rotation.x;
  41911. this._roll = this.mesh.rotation.z;
  41912. this._quaternionRotationYPR();
  41913. this._quaternionToRotationMatrix();
  41914. this._rotMatrix.invertToRef(this._invertMatrix);
  41915. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  41916. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  41917. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  41918. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  41919. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  41920. this._cam_axisY.normalize();
  41921. this._cam_axisX.normalize();
  41922. this._cam_axisZ.normalize();
  41923. }
  41924. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  41925. var idx = 0;
  41926. var index = 0;
  41927. var colidx = 0;
  41928. var colorIndex = 0;
  41929. var uvidx = 0;
  41930. var uvIndex = 0;
  41931. if (this._computeBoundingBox) {
  41932. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  41933. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  41934. }
  41935. // particle loop
  41936. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  41937. for (var p = start; p <= end; p++) {
  41938. this._particle = this.particles[p];
  41939. this._shape = this._particle._model._shape;
  41940. this._shapeUV = this._particle._model._shapeUV;
  41941. // call to custom user function to update the particle properties
  41942. this.updateParticle(this._particle);
  41943. // particle rotation matrix
  41944. if (this.billboard) {
  41945. this._particle.rotation.x = 0.0;
  41946. this._particle.rotation.y = 0.0;
  41947. }
  41948. if (this._computeParticleRotation) {
  41949. if (this._particle.rotationQuaternion) {
  41950. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  41951. }
  41952. else {
  41953. this._yaw = this._particle.rotation.y;
  41954. this._pitch = this._particle.rotation.x;
  41955. this._roll = this._particle.rotation.z;
  41956. this._quaternionRotationYPR();
  41957. }
  41958. this._quaternionToRotationMatrix();
  41959. }
  41960. for (var pt = 0; pt < this._shape.length; pt++) {
  41961. idx = index + pt * 3;
  41962. colidx = colorIndex + pt * 4;
  41963. uvidx = uvIndex + pt * 2;
  41964. this._vertex.x = this._shape[pt].x;
  41965. this._vertex.y = this._shape[pt].y;
  41966. this._vertex.z = this._shape[pt].z;
  41967. if (this._computeParticleVertex) {
  41968. this.updateParticleVertex(this._particle, this._vertex, pt);
  41969. }
  41970. // positions
  41971. this._vertex.x *= this._particle.scaling.x;
  41972. this._vertex.y *= this._particle.scaling.y;
  41973. this._vertex.z *= this._particle.scaling.z;
  41974. 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];
  41975. 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;
  41976. 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;
  41977. 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;
  41978. 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;
  41979. 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;
  41980. 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;
  41981. if (this._computeBoundingBox) {
  41982. if (this._positions32[idx] < this._minimum.x) {
  41983. this._minimum.x = this._positions32[idx];
  41984. }
  41985. if (this._positions32[idx] > this._maximum.x) {
  41986. this._maximum.x = this._positions32[idx];
  41987. }
  41988. if (this._positions32[idx + 1] < this._minimum.y) {
  41989. this._minimum.y = this._positions32[idx + 1];
  41990. }
  41991. if (this._positions32[idx + 1] > this._maximum.y) {
  41992. this._maximum.y = this._positions32[idx + 1];
  41993. }
  41994. if (this._positions32[idx + 2] < this._minimum.z) {
  41995. this._minimum.z = this._positions32[idx + 2];
  41996. }
  41997. if (this._positions32[idx + 2] > this._maximum.z) {
  41998. this._maximum.z = this._positions32[idx + 2];
  41999. }
  42000. }
  42001. // normals : if the particles can't be morphed then just rotate the normals
  42002. if (!this._computeParticleVertex && !this.billboard) {
  42003. this._normal.x = this._fixedNormal32[idx];
  42004. this._normal.y = this._fixedNormal32[idx + 1];
  42005. this._normal.z = this._fixedNormal32[idx + 2];
  42006. 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];
  42007. 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;
  42008. 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;
  42009. 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;
  42010. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  42011. 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;
  42012. 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;
  42013. }
  42014. if (this._computeParticleColor) {
  42015. this._colors32[colidx] = this._particle.color.r;
  42016. this._colors32[colidx + 1] = this._particle.color.g;
  42017. this._colors32[colidx + 2] = this._particle.color.b;
  42018. this._colors32[colidx + 3] = this._particle.color.a;
  42019. }
  42020. if (this._computeParticleTexture) {
  42021. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  42022. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  42023. }
  42024. }
  42025. index = idx + 3;
  42026. colorIndex = colidx + 4;
  42027. uvIndex = uvidx + 2;
  42028. }
  42029. if (update) {
  42030. if (this._computeParticleColor) {
  42031. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  42032. }
  42033. if (this._computeParticleTexture) {
  42034. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  42035. }
  42036. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  42037. if (!this.mesh.areNormalsFrozen) {
  42038. if (this._computeParticleVertex || this.billboard) {
  42039. // recompute the normals only if the particles can be morphed, update then the normal reference array
  42040. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  42041. for (var i = 0; i < this._normals32.length; i++) {
  42042. this._fixedNormal32[i] = this._normals32[i];
  42043. }
  42044. }
  42045. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  42046. }
  42047. }
  42048. if (this._computeBoundingBox) {
  42049. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  42050. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  42051. }
  42052. this.afterUpdateParticles(start, end, update);
  42053. };
  42054. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  42055. this._halfroll = this._roll * 0.5;
  42056. this._halfpitch = this._pitch * 0.5;
  42057. this._halfyaw = this._yaw * 0.5;
  42058. this._sinRoll = Math.sin(this._halfroll);
  42059. this._cosRoll = Math.cos(this._halfroll);
  42060. this._sinPitch = Math.sin(this._halfpitch);
  42061. this._cosPitch = Math.cos(this._halfpitch);
  42062. this._sinYaw = Math.sin(this._halfyaw);
  42063. this._cosYaw = Math.cos(this._halfyaw);
  42064. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  42065. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  42066. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  42067. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  42068. };
  42069. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  42070. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  42071. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  42072. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  42073. this._rotMatrix.m[3] = 0;
  42074. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  42075. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  42076. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  42077. this._rotMatrix.m[7] = 0;
  42078. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  42079. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  42080. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  42081. this._rotMatrix.m[11] = 0;
  42082. this._rotMatrix.m[12] = 0;
  42083. this._rotMatrix.m[13] = 0;
  42084. this._rotMatrix.m[14] = 0;
  42085. this._rotMatrix.m[15] = 1.0;
  42086. };
  42087. /**
  42088. * Disposes the SPS
  42089. */
  42090. SolidParticleSystem.prototype.dispose = function () {
  42091. this.mesh.dispose();
  42092. this.vars = null;
  42093. // drop references to internal big arrays for the GC
  42094. this._positions = null;
  42095. this._indices = null;
  42096. this._normals = null;
  42097. this._uvs = null;
  42098. this._colors = null;
  42099. this._positions32 = null;
  42100. this._normals32 = null;
  42101. this._fixedNormal32 = null;
  42102. this._uvs32 = null;
  42103. this._colors32 = null;
  42104. this.pickedParticles = null;
  42105. };
  42106. /**
  42107. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  42108. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  42109. */
  42110. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  42111. if (!this._isVisibilityBoxLocked) {
  42112. this.mesh.refreshBoundingInfo();
  42113. }
  42114. };
  42115. /**
  42116. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  42117. * @param size the size (float) of the visibility box
  42118. * note : this doesn't lock the SPS mesh bounding box.
  42119. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  42120. */
  42121. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  42122. var vis = size / 2;
  42123. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  42124. };
  42125. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  42126. // getter and setter
  42127. get: function () {
  42128. return this._alwaysVisible;
  42129. },
  42130. /**
  42131. * Sets the SPS as always visible or not
  42132. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  42133. */
  42134. set: function (val) {
  42135. this._alwaysVisible = val;
  42136. this.mesh.alwaysSelectAsActiveMesh = val;
  42137. },
  42138. enumerable: true,
  42139. configurable: true
  42140. });
  42141. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  42142. get: function () {
  42143. return this._isVisibilityBoxLocked;
  42144. },
  42145. /**
  42146. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  42147. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  42148. */
  42149. set: function (val) {
  42150. this._isVisibilityBoxLocked = val;
  42151. this.mesh.getBoundingInfo().isLocked = val;
  42152. },
  42153. enumerable: true,
  42154. configurable: true
  42155. });
  42156. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  42157. // getters
  42158. get: function () {
  42159. return this._computeParticleRotation;
  42160. },
  42161. // Optimizer setters
  42162. /**
  42163. * Tells to `setParticles()` to compute the particle rotations or not.
  42164. * Default value : true. The SPS is faster when it's set to false.
  42165. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  42166. */
  42167. set: function (val) {
  42168. this._computeParticleRotation = val;
  42169. },
  42170. enumerable: true,
  42171. configurable: true
  42172. });
  42173. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  42174. get: function () {
  42175. return this._computeParticleColor;
  42176. },
  42177. /**
  42178. * Tells to `setParticles()` to compute the particle colors or not.
  42179. * Default value : true. The SPS is faster when it's set to false.
  42180. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  42181. */
  42182. set: function (val) {
  42183. this._computeParticleColor = val;
  42184. },
  42185. enumerable: true,
  42186. configurable: true
  42187. });
  42188. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  42189. get: function () {
  42190. return this._computeParticleTexture;
  42191. },
  42192. /**
  42193. * Tells to `setParticles()` to compute the particle textures or not.
  42194. * Default value : true. The SPS is faster when it's set to false.
  42195. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  42196. */
  42197. set: function (val) {
  42198. this._computeParticleTexture = val;
  42199. },
  42200. enumerable: true,
  42201. configurable: true
  42202. });
  42203. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  42204. get: function () {
  42205. return this._computeParticleVertex;
  42206. },
  42207. /**
  42208. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  42209. * Default value : false. The SPS is faster when it's set to false.
  42210. * Note : the particle custom vertex positions aren't stored values.
  42211. */
  42212. set: function (val) {
  42213. this._computeParticleVertex = val;
  42214. },
  42215. enumerable: true,
  42216. configurable: true
  42217. });
  42218. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  42219. get: function () {
  42220. return this._computeBoundingBox;
  42221. },
  42222. /**
  42223. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  42224. */
  42225. set: function (val) {
  42226. this._computeBoundingBox = val;
  42227. },
  42228. enumerable: true,
  42229. configurable: true
  42230. });
  42231. // =======================================================================
  42232. // Particle behavior logic
  42233. // these following methods may be overwritten by the user to fit his needs
  42234. /**
  42235. * This function does nothing. It may be overwritten to set all the particle first values.
  42236. * The SPS doesn't call this function, you may have to call it by your own.
  42237. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  42238. */
  42239. SolidParticleSystem.prototype.initParticles = function () {
  42240. };
  42241. /**
  42242. * This function does nothing. It may be overwritten to recycle a particle.
  42243. * The SPS doesn't call this function, you may have to call it by your own.
  42244. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  42245. */
  42246. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  42247. return particle;
  42248. };
  42249. /**
  42250. * Updates a particle : this function should be overwritten by the user.
  42251. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  42252. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  42253. * ex : just set a particle position or velocity and recycle conditions
  42254. */
  42255. SolidParticleSystem.prototype.updateParticle = function (particle) {
  42256. return particle;
  42257. };
  42258. /**
  42259. * Updates a vertex of a particle : it can be overwritten by the user.
  42260. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  42261. * @param particle the current particle
  42262. * @param vertex the current index of the current particle
  42263. * @param pt the index of the current vertex in the particle shape
  42264. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  42265. * ex : just set a vertex particle position
  42266. */
  42267. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  42268. return vertex;
  42269. };
  42270. /**
  42271. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  42272. * This does nothing and may be overwritten by the user.
  42273. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42274. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42275. * @param update the boolean update value actually passed to setParticles()
  42276. */
  42277. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  42278. };
  42279. /**
  42280. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  42281. * This will be passed three parameters.
  42282. * This does nothing and may be overwritten by the user.
  42283. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42284. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42285. * @param update the boolean update value actually passed to setParticles()
  42286. */
  42287. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  42288. };
  42289. return SolidParticleSystem;
  42290. })();
  42291. BABYLON.SolidParticleSystem = SolidParticleSystem;
  42292. })(BABYLON || (BABYLON = {}));
  42293. var BABYLON;
  42294. (function (BABYLON) {
  42295. var Internals;
  42296. (function (Internals) {
  42297. var FileFaceOrientation = (function () {
  42298. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  42299. this.name = name;
  42300. this.worldAxisForNormal = worldAxisForNormal;
  42301. this.worldAxisForFileX = worldAxisForFileX;
  42302. this.worldAxisForFileY = worldAxisForFileY;
  42303. }
  42304. return FileFaceOrientation;
  42305. })();
  42306. ;
  42307. /**
  42308. * Helper class dealing with the extraction of spherical polynomial dataArray
  42309. * from a cube map.
  42310. */
  42311. var CubeMapToSphericalPolynomialTools = (function () {
  42312. function CubeMapToSphericalPolynomialTools() {
  42313. }
  42314. /**
  42315. * Converts a cubemap to the according Spherical Polynomial data.
  42316. * This extracts the first 3 orders only as they are the only one used in the lighting.
  42317. *
  42318. * @param cubeInfo The Cube map to extract the information from.
  42319. * @return The Spherical Polynomial data.
  42320. */
  42321. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  42322. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  42323. var totalSolidAngle = 0.0;
  42324. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  42325. var du = 2.0 / cubeInfo.size;
  42326. var dv = du;
  42327. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  42328. var minUV = du * 0.5 - 1.0;
  42329. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  42330. var fileFace = this.FileFaces[faceIndex];
  42331. var dataArray = cubeInfo[fileFace.name];
  42332. var v = minUV;
  42333. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  42334. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  42335. // Because SP is still linear, so summation is fine in that basis.
  42336. for (var y = 0; y < cubeInfo.size; y++) {
  42337. var u = minUV;
  42338. for (var x = 0; x < cubeInfo.size; x++) {
  42339. // World direction (not normalised)
  42340. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  42341. worldDirection.normalize();
  42342. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  42343. if (1) {
  42344. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  42345. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  42346. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  42347. var color = new BABYLON.Color3(r, g, b);
  42348. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  42349. }
  42350. else {
  42351. if (faceIndex == 0) {
  42352. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  42353. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  42354. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  42355. }
  42356. else if (faceIndex == 1) {
  42357. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  42358. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  42359. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  42360. }
  42361. else if (faceIndex == 2) {
  42362. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  42363. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  42364. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  42365. }
  42366. else if (faceIndex == 3) {
  42367. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  42368. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  42369. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  42370. }
  42371. else if (faceIndex == 4) {
  42372. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  42373. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  42374. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  42375. }
  42376. else if (faceIndex == 5) {
  42377. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  42378. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  42379. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  42380. }
  42381. 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]);
  42382. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  42383. }
  42384. totalSolidAngle += deltaSolidAngle;
  42385. u += du;
  42386. }
  42387. v += dv;
  42388. }
  42389. }
  42390. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  42391. var correction = correctSolidAngle / totalSolidAngle;
  42392. sphericalHarmonics.scale(correction);
  42393. // Additionally scale by pi -- audit needed
  42394. sphericalHarmonics.scale(1.0 / Math.PI);
  42395. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  42396. };
  42397. CubeMapToSphericalPolynomialTools.FileFaces = [
  42398. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  42399. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  42400. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  42401. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  42402. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  42403. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  42404. ];
  42405. return CubeMapToSphericalPolynomialTools;
  42406. })();
  42407. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  42408. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  42409. })(BABYLON || (BABYLON = {}));
  42410. var BABYLON;
  42411. (function (BABYLON) {
  42412. var Internals;
  42413. (function (Internals) {
  42414. /**
  42415. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  42416. */
  42417. var PanoramaToCubeMapTools = (function () {
  42418. function PanoramaToCubeMapTools() {
  42419. }
  42420. /**
  42421. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  42422. *
  42423. * @param float32Array The source data.
  42424. * @param inputWidth The width of the input panorama.
  42425. * @param inputhHeight The height of the input panorama.
  42426. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  42427. * @return The cubemap data
  42428. */
  42429. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  42430. if (!float32Array) {
  42431. throw "ConvertPanoramaToCubemap: input cannot be null";
  42432. }
  42433. if (float32Array.length != inputWidth * inputHeight * 3) {
  42434. throw "ConvertPanoramaToCubemap: input size is wrong";
  42435. }
  42436. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  42437. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  42438. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  42439. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  42440. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  42441. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  42442. return {
  42443. front: textureFront,
  42444. back: textureBack,
  42445. left: textureLeft,
  42446. right: textureRight,
  42447. up: textureUp,
  42448. down: textureDown,
  42449. size: size
  42450. };
  42451. };
  42452. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  42453. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  42454. var textureArray = new Float32Array(buffer);
  42455. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  42456. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  42457. var dy = 1 / texSize;
  42458. var fy = 0;
  42459. for (var y = 0; y < texSize; y++) {
  42460. var xv1 = faceData[0];
  42461. var xv2 = faceData[2];
  42462. for (var x = 0; x < texSize; x++) {
  42463. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  42464. v.normalize();
  42465. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  42466. // 3 channels per pixels
  42467. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  42468. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  42469. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  42470. xv1 = xv1.add(rotDX1);
  42471. xv2 = xv2.add(rotDX2);
  42472. }
  42473. fy += dy;
  42474. }
  42475. return textureArray;
  42476. };
  42477. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  42478. var theta = Math.atan2(vDir.z, vDir.x);
  42479. var phi = Math.acos(vDir.y);
  42480. while (theta < -Math.PI)
  42481. theta += 2 * Math.PI;
  42482. while (theta > Math.PI)
  42483. theta -= 2 * Math.PI;
  42484. var dx = theta / Math.PI;
  42485. var dy = phi / Math.PI;
  42486. // recenter.
  42487. dx = dx * 0.5 + 0.5;
  42488. var px = Math.round(dx * inputWidth);
  42489. if (px < 0)
  42490. px = 0;
  42491. else if (px >= inputWidth)
  42492. px = inputWidth - 1;
  42493. var py = Math.round(dy * inputHeight);
  42494. if (py < 0)
  42495. py = 0;
  42496. else if (py >= inputHeight)
  42497. py = inputHeight - 1;
  42498. var inputY = (inputHeight - py - 1);
  42499. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  42500. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  42501. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  42502. return {
  42503. r: r,
  42504. g: g,
  42505. b: b
  42506. };
  42507. };
  42508. PanoramaToCubeMapTools.FACE_FRONT = [
  42509. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  42510. new BABYLON.Vector3(1.0, -1.0, -1.0),
  42511. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  42512. new BABYLON.Vector3(1.0, 1.0, -1.0)
  42513. ];
  42514. PanoramaToCubeMapTools.FACE_BACK = [
  42515. new BABYLON.Vector3(1.0, -1.0, 1.0),
  42516. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  42517. new BABYLON.Vector3(1.0, 1.0, 1.0),
  42518. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  42519. ];
  42520. PanoramaToCubeMapTools.FACE_RIGHT = [
  42521. new BABYLON.Vector3(1.0, -1.0, -1.0),
  42522. new BABYLON.Vector3(1.0, -1.0, 1.0),
  42523. new BABYLON.Vector3(1.0, 1.0, -1.0),
  42524. new BABYLON.Vector3(1.0, 1.0, 1.0)
  42525. ];
  42526. PanoramaToCubeMapTools.FACE_LEFT = [
  42527. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  42528. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  42529. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  42530. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  42531. ];
  42532. PanoramaToCubeMapTools.FACE_DOWN = [
  42533. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  42534. new BABYLON.Vector3(1.0, 1.0, -1.0),
  42535. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  42536. new BABYLON.Vector3(1.0, 1.0, 1.0)
  42537. ];
  42538. PanoramaToCubeMapTools.FACE_UP = [
  42539. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  42540. new BABYLON.Vector3(1.0, -1.0, 1.0),
  42541. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  42542. new BABYLON.Vector3(1.0, -1.0, -1.0)
  42543. ];
  42544. return PanoramaToCubeMapTools;
  42545. })();
  42546. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  42547. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  42548. })(BABYLON || (BABYLON = {}));
  42549. var BABYLON;
  42550. (function (BABYLON) {
  42551. var Internals;
  42552. (function (Internals) {
  42553. ;
  42554. /**
  42555. * This groups tools to convert HDR texture to native colors array.
  42556. */
  42557. var HDRTools = (function () {
  42558. function HDRTools() {
  42559. }
  42560. HDRTools.Ldexp = function (mantissa, exponent) {
  42561. if (exponent > 1023) {
  42562. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  42563. }
  42564. if (exponent < -1074) {
  42565. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  42566. }
  42567. return mantissa * Math.pow(2, exponent);
  42568. };
  42569. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  42570. if (exponent > 0) {
  42571. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  42572. float32array[index + 0] = red * exponent;
  42573. float32array[index + 1] = green * exponent;
  42574. float32array[index + 2] = blue * exponent;
  42575. }
  42576. else {
  42577. float32array[index + 0] = 0;
  42578. float32array[index + 1] = 0;
  42579. float32array[index + 2] = 0;
  42580. }
  42581. };
  42582. HDRTools.readStringLine = function (uint8array, startIndex) {
  42583. var line = "";
  42584. var character = "";
  42585. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  42586. character = String.fromCharCode(uint8array[i]);
  42587. if (character == "\n") {
  42588. break;
  42589. }
  42590. line += character;
  42591. }
  42592. return line;
  42593. };
  42594. /**
  42595. * Reads header information from an RGBE texture stored in a native array.
  42596. * More information on this format are available here:
  42597. * https://en.wikipedia.org/wiki/RGBE_image_format
  42598. *
  42599. * @param uint8array The binary file stored in native array.
  42600. * @return The header information.
  42601. */
  42602. HDRTools.RGBE_ReadHeader = function (uint8array) {
  42603. var height = 0;
  42604. var width = 0;
  42605. var line = this.readStringLine(uint8array, 0);
  42606. if (line[0] != '#' || line[1] != '?') {
  42607. throw "Bad HDR Format.";
  42608. }
  42609. var endOfHeader = false;
  42610. var findFormat = false;
  42611. var lineIndex = 0;
  42612. do {
  42613. lineIndex += (line.length + 1);
  42614. line = this.readStringLine(uint8array, lineIndex);
  42615. if (line == "FORMAT=32-bit_rle_rgbe") {
  42616. findFormat = true;
  42617. }
  42618. else if (line.length == 0) {
  42619. endOfHeader = true;
  42620. }
  42621. } while (!endOfHeader);
  42622. if (!findFormat) {
  42623. throw "HDR Bad header format, unsupported FORMAT";
  42624. }
  42625. lineIndex += (line.length + 1);
  42626. line = this.readStringLine(uint8array, lineIndex);
  42627. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  42628. var match = sizeRegexp.exec(line);
  42629. // TODO. Support +Y and -X if needed.
  42630. if (match.length < 3) {
  42631. throw "HDR Bad header format, no size";
  42632. }
  42633. width = parseInt(match[2]);
  42634. height = parseInt(match[1]);
  42635. if (width < 8 || width > 0x7fff) {
  42636. throw "HDR Bad header format, unsupported size";
  42637. }
  42638. lineIndex += (line.length + 1);
  42639. return {
  42640. height: height,
  42641. width: width,
  42642. dataPosition: lineIndex
  42643. };
  42644. };
  42645. /**
  42646. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  42647. * This RGBE texture needs to store the information as a panorama.
  42648. *
  42649. * More information on this format are available here:
  42650. * https://en.wikipedia.org/wiki/RGBE_image_format
  42651. *
  42652. * @param buffer The binary file stored in an array buffer.
  42653. * @param size The expected size of the extracted cubemap.
  42654. * @return The Cube Map information.
  42655. */
  42656. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  42657. var uint8array = new Uint8Array(buffer);
  42658. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  42659. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  42660. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  42661. return cubeMapData;
  42662. };
  42663. /**
  42664. * Returns the pixels data extracted from an RGBE texture.
  42665. * This pixels will be stored left to right up to down in the R G B order in one array.
  42666. *
  42667. * More information on this format are available here:
  42668. * https://en.wikipedia.org/wiki/RGBE_image_format
  42669. *
  42670. * @param uint8array The binary file stored in an array buffer.
  42671. * @param hdrInfo The header information of the file.
  42672. * @return The pixels data in RGB right to left up to down order.
  42673. */
  42674. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  42675. // Keep for multi format supports.
  42676. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  42677. };
  42678. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  42679. var num_scanlines = hdrInfo.height;
  42680. var scanline_width = hdrInfo.width;
  42681. var a, b, c, d, count;
  42682. var dataIndex = hdrInfo.dataPosition;
  42683. var index = 0, endIndex = 0, i = 0;
  42684. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  42685. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  42686. // 3 channels of 4 bytes per pixel in float.
  42687. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  42688. var resultArray = new Float32Array(resultBuffer);
  42689. // read in each successive scanline
  42690. while (num_scanlines > 0) {
  42691. a = uint8array[dataIndex++];
  42692. b = uint8array[dataIndex++];
  42693. c = uint8array[dataIndex++];
  42694. d = uint8array[dataIndex++];
  42695. if (a != 2 || b != 2 || (c & 0x80)) {
  42696. // this file is not run length encoded
  42697. throw "HDR Bad header format, not RLE";
  42698. }
  42699. if (((c << 8) | d) != scanline_width) {
  42700. throw "HDR Bad header format, wrong scan line width";
  42701. }
  42702. index = 0;
  42703. // read each of the four channels for the scanline into the buffer
  42704. for (i = 0; i < 4; i++) {
  42705. endIndex = (i + 1) * scanline_width;
  42706. while (index < endIndex) {
  42707. a = uint8array[dataIndex++];
  42708. b = uint8array[dataIndex++];
  42709. if (a > 128) {
  42710. // a run of the same value
  42711. count = a - 128;
  42712. if ((count == 0) || (count > endIndex - index)) {
  42713. throw "HDR Bad Format, bad scanline data (run)";
  42714. }
  42715. while (count-- > 0) {
  42716. scanLineArray[index++] = b;
  42717. }
  42718. }
  42719. else {
  42720. // a non-run
  42721. count = a;
  42722. if ((count == 0) || (count > endIndex - index)) {
  42723. throw "HDR Bad Format, bad scanline data (non-run)";
  42724. }
  42725. scanLineArray[index++] = b;
  42726. if (--count > 0) {
  42727. for (var j = 0; j < count; j++) {
  42728. scanLineArray[index++] = uint8array[dataIndex++];
  42729. }
  42730. }
  42731. }
  42732. }
  42733. }
  42734. // now convert data from buffer into floats
  42735. for (i = 0; i < scanline_width; i++) {
  42736. a = scanLineArray[i];
  42737. b = scanLineArray[i + scanline_width];
  42738. c = scanLineArray[i + 2 * scanline_width];
  42739. d = scanLineArray[i + 3 * scanline_width];
  42740. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  42741. }
  42742. num_scanlines--;
  42743. }
  42744. return resultArray;
  42745. };
  42746. return HDRTools;
  42747. })();
  42748. Internals.HDRTools = HDRTools;
  42749. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  42750. })(BABYLON || (BABYLON = {}));
  42751. //_______________________________________________________________
  42752. // Extracted from CubeMapGen:
  42753. // https://code.google.com/archive/p/cubemapgen/
  42754. //
  42755. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  42756. //_______________________________________________________________
  42757. var BABYLON;
  42758. (function (BABYLON) {
  42759. var Internals;
  42760. (function (Internals) {
  42761. /**
  42762. * The bounding box information used during the conversion process.
  42763. */
  42764. var CMGBoundinBox = (function () {
  42765. function CMGBoundinBox() {
  42766. this.min = new BABYLON.Vector3(0, 0, 0);
  42767. this.max = new BABYLON.Vector3(0, 0, 0);
  42768. this.clear();
  42769. }
  42770. CMGBoundinBox.prototype.clear = function () {
  42771. this.min.x = CMGBoundinBox.MAX;
  42772. this.min.y = CMGBoundinBox.MAX;
  42773. this.min.z = CMGBoundinBox.MAX;
  42774. this.max.x = CMGBoundinBox.MIN;
  42775. this.max.y = CMGBoundinBox.MIN;
  42776. this.max.z = CMGBoundinBox.MIN;
  42777. };
  42778. CMGBoundinBox.prototype.augment = function (x, y, z) {
  42779. this.min.x = Math.min(this.min.x, x);
  42780. this.min.y = Math.min(this.min.y, y);
  42781. this.min.z = Math.min(this.min.z, z);
  42782. this.max.x = Math.max(this.max.x, x);
  42783. this.max.y = Math.max(this.max.y, y);
  42784. this.max.z = Math.max(this.max.z, z);
  42785. };
  42786. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  42787. this.min.x = Math.max(this.min.x, x);
  42788. this.min.y = Math.max(this.min.y, y);
  42789. this.min.z = Math.max(this.min.z, z);
  42790. };
  42791. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  42792. this.max.x = Math.min(this.max.x, x);
  42793. this.max.y = Math.min(this.max.y, y);
  42794. this.max.z = Math.min(this.max.z, z);
  42795. };
  42796. CMGBoundinBox.prototype.empty = function () {
  42797. if ((this.min.x > this.max.y) ||
  42798. (this.min.y > this.max.y) ||
  42799. (this.min.z > this.max.y)) {
  42800. return true;
  42801. }
  42802. else {
  42803. return false;
  42804. }
  42805. };
  42806. CMGBoundinBox.MAX = Number.MAX_VALUE;
  42807. CMGBoundinBox.MIN = Number.MIN_VALUE;
  42808. return CMGBoundinBox;
  42809. })();
  42810. /**
  42811. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  42812. * required by the glossinees of a material.
  42813. *
  42814. * This only supports the cosine drop power as well as Warp fixup generation method.
  42815. *
  42816. * This is using the process from CubeMapGen described here:
  42817. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  42818. */
  42819. var PMREMGenerator = (function () {
  42820. /**
  42821. * Constructor of the generator.
  42822. *
  42823. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  42824. * @param inputSize The size of the cubemap faces
  42825. * @param outputSize The size of the output cubemap faces
  42826. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  42827. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  42828. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  42829. * @param specularPower The max specular level of the desired cubemap
  42830. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  42831. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  42832. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  42833. */
  42834. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  42835. this.input = input;
  42836. this.inputSize = inputSize;
  42837. this.outputSize = outputSize;
  42838. this.maxNumMipLevels = maxNumMipLevels;
  42839. this.numChannels = numChannels;
  42840. this.isFloat = isFloat;
  42841. this.specularPower = specularPower;
  42842. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  42843. this.excludeBase = excludeBase;
  42844. this.fixup = fixup;
  42845. this._outputSurface = [];
  42846. this._numMipLevels = 0;
  42847. }
  42848. /**
  42849. * Launches the filter process and return the result.
  42850. *
  42851. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  42852. */
  42853. PMREMGenerator.prototype.filterCubeMap = function () {
  42854. // Init cubemap processor
  42855. this.init();
  42856. // Filters the cubemap
  42857. this.filterCubeMapMipChain();
  42858. // Returns the filtered mips.
  42859. return this._outputSurface;
  42860. };
  42861. PMREMGenerator.prototype.init = function () {
  42862. var i;
  42863. var j;
  42864. var mipLevelSize;
  42865. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  42866. if (this.maxNumMipLevels == 0) {
  42867. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  42868. }
  42869. //first miplevel size
  42870. mipLevelSize = this.outputSize;
  42871. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  42872. for (j = 0; j < this.maxNumMipLevels; j++) {
  42873. this._outputSurface.length++;
  42874. this._outputSurface[j] = [];
  42875. //Iterate over faces for output images
  42876. for (i = 0; i < 6; i++) {
  42877. this._outputSurface[j].length++;
  42878. // Initializes a new array for the output.
  42879. if (this.isFloat) {
  42880. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  42881. }
  42882. else {
  42883. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  42884. }
  42885. }
  42886. //next mip level is half size
  42887. mipLevelSize >>= 1;
  42888. this._numMipLevels++;
  42889. //terminate if mip chain becomes too small
  42890. if (mipLevelSize == 0) {
  42891. this.maxNumMipLevels = j;
  42892. return;
  42893. }
  42894. }
  42895. };
  42896. //--------------------------------------------------------------------------------------
  42897. //Cube map filtering and mip chain generation.
  42898. // the cube map filtereing is specified using a number of parameters:
  42899. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  42900. // indicates the region of the hemisphere to filter over for each tap.
  42901. //
  42902. // Note that the top mip level is also a filtered version of the original input images
  42903. // as well in order to create mip chains for diffuse environment illumination.
  42904. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  42905. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  42906. //
  42907. // Then the mip angle used to genreate the next level of the mip chain from the first level
  42908. // is a_InitialMipAngle
  42909. //
  42910. // The angle for the subsequent levels of the mip chain are specified by their parents
  42911. // filtering angle and a per-level scale and bias
  42912. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  42913. //
  42914. //--------------------------------------------------------------------------------------
  42915. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  42916. // First, take count of the lighting model to modify SpecularPower
  42917. // 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;
  42918. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  42919. //Cone angle start (for generating subsequent mip levels)
  42920. var currentSpecularPower = this.specularPower;
  42921. //Build filter lookup tables based on the source miplevel size
  42922. this.precomputeFilterLookupTables(this.inputSize);
  42923. // Note that we need to filter the first level before generating mipmap
  42924. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  42925. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  42926. // TODO : Write a function to copy and scale the base mipmap in output
  42927. // I am just lazy here and just put a high specular power value, and do some if.
  42928. if (this.excludeBase && (levelIndex == 0)) {
  42929. // 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).
  42930. currentSpecularPower = 100000.0;
  42931. }
  42932. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  42933. var srcCubeImage = this.input;
  42934. var dstCubeImage = this._outputSurface[levelIndex];
  42935. var dstSize = this.outputSize >> levelIndex;
  42936. // Compute required angle.
  42937. var angle = this.getBaseFilterAngle(currentSpecularPower);
  42938. // filter cube surfaces
  42939. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  42940. // fix seams
  42941. if (this.fixup) {
  42942. this.fixupCubeEdges(dstCubeImage, dstSize);
  42943. }
  42944. // Decrease the specular power to generate the mipmap chain
  42945. // TODO : Use another method for Exclude (see first comment at start of the function
  42946. if (this.excludeBase && (levelIndex == 0)) {
  42947. currentSpecularPower = this.specularPower;
  42948. }
  42949. currentSpecularPower *= this.cosinePowerDropPerMip;
  42950. }
  42951. };
  42952. //--------------------------------------------------------------------------------------
  42953. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  42954. // It allow to optimize the texel to access base on the specular power.
  42955. //--------------------------------------------------------------------------------------
  42956. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  42957. // We want to find the alpha such that:
  42958. // cos(alpha)^cosinePower = epsilon
  42959. // That's: acos(epsilon^(1/cosinePower))
  42960. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  42961. var angle = 180.0;
  42962. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  42963. angle *= 180.0 / Math.PI; // Convert to degree
  42964. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  42965. return angle;
  42966. };
  42967. //--------------------------------------------------------------------------------------
  42968. //Builds the following lookup tables prior to filtering:
  42969. // -normalizer cube map
  42970. // -tap weight lookup table
  42971. //
  42972. //--------------------------------------------------------------------------------------
  42973. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  42974. var srcTexelAngle;
  42975. var iCubeFace;
  42976. //clear pre-existing normalizer cube map
  42977. this._normCubeMap = [];
  42978. //Normalized vectors per cubeface and per-texel solid angle
  42979. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  42980. };
  42981. //--------------------------------------------------------------------------------------
  42982. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  42983. //
  42984. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  42985. //
  42986. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  42987. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  42988. // below
  42989. //--------------------------------------------------------------------------------------
  42990. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  42991. var iCubeFace;
  42992. var u;
  42993. var v;
  42994. //iterate over cube faces
  42995. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  42996. //First three channels for norm cube, and last channel for solid angle
  42997. this._normCubeMap.push(new Float32Array(size * size * 4));
  42998. //fast texture walk, build normalizer cube map
  42999. var facesData = this.input[iCubeFace];
  43000. for (v = 0; v < size; v++) {
  43001. for (u = 0; u < size; u++) {
  43002. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  43003. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  43004. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  43005. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  43006. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  43007. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  43008. }
  43009. }
  43010. }
  43011. };
  43012. //--------------------------------------------------------------------------------------
  43013. // Convert cubemap face texel coordinates and face idx to 3D vector
  43014. // note the U and V coords are integer coords and range from 0 to size-1
  43015. // this routine can be used to generate a normalizer cube map
  43016. //--------------------------------------------------------------------------------------
  43017. // SL BEGIN
  43018. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  43019. var nvcU;
  43020. var nvcV;
  43021. var tempVec;
  43022. // Change from original AMD code
  43023. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  43024. // + 0.5f is for texel center addressing
  43025. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  43026. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  43027. // warp fixup
  43028. if (fixup && size > 1) {
  43029. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  43030. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  43031. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  43032. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  43033. }
  43034. // Get current vector
  43035. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  43036. // U contribution
  43037. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  43038. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  43039. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  43040. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  43041. // V contribution and Sum
  43042. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  43043. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  43044. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  43045. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  43046. //add face axis
  43047. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  43048. PMREMGenerator._vectorTemp.x += faceAxis[0];
  43049. PMREMGenerator._vectorTemp.y += faceAxis[1];
  43050. PMREMGenerator._vectorTemp.z += faceAxis[2];
  43051. //normalize vector
  43052. PMREMGenerator._vectorTemp.normalize();
  43053. return PMREMGenerator._vectorTemp;
  43054. };
  43055. //--------------------------------------------------------------------------------------
  43056. // Convert 3D vector to cubemap face texel coordinates and face idx
  43057. // note the U and V coords are integer coords and range from 0 to size-1
  43058. // this routine can be used to generate a normalizer cube map
  43059. //
  43060. // returns face IDX and texel coords
  43061. //--------------------------------------------------------------------------------------
  43062. // SL BEGIN
  43063. /*
  43064. Mapping Texture Coordinates to Cube Map Faces
  43065. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  43066. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  43067. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  43068. map arrangement in Pixar's RenderMan package.
  43069. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  43070. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  43071. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  43072. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  43073. the major axis direction). The target column in the table below explains how the major axis direction
  43074. maps to the 2D image of a particular cube map target.
  43075. major axis
  43076. direction target sc tc ma
  43077. ---------- --------------------------------- --- --- ---
  43078. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  43079. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  43080. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  43081. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  43082. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  43083. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  43084. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  43085. an updated (s,t) is calculated as follows
  43086. s = ( sc/|ma| + 1 ) / 2
  43087. t = ( tc/|ma| + 1 ) / 2
  43088. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  43089. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  43090. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  43091. */
  43092. // Note this method return U and V in range from 0 to size-1
  43093. // SL END
  43094. // Store the information in vector3 for convenience (faceindex, u, v)
  43095. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  43096. var maxCoord;
  43097. var faceIdx;
  43098. //absolute value 3
  43099. var absX = Math.abs(x);
  43100. var absY = Math.abs(y);
  43101. var absZ = Math.abs(z);
  43102. if (absX >= absY && absX >= absZ) {
  43103. maxCoord = absX;
  43104. if (x >= 0) {
  43105. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  43106. }
  43107. else {
  43108. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  43109. }
  43110. }
  43111. else if (absY >= absX && absY >= absZ) {
  43112. maxCoord = absY;
  43113. if (y >= 0) {
  43114. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  43115. }
  43116. else {
  43117. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  43118. }
  43119. }
  43120. else {
  43121. maxCoord = absZ;
  43122. if (z >= 0) {
  43123. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  43124. }
  43125. else {
  43126. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  43127. }
  43128. }
  43129. //divide through by max coord so face vector lies on cube face
  43130. var scale = 1 / maxCoord;
  43131. x *= scale;
  43132. y *= scale;
  43133. z *= scale;
  43134. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  43135. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  43136. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  43137. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  43138. // Modify original AMD code to return value from 0 to Size - 1
  43139. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  43140. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  43141. PMREMGenerator._vectorTemp.x = faceIdx;
  43142. PMREMGenerator._vectorTemp.y = u;
  43143. PMREMGenerator._vectorTemp.z = v;
  43144. return PMREMGenerator._vectorTemp;
  43145. };
  43146. //--------------------------------------------------------------------------------------
  43147. //Original code from Ignacio CastaÒo
  43148. // This formula is from Manne ÷hrstrˆm's thesis.
  43149. // Take two coordiantes in the range [-1, 1] that define a portion of a
  43150. // cube face and return the area of the projection of that portion on the
  43151. // surface of the sphere.
  43152. //--------------------------------------------------------------------------------------
  43153. PMREMGenerator.prototype.areaElement = function (x, y) {
  43154. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  43155. };
  43156. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  43157. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  43158. // (+ 0.5f is for texel center addressing)
  43159. u = (2.0 * (u + 0.5) / size) - 1.0;
  43160. v = (2.0 * (v + 0.5) / size) - 1.0;
  43161. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  43162. var invResolution = 1.0 / size;
  43163. // U and V are the -1..1 texture coordinate on the current face.
  43164. // Get projected area for this texel
  43165. var x0 = u - invResolution;
  43166. var y0 = v - invResolution;
  43167. var x1 = u + invResolution;
  43168. var y1 = v + invResolution;
  43169. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  43170. return solidAngle;
  43171. };
  43172. //--------------------------------------------------------------------------------------
  43173. //The key to the speed of these filtering routines is to quickly define a per-face
  43174. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  43175. // Later these pixels are selectively processed based on their dot products to see if
  43176. // they reside within the filtering cone.
  43177. //
  43178. //This is done by computing the smallest per-texel angle to get a conservative estimate
  43179. // of the number of texels needed to be covered in width and height order to filter the
  43180. // region. the bounding box for the center taps face is defined first, and if the
  43181. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  43182. // defined next
  43183. //--------------------------------------------------------------------------------------
  43184. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  43185. // note that pixels within these regions may be rejected
  43186. // based on the anlge
  43187. var iCubeFace;
  43188. var u;
  43189. var v;
  43190. // bounding box per face to specify region to process
  43191. var filterExtents = [];
  43192. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  43193. filterExtents.push(new CMGBoundinBox());
  43194. }
  43195. // min angle a src texel can cover (in degrees)
  43196. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  43197. // angle about center tap to define filter cone
  43198. // filter angle is 1/2 the cone angle
  43199. var filterAngle = filterConeAngle / 2.0;
  43200. //ensure filter angle is larger than a texel
  43201. if (filterAngle < srcTexelAngle) {
  43202. filterAngle = srcTexelAngle;
  43203. }
  43204. //ensure filter cone is always smaller than the hemisphere
  43205. if (filterAngle > 90.0) {
  43206. filterAngle = 90.0;
  43207. }
  43208. // the maximum number of texels in 1D the filter cone angle will cover
  43209. // used to determine bounding box size for filter extents
  43210. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  43211. // ensure conservative region always covers at least one texel
  43212. if (filterSize < 1) {
  43213. filterSize = 1;
  43214. }
  43215. // dotProdThresh threshold based on cone angle to determine whether or not taps
  43216. // reside within the cone angle
  43217. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  43218. // process required faces
  43219. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  43220. //iterate over dst cube map face texel
  43221. for (v = 0; v < dstSize; v++) {
  43222. for (u = 0; u < dstSize; u++) {
  43223. //get center tap direction
  43224. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  43225. //clear old per-face filter extents
  43226. this.clearFilterExtents(filterExtents);
  43227. //define per-face filter extents
  43228. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  43229. //perform filtering of src faces using filter extents
  43230. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  43231. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  43232. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  43233. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  43234. }
  43235. }
  43236. }
  43237. };
  43238. //--------------------------------------------------------------------------------------
  43239. //Clear filter extents for the 6 cube map faces
  43240. //--------------------------------------------------------------------------------------
  43241. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  43242. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  43243. filterExtents[iCubeFaces].clear();
  43244. }
  43245. };
  43246. //--------------------------------------------------------------------------------------
  43247. //Define per-face bounding box filter extents
  43248. //
  43249. // These define conservative texel regions in each of the faces the filter can possibly
  43250. // process. When the pixels in the regions are actually processed, the dot product
  43251. // between the tap vector and the center tap vector is used to determine the weight of
  43252. // the tap and whether or not the tap is within the cone.
  43253. //
  43254. //--------------------------------------------------------------------------------------
  43255. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  43256. //neighboring face and bleed over amount, and width of BBOX for
  43257. // left, right, top, and bottom edges of this face
  43258. var bleedOverAmount = [0, 0, 0, 0];
  43259. var bleedOverBBoxMin = [0, 0, 0, 0];
  43260. var bleedOverBBoxMax = [0, 0, 0, 0];
  43261. var neighborFace;
  43262. var neighborEdge;
  43263. var oppositeFaceIdx;
  43264. //get face idx, and u, v info from center tap dir
  43265. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  43266. var faceIdx = result.x;
  43267. var u = result.y;
  43268. var v = result.z;
  43269. //define bbox size within face
  43270. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  43271. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  43272. filterExtents[faceIdx].clampMin(0, 0, 0);
  43273. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  43274. //u and v extent in face corresponding to center tap
  43275. var minU = filterExtents[faceIdx].min.x;
  43276. var minV = filterExtents[faceIdx].min.y;
  43277. var maxU = filterExtents[faceIdx].max.x;
  43278. var maxV = filterExtents[faceIdx].max.y;
  43279. //bleed over amounts for face across u=0 edge (left)
  43280. bleedOverAmount[0] = (bboxSize - u);
  43281. bleedOverBBoxMin[0] = minV;
  43282. bleedOverBBoxMax[0] = maxV;
  43283. //bleed over amounts for face across u=1 edge (right)
  43284. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  43285. bleedOverBBoxMin[1] = minV;
  43286. bleedOverBBoxMax[1] = maxV;
  43287. //bleed over to face across v=0 edge (up)
  43288. bleedOverAmount[2] = (bboxSize - v);
  43289. bleedOverBBoxMin[2] = minU;
  43290. bleedOverBBoxMax[2] = maxU;
  43291. //bleed over to face across v=1 edge (down)
  43292. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  43293. bleedOverBBoxMin[3] = minU;
  43294. bleedOverBBoxMax[3] = maxU;
  43295. //compute bleed over regions in neighboring faces
  43296. for (var i = 0; i < 4; i++) {
  43297. if (bleedOverAmount[i] > 0) {
  43298. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  43299. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  43300. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  43301. // be flipped: the cases are
  43302. // if a left edge mates with a left or bottom edge on the neighbor
  43303. // if a top edge mates with a top or right edge on the neighbor
  43304. // if a right edge mates with a right or top edge on the neighbor
  43305. // if a bottom edge mates with a bottom or left edge on the neighbor
  43306. //Seeing as the edges are enumerated as follows
  43307. // left =0
  43308. // right =1
  43309. // top =2
  43310. // bottom =3
  43311. //
  43312. // so if the edge enums are the same, or the sum of the enums == 3,
  43313. // the bbox needs to be flipped
  43314. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  43315. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  43316. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  43317. }
  43318. //The way the bounding box is extended onto the neighboring face
  43319. // depends on which edge of neighboring face abuts with this one
  43320. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  43321. case PMREMGenerator.CP_EDGE_LEFT:
  43322. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  43323. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  43324. break;
  43325. case PMREMGenerator.CP_EDGE_RIGHT:
  43326. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  43327. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  43328. break;
  43329. case PMREMGenerator.CP_EDGE_TOP:
  43330. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  43331. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  43332. break;
  43333. case PMREMGenerator.CP_EDGE_BOTTOM:
  43334. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  43335. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  43336. break;
  43337. }
  43338. //clamp filter extents in non-center tap faces to remain within surface
  43339. filterExtents[neighborFace].clampMin(0, 0, 0);
  43340. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  43341. }
  43342. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  43343. // from the center tap face, then process the opposite face entirely for now.
  43344. //Note that the cases in which this happens, what usually happens is that
  43345. // more than one edge bleeds onto the opposite face, and the bounding box
  43346. // encompasses the entire cube map face.
  43347. if (bleedOverAmount[i] > srcSize) {
  43348. //determine opposite face
  43349. switch (faceIdx) {
  43350. case PMREMGenerator.CP_FACE_X_POS:
  43351. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  43352. break;
  43353. case PMREMGenerator.CP_FACE_X_NEG:
  43354. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  43355. break;
  43356. case PMREMGenerator.CP_FACE_Y_POS:
  43357. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  43358. break;
  43359. case PMREMGenerator.CP_FACE_Y_NEG:
  43360. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  43361. break;
  43362. case PMREMGenerator.CP_FACE_Z_POS:
  43363. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  43364. break;
  43365. case PMREMGenerator.CP_FACE_Z_NEG:
  43366. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  43367. break;
  43368. default:
  43369. break;
  43370. }
  43371. //just encompass entire face for now
  43372. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  43373. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  43374. }
  43375. }
  43376. };
  43377. //--------------------------------------------------------------------------------------
  43378. //ProcessFilterExtents
  43379. // Process bounding box in each cube face
  43380. //
  43381. //--------------------------------------------------------------------------------------
  43382. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  43383. //accumulators are 64-bit floats in order to have the precision needed
  43384. // over a summation of a large number of pixels
  43385. var dstAccum = [0, 0, 0, 0];
  43386. var weightAccum = 0;
  43387. var k = 0;
  43388. var nSrcChannels = this.numChannels;
  43389. // norm cube map and srcCubeMap have same face width
  43390. var faceWidth = srcSize;
  43391. //amount to add to pointer to move to next scanline in images
  43392. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  43393. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  43394. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  43395. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  43396. // iterate over cubefaces
  43397. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  43398. //if bbox is non empty
  43399. if (!filterExtents[iFaceIdx].empty()) {
  43400. var uStart = filterExtents[iFaceIdx].min.x;
  43401. var vStart = filterExtents[iFaceIdx].min.y;
  43402. var uEnd = filterExtents[iFaceIdx].max.x;
  43403. var vEnd = filterExtents[iFaceIdx].max.y;
  43404. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  43405. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  43406. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  43407. for (var v = vStart; v <= vEnd; v++) {
  43408. var normCubeRowWalk = 0;
  43409. var srcCubeRowWalk = 0;
  43410. for (var u = uStart; u <= uEnd; u++) {
  43411. //pointer to direction in cube map associated with texel
  43412. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  43413. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  43414. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  43415. //check dot product to see if texel is within cone
  43416. var tapDotProd = texelVectX * centerTapDir.x +
  43417. texelVectY * centerTapDir.y +
  43418. texelVectZ * centerTapDir.z;
  43419. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  43420. //solid angle stored in 4th channel of normalizer/solid angle cube map
  43421. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  43422. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  43423. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  43424. // so just adding one to specularpower do the trick.
  43425. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  43426. //iterate over channels
  43427. for (k = 0; k < nSrcChannels; k++) {
  43428. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  43429. srcCubeRowWalk++;
  43430. }
  43431. weightAccum += weight; //accumulate weight
  43432. }
  43433. else {
  43434. //step across source pixel
  43435. srcCubeRowWalk += nSrcChannels;
  43436. }
  43437. normCubeRowWalk += 4; // 4 channels per norm cube map.
  43438. }
  43439. startIndexNormCubeMap += normCubePitch;
  43440. startIndexSrcCubeMap += srcCubePitch;
  43441. }
  43442. }
  43443. }
  43444. //divide through by weights if weight is non zero
  43445. if (weightAccum != 0.0) {
  43446. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  43447. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  43448. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  43449. if (this.numChannels > 3) {
  43450. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  43451. }
  43452. }
  43453. else {
  43454. // otherwise sample nearest
  43455. // get face idx and u, v texel coordinate in face
  43456. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  43457. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  43458. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  43459. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  43460. if (this.numChannels > 3) {
  43461. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  43462. }
  43463. }
  43464. return PMREMGenerator._vectorTemp;
  43465. };
  43466. //--------------------------------------------------------------------------------------
  43467. // Fixup cube edges
  43468. //
  43469. // average texels on cube map faces across the edges
  43470. // WARP/BENT Method Only.
  43471. //--------------------------------------------------------------------------------------
  43472. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  43473. var k;
  43474. var j;
  43475. var i;
  43476. var iFace;
  43477. var iCorner = 0;
  43478. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  43479. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  43480. // note that if functionality to filter across the three texels for each corner, then
  43481. //indexed by corner and face idx. the array contains the face the start points belongs to.
  43482. var cornerPtr = [
  43483. [[], [], []],
  43484. [[], [], []],
  43485. [[], [], []],
  43486. [[], [], []],
  43487. [[], [], []],
  43488. [[], [], []],
  43489. [[], [], []],
  43490. [[], [], []]
  43491. ];
  43492. //if there is no fixup, or fixup width = 0, do nothing
  43493. if (cubeMapSize < 1) {
  43494. return;
  43495. }
  43496. //special case 1x1 cubemap, average face colors
  43497. if (cubeMapSize == 1) {
  43498. //iterate over channels
  43499. for (k = 0; k < this.numChannels; k++) {
  43500. var accum = 0.0;
  43501. //iterate over faces to accumulate face colors
  43502. for (iFace = 0; iFace < 6; iFace++) {
  43503. accum += cubeMap[iFace][k];
  43504. }
  43505. //compute average over 6 face colors
  43506. accum /= 6.0;
  43507. //iterate over faces to distribute face colors
  43508. for (iFace = 0; iFace < 6; iFace++) {
  43509. cubeMap[iFace][k] = accum;
  43510. }
  43511. }
  43512. return;
  43513. }
  43514. //iterate over faces to collect list of corner texel pointers
  43515. for (iFace = 0; iFace < 6; iFace++) {
  43516. //the 4 corner pointers for this face
  43517. faceCornerStartIndicies[0] = [iFace, 0];
  43518. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  43519. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  43520. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  43521. //iterate over face corners to collect cube corner pointers
  43522. for (iCorner = 0; iCorner < 4; iCorner++) {
  43523. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  43524. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  43525. cornerNumPtrs[corner]++;
  43526. }
  43527. }
  43528. //iterate over corners to average across corner tap values
  43529. for (iCorner = 0; iCorner < 8; iCorner++) {
  43530. for (k = 0; k < this.numChannels; k++) {
  43531. var cornerTapAccum = 0.0;
  43532. //iterate over corner texels and average results
  43533. for (i = 0; i < 3; i++) {
  43534. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  43535. }
  43536. //divide by 3 to compute average of corner tap values
  43537. cornerTapAccum *= (1.0 / 3.0);
  43538. //iterate over corner texels and average results
  43539. for (i = 0; i < 3; i++) {
  43540. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  43541. }
  43542. }
  43543. }
  43544. //iterate over the twelve edges of the cube to average across edges
  43545. for (i = 0; i < 12; i++) {
  43546. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  43547. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  43548. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  43549. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  43550. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  43551. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  43552. var edgeWalk = 0;
  43553. var neighborEdgeWalk = 0;
  43554. //Determine walking pointers based on edge type
  43555. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  43556. switch (edge) {
  43557. case PMREMGenerator.CP_EDGE_LEFT:
  43558. // no change to faceEdgeStartPtr
  43559. edgeWalk = this.numChannels * cubeMapSize;
  43560. break;
  43561. case PMREMGenerator.CP_EDGE_RIGHT:
  43562. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  43563. edgeWalk = this.numChannels * cubeMapSize;
  43564. break;
  43565. case PMREMGenerator.CP_EDGE_TOP:
  43566. // no change to faceEdgeStartPtr
  43567. edgeWalk = this.numChannels;
  43568. break;
  43569. case PMREMGenerator.CP_EDGE_BOTTOM:
  43570. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  43571. edgeWalk = this.numChannels;
  43572. break;
  43573. }
  43574. //For certain types of edge abutments, the neighbor edge walk needs to
  43575. // be flipped: the cases are
  43576. // if a left edge mates with a left or bottom edge on the neighbor
  43577. // if a top edge mates with a top or right edge on the neighbor
  43578. // if a right edge mates with a right or top edge on the neighbor
  43579. // if a bottom edge mates with a bottom or left edge on the neighbor
  43580. //Seeing as the edges are enumerated as follows
  43581. // left =0
  43582. // right =1
  43583. // top =2
  43584. // bottom =3
  43585. //
  43586. //If the edge enums are the same, or the sum of the enums == 3,
  43587. // the neighbor edge walk needs to be flipped
  43588. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  43589. switch (neighborEdge) {
  43590. case PMREMGenerator.CP_EDGE_LEFT:
  43591. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  43592. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  43593. break;
  43594. case PMREMGenerator.CP_EDGE_RIGHT:
  43595. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  43596. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  43597. break;
  43598. case PMREMGenerator.CP_EDGE_TOP:
  43599. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  43600. neighborEdgeWalk = -this.numChannels;
  43601. break;
  43602. case PMREMGenerator.CP_EDGE_BOTTOM:
  43603. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  43604. neighborEdgeWalk = -this.numChannels;
  43605. break;
  43606. }
  43607. }
  43608. else {
  43609. //swapped direction neighbor edge walk
  43610. switch (neighborEdge) {
  43611. case PMREMGenerator.CP_EDGE_LEFT:
  43612. //no change to neighborEdgeStartPtr for this case since it points
  43613. // to the upper left corner already
  43614. neighborEdgeWalk = this.numChannels * cubeMapSize;
  43615. break;
  43616. case PMREMGenerator.CP_EDGE_RIGHT:
  43617. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  43618. neighborEdgeWalk = this.numChannels * cubeMapSize;
  43619. break;
  43620. case PMREMGenerator.CP_EDGE_TOP:
  43621. //no change to neighborEdgeStartPtr for this case since it points
  43622. // to the upper left corner already
  43623. neighborEdgeWalk = this.numChannels;
  43624. break;
  43625. case PMREMGenerator.CP_EDGE_BOTTOM:
  43626. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  43627. neighborEdgeWalk = this.numChannels;
  43628. break;
  43629. }
  43630. }
  43631. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  43632. //nearby neighborhood
  43633. //step ahead one texel on edge
  43634. edgeStartIndex += edgeWalk;
  43635. neighborEdgeStartIndex += neighborEdgeWalk;
  43636. // note that this loop does not process the corner texels, since they have already been
  43637. // averaged across faces across earlier
  43638. for (j = 1; j < (cubeMapSize - 1); j++) {
  43639. //for each set of taps along edge, average them
  43640. // and rewrite the results into the edges
  43641. for (k = 0; k < this.numChannels; k++) {
  43642. var edgeTap = cubeMap[face][edgeStartIndex + k];
  43643. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  43644. //compute average of tap intensity values
  43645. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  43646. //propagate average of taps to edge taps
  43647. cubeMap[face][edgeStartIndex + k] = avgTap;
  43648. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  43649. }
  43650. edgeStartIndex += edgeWalk;
  43651. neighborEdgeStartIndex += neighborEdgeWalk;
  43652. }
  43653. }
  43654. };
  43655. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  43656. PMREMGenerator.CP_UDIR = 0;
  43657. PMREMGenerator.CP_VDIR = 1;
  43658. PMREMGenerator.CP_FACEAXIS = 2;
  43659. //used to index cube faces
  43660. PMREMGenerator.CP_FACE_X_POS = 0;
  43661. PMREMGenerator.CP_FACE_X_NEG = 1;
  43662. PMREMGenerator.CP_FACE_Y_POS = 2;
  43663. PMREMGenerator.CP_FACE_Y_NEG = 3;
  43664. PMREMGenerator.CP_FACE_Z_POS = 4;
  43665. PMREMGenerator.CP_FACE_Z_NEG = 5;
  43666. //used to index image edges
  43667. // NOTE.. the actual number corresponding to the edge is important
  43668. // do not change these, or the code will break
  43669. //
  43670. // CP_EDGE_LEFT is u = 0
  43671. // CP_EDGE_RIGHT is u = width-1
  43672. // CP_EDGE_TOP is v = 0
  43673. // CP_EDGE_BOTTOM is v = height-1
  43674. PMREMGenerator.CP_EDGE_LEFT = 0;
  43675. PMREMGenerator.CP_EDGE_RIGHT = 1;
  43676. PMREMGenerator.CP_EDGE_TOP = 2;
  43677. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  43678. //corners of CUBE map (P or N specifys if it corresponds to the
  43679. // positive or negative direction each of X, Y, and Z
  43680. PMREMGenerator.CP_CORNER_NNN = 0;
  43681. PMREMGenerator.CP_CORNER_NNP = 1;
  43682. PMREMGenerator.CP_CORNER_NPN = 2;
  43683. PMREMGenerator.CP_CORNER_NPP = 3;
  43684. PMREMGenerator.CP_CORNER_PNN = 4;
  43685. PMREMGenerator.CP_CORNER_PNP = 5;
  43686. PMREMGenerator.CP_CORNER_PPN = 6;
  43687. PMREMGenerator.CP_CORNER_PPP = 7;
  43688. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  43689. //3x2 matrices that map cube map indexing vectors in 3d
  43690. // (after face selection and divide through by the
  43691. // _ABSOLUTE VALUE_ of the max coord)
  43692. // into NVC space
  43693. //Note this currently assumes the D3D cube face ordering and orientation
  43694. PMREMGenerator._sgFace2DMapping = [
  43695. //XPOS face
  43696. [[0, 0, -1],
  43697. [0, -1, 0],
  43698. [1, 0, 0]],
  43699. //XNEG face
  43700. [[0, 0, 1],
  43701. [0, -1, 0],
  43702. [-1, 0, 0]],
  43703. //YPOS face
  43704. [[1, 0, 0],
  43705. [0, 0, 1],
  43706. [0, 1, 0]],
  43707. //YNEG face
  43708. [[1, 0, 0],
  43709. [0, 0, -1],
  43710. [0, -1, 0]],
  43711. //ZPOS face
  43712. [[1, 0, 0],
  43713. [0, -1, 0],
  43714. [0, 0, 1]],
  43715. //ZNEG face
  43716. [[-1, 0, 0],
  43717. [0, -1, 0],
  43718. [0, 0, -1]],
  43719. ];
  43720. //------------------------------------------------------------------------------
  43721. // D3D cube map face specification
  43722. // mapping from 3D x,y,z cube map lookup coordinates
  43723. // to 2D within face u,v coordinates
  43724. //
  43725. // --------------------> U direction
  43726. // | (within-face texture space)
  43727. // | _____
  43728. // | | |
  43729. // | | +Y |
  43730. // | _____|_____|_____ _____
  43731. // | | | | | |
  43732. // | | -X | +Z | +X | -Z |
  43733. // | |_____|_____|_____|_____|
  43734. // | | |
  43735. // | | -Y |
  43736. // | |_____|
  43737. // |
  43738. // v V direction
  43739. // (within-face texture space)
  43740. //------------------------------------------------------------------------------
  43741. //Information about neighbors and how texture coorrdinates change across faces
  43742. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  43743. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  43744. //Note this currently assumes the D3D cube face ordering and orientation
  43745. PMREMGenerator._sgCubeNgh = [
  43746. //XPOS face
  43747. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  43748. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  43749. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  43750. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  43751. //XNEG face
  43752. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  43753. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  43754. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  43755. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  43756. //YPOS face
  43757. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  43758. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  43759. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  43760. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  43761. //YNEG face
  43762. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  43763. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43764. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43765. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  43766. //ZPOS face
  43767. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  43768. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  43769. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43770. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  43771. //ZNEG face
  43772. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  43773. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  43774. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  43775. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  43776. ];
  43777. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  43778. // this table is used to average over the edges.
  43779. PMREMGenerator._sgCubeEdgeList = [
  43780. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  43781. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  43782. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  43783. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43784. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  43785. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  43786. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  43787. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  43788. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  43789. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43790. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  43791. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  43792. ];
  43793. //Information about which of the 8 cube corners are correspond to the
  43794. // the 4 corners in each cube face
  43795. // the order is upper left, upper right, lower left, lower right
  43796. PMREMGenerator._sgCubeCornerList = [
  43797. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  43798. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  43799. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  43800. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  43801. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  43802. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  43803. ];
  43804. return PMREMGenerator;
  43805. })();
  43806. Internals.PMREMGenerator = PMREMGenerator;
  43807. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43808. })(BABYLON || (BABYLON = {}));
  43809. var BABYLON;
  43810. (function (BABYLON) {
  43811. /**
  43812. * This represents a texture coming from an HDR input.
  43813. *
  43814. * The only supported format is currently panorama picture stored in RGBE format.
  43815. * Example of such files can be found on HDRLib: http://hdrlib.com/
  43816. */
  43817. var HDRCubeTexture = (function (_super) {
  43818. __extends(HDRCubeTexture, _super);
  43819. /**
  43820. * Instantiates an HDRTexture from the following parameters.
  43821. *
  43822. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  43823. * @param scene The scene the texture will be used in
  43824. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  43825. * @param noMipmap Forces to not generate the mipmap if true
  43826. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  43827. * @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)
  43828. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  43829. */
  43830. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  43831. if (noMipmap === void 0) { noMipmap = false; }
  43832. if (generateHarmonics === void 0) { generateHarmonics = true; }
  43833. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  43834. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  43835. _super.call(this, scene);
  43836. this._useInGammaSpace = false;
  43837. this._generateHarmonics = true;
  43838. /**
  43839. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  43840. */
  43841. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  43842. /**
  43843. * The spherical polynomial data extracted from the texture.
  43844. */
  43845. this.sphericalPolynomial = null;
  43846. /**
  43847. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  43848. * This is usefull at run time to apply the good shader.
  43849. */
  43850. this.isPMREM = false;
  43851. this.name = url;
  43852. this.url = url;
  43853. this._noMipmap = noMipmap;
  43854. this.hasAlpha = false;
  43855. this._size = size;
  43856. this._useInGammaSpace = useInGammaSpace;
  43857. this._usePMREMGenerator = usePMREMGenerator && scene.getEngine().getCaps().textureLOD;
  43858. this.isPMREM = this._usePMREMGenerator;
  43859. if (!url) {
  43860. return;
  43861. }
  43862. this._texture = this._getFromCache(url, noMipmap);
  43863. if (!this._texture) {
  43864. if (!scene.useDelayedTextureLoading) {
  43865. this.loadTexture();
  43866. }
  43867. else {
  43868. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  43869. }
  43870. }
  43871. this.isCube = true;
  43872. this._textureMatrix = BABYLON.Matrix.Identity();
  43873. }
  43874. HDRCubeTexture.prototype.loadTexture = function () {
  43875. var _this = this;
  43876. var callback = function (buffer) {
  43877. // Extract the raw linear data.
  43878. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  43879. // Generate harmonics if needed.
  43880. if (_this._generateHarmonics) {
  43881. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  43882. }
  43883. var results = [];
  43884. var byteArray = null;
  43885. // Create uintarray fallback.
  43886. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  43887. // 3 channels of 1 bytes per pixel in bytes.
  43888. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  43889. byteArray = new Uint8Array(byteBuffer);
  43890. }
  43891. // Push each faces.
  43892. for (var j = 0; j < 6; j++) {
  43893. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  43894. // If special cases.
  43895. if (_this._useInGammaSpace || byteArray) {
  43896. for (var i = 0; i < _this._size * _this._size; i++) {
  43897. // Put in gamma space if requested.
  43898. if (_this._useInGammaSpace) {
  43899. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  43900. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  43901. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  43902. }
  43903. // Convert to int texture for fallback.
  43904. if (byteArray) {
  43905. // R
  43906. byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  43907. byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
  43908. // G
  43909. byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  43910. byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
  43911. // B
  43912. byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  43913. byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
  43914. }
  43915. }
  43916. }
  43917. results.push(dataFace);
  43918. }
  43919. return results;
  43920. };
  43921. var mipmapGenerator = null;
  43922. if (!this._noMipmap && this._usePMREMGenerator) {
  43923. mipmapGenerator = function (data) {
  43924. // Custom setup of the generator matching with the PBR shader values.
  43925. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  43926. return generator.filterCubeMap();
  43927. };
  43928. }
  43929. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback, mipmapGenerator);
  43930. };
  43931. HDRCubeTexture.prototype.clone = function () {
  43932. var newTexture = new HDRCubeTexture(this.url, this.getScene(), this._size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  43933. // Base texture
  43934. newTexture.level = this.level;
  43935. newTexture.wrapU = this.wrapU;
  43936. newTexture.wrapV = this.wrapV;
  43937. newTexture.coordinatesIndex = this.coordinatesIndex;
  43938. newTexture.coordinatesMode = this.coordinatesMode;
  43939. return newTexture;
  43940. };
  43941. // Methods
  43942. HDRCubeTexture.prototype.delayLoad = function () {
  43943. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  43944. return;
  43945. }
  43946. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  43947. this._texture = this._getFromCache(this.url, this._noMipmap);
  43948. if (!this._texture) {
  43949. this.loadTexture();
  43950. }
  43951. };
  43952. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  43953. return this._textureMatrix;
  43954. };
  43955. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  43956. var texture = null;
  43957. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  43958. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  43959. texture.name = parsedTexture.name;
  43960. texture.hasAlpha = parsedTexture.hasAlpha;
  43961. texture.level = parsedTexture.level;
  43962. texture.coordinatesMode = parsedTexture.coordinatesMode;
  43963. }
  43964. return texture;
  43965. };
  43966. HDRCubeTexture.prototype.serialize = function () {
  43967. if (!this.name) {
  43968. return null;
  43969. }
  43970. var serializationObject = {};
  43971. serializationObject.name = this.name;
  43972. serializationObject.hasAlpha = this.hasAlpha;
  43973. serializationObject.isCube = true;
  43974. serializationObject.level = this.level;
  43975. serializationObject.size = this._size;
  43976. serializationObject.coordinatesMode = this.coordinatesMode;
  43977. serializationObject.useInGammaSpace = this._useInGammaSpace;
  43978. serializationObject.generateHarmonics = this._generateHarmonics;
  43979. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  43980. return serializationObject;
  43981. };
  43982. HDRCubeTexture._facesMapping = [
  43983. "right",
  43984. "up",
  43985. "front",
  43986. "left",
  43987. "down",
  43988. "back"
  43989. ];
  43990. return HDRCubeTexture;
  43991. })(BABYLON.BaseTexture);
  43992. BABYLON.HDRCubeTexture = HDRCubeTexture;
  43993. })(BABYLON || (BABYLON = {}));
  43994. var BABYLON;
  43995. (function (BABYLON) {
  43996. var Debug;
  43997. (function (Debug) {
  43998. /**
  43999. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  44000. */
  44001. var SkeletonViewer = (function () {
  44002. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  44003. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  44004. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  44005. this.skeleton = skeleton;
  44006. this.mesh = mesh;
  44007. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  44008. this.renderingGroupId = renderingGroupId;
  44009. this.color = BABYLON.Color3.White();
  44010. this._debugLines = [];
  44011. this._isEnabled = false;
  44012. this._scene = scene;
  44013. this.update();
  44014. this._renderFunction = this.update.bind(this);
  44015. }
  44016. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  44017. get: function () {
  44018. return this._isEnabled;
  44019. },
  44020. set: function (value) {
  44021. if (this._isEnabled === value) {
  44022. return;
  44023. }
  44024. this._isEnabled = value;
  44025. if (value) {
  44026. this._scene.registerBeforeRender(this._renderFunction);
  44027. }
  44028. else {
  44029. this._scene.unregisterBeforeRender(this._renderFunction);
  44030. }
  44031. },
  44032. enumerable: true,
  44033. configurable: true
  44034. });
  44035. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  44036. if (x === void 0) { x = 0; }
  44037. if (y === void 0) { y = 0; }
  44038. if (z === void 0) { z = 0; }
  44039. var tmat = BABYLON.Tmp.Matrix[0];
  44040. var parentBone = bone.getParent();
  44041. tmat.copyFrom(bone.getLocalMatrix());
  44042. if (x !== 0 || y !== 0 || z !== 0) {
  44043. var tmat2 = BABYLON.Tmp.Matrix[1];
  44044. BABYLON.Matrix.IdentityToRef(tmat2);
  44045. tmat2.m[12] = x;
  44046. tmat2.m[13] = y;
  44047. tmat2.m[14] = z;
  44048. tmat2.multiplyToRef(tmat, tmat);
  44049. }
  44050. if (parentBone) {
  44051. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  44052. }
  44053. tmat.multiplyToRef(meshMat, tmat);
  44054. position.x = tmat.m[12];
  44055. position.y = tmat.m[13];
  44056. position.z = tmat.m[14];
  44057. };
  44058. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  44059. var len = bones.length;
  44060. for (var i = 0; i < len; i++) {
  44061. var bone = bones[i];
  44062. var points = this._debugLines[i];
  44063. if (!points) {
  44064. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  44065. this._debugLines[i] = points;
  44066. }
  44067. this._getBonePosition(points[0], bone, meshMat);
  44068. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  44069. }
  44070. };
  44071. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  44072. var len = bones.length;
  44073. var boneNum = 0;
  44074. for (var i = len - 1; i >= 0; i--) {
  44075. var childBone = bones[i];
  44076. var parentBone = childBone.getParent();
  44077. if (!parentBone) {
  44078. continue;
  44079. }
  44080. var points = this._debugLines[boneNum];
  44081. if (!points) {
  44082. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  44083. this._debugLines[boneNum] = points;
  44084. }
  44085. this._getBonePosition(points[0], childBone, meshMat);
  44086. this._getBonePosition(points[1], parentBone, meshMat);
  44087. boneNum++;
  44088. }
  44089. };
  44090. SkeletonViewer.prototype.update = function () {
  44091. if (this.autoUpdateBonesMatrices) {
  44092. this._updateBoneMatrix(this.skeleton.bones[0]);
  44093. }
  44094. if (this.skeleton.bones[0].length === undefined) {
  44095. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  44096. }
  44097. else {
  44098. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  44099. }
  44100. if (!this._debugMesh) {
  44101. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  44102. this._debugMesh.renderingGroupId = this.renderingGroupId;
  44103. }
  44104. else {
  44105. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  44106. }
  44107. this._debugMesh.color = this.color;
  44108. };
  44109. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  44110. if (bone.getParent()) {
  44111. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  44112. }
  44113. var children = bone.children;
  44114. var len = children.length;
  44115. for (var i = 0; i < len; i++) {
  44116. this._updateBoneMatrix(children[i]);
  44117. }
  44118. };
  44119. SkeletonViewer.prototype.dispose = function () {
  44120. if (this._debugMesh) {
  44121. this.isEnabled = false;
  44122. this._debugMesh.dispose();
  44123. this._debugMesh = null;
  44124. }
  44125. };
  44126. return SkeletonViewer;
  44127. })();
  44128. Debug.SkeletonViewer = SkeletonViewer;
  44129. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  44130. })(BABYLON || (BABYLON = {}));
  44131. var BABYLON;
  44132. (function (BABYLON) {
  44133. var maxSimultaneousLights = 4;
  44134. var PBRMaterialDefines = (function (_super) {
  44135. __extends(PBRMaterialDefines, _super);
  44136. function PBRMaterialDefines() {
  44137. _super.call(this);
  44138. this.ALBEDO = false;
  44139. this.AMBIENT = false;
  44140. this.OPACITY = false;
  44141. this.OPACITYRGB = false;
  44142. this.REFLECTION = false;
  44143. this.EMISSIVE = false;
  44144. this.REFLECTIVITY = false;
  44145. this.BUMP = false;
  44146. this.PARALLAX = false;
  44147. this.PARALLAXOCCLUSION = false;
  44148. this.SPECULAROVERALPHA = false;
  44149. this.CLIPPLANE = false;
  44150. this.ALPHATEST = false;
  44151. this.ALPHAFROMALBEDO = false;
  44152. this.POINTSIZE = false;
  44153. this.FOG = false;
  44154. this.LIGHT0 = false;
  44155. this.LIGHT1 = false;
  44156. this.LIGHT2 = false;
  44157. this.LIGHT3 = false;
  44158. this.SPOTLIGHT0 = false;
  44159. this.SPOTLIGHT1 = false;
  44160. this.SPOTLIGHT2 = false;
  44161. this.SPOTLIGHT3 = false;
  44162. this.HEMILIGHT0 = false;
  44163. this.HEMILIGHT1 = false;
  44164. this.HEMILIGHT2 = false;
  44165. this.HEMILIGHT3 = false;
  44166. this.POINTLIGHT0 = false;
  44167. this.POINTLIGHT1 = false;
  44168. this.POINTLIGHT2 = false;
  44169. this.POINTLIGHT3 = false;
  44170. this.DIRLIGHT0 = false;
  44171. this.DIRLIGHT1 = false;
  44172. this.DIRLIGHT2 = false;
  44173. this.DIRLIGHT3 = false;
  44174. this.SPECULARTERM = false;
  44175. this.SHADOW0 = false;
  44176. this.SHADOW1 = false;
  44177. this.SHADOW2 = false;
  44178. this.SHADOW3 = false;
  44179. this.SHADOWS = false;
  44180. this.SHADOWVSM0 = false;
  44181. this.SHADOWVSM1 = false;
  44182. this.SHADOWVSM2 = false;
  44183. this.SHADOWVSM3 = false;
  44184. this.SHADOWPCF0 = false;
  44185. this.SHADOWPCF1 = false;
  44186. this.SHADOWPCF2 = false;
  44187. this.SHADOWPCF3 = false;
  44188. this.OPACITYFRESNEL = false;
  44189. this.EMISSIVEFRESNEL = false;
  44190. this.FRESNEL = false;
  44191. this.NORMAL = false;
  44192. this.UV1 = false;
  44193. this.UV2 = false;
  44194. this.VERTEXCOLOR = false;
  44195. this.VERTEXALPHA = false;
  44196. this.NUM_BONE_INFLUENCERS = 0;
  44197. this.BonesPerMesh = 0;
  44198. this.INSTANCES = false;
  44199. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44200. this.MICROSURFACEAUTOMATIC = false;
  44201. this.EMISSIVEASILLUMINATION = false;
  44202. this.LINKEMISSIVEWITHALBEDO = false;
  44203. this.LIGHTMAP = false;
  44204. this.USELIGHTMAPASSHADOWMAP = false;
  44205. this.REFLECTIONMAP_3D = false;
  44206. this.REFLECTIONMAP_SPHERICAL = false;
  44207. this.REFLECTIONMAP_PLANAR = false;
  44208. this.REFLECTIONMAP_CUBIC = false;
  44209. this.REFLECTIONMAP_PROJECTION = false;
  44210. this.REFLECTIONMAP_SKYBOX = false;
  44211. this.REFLECTIONMAP_EXPLICIT = false;
  44212. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44213. this.INVERTCUBICMAP = false;
  44214. this.LOGARITHMICDEPTH = false;
  44215. this.CAMERATONEMAP = false;
  44216. this.CAMERACONTRAST = false;
  44217. this.OVERLOADEDVALUES = false;
  44218. this.OVERLOADEDSHADOWVALUES = false;
  44219. this.USESPHERICALFROMREFLECTIONMAP = false;
  44220. this.REFRACTION = false;
  44221. this.REFRACTIONMAP_3D = false;
  44222. this.LINKREFRACTIONTOTRANSPARENCY = false;
  44223. this.REFRACTIONMAPINLINEARSPACE = false;
  44224. this.LODBASEDMICROSFURACE = false;
  44225. this.USEPHYSICALLIGHTFALLOFF = false;
  44226. this.RADIANCEOVERALPHA = false;
  44227. this.USEPMREMREFLECTION = false;
  44228. this.USEPMREMREFRACTION = false;
  44229. this._keys = Object.keys(this);
  44230. }
  44231. return PBRMaterialDefines;
  44232. })(BABYLON.MaterialDefines);
  44233. /**
  44234. * The Physically based material of BJS.
  44235. *
  44236. * This offers the main features of a standard PBR material.
  44237. * For more information, please refer to the documentation :
  44238. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44239. */
  44240. var PBRMaterial = (function (_super) {
  44241. __extends(PBRMaterial, _super);
  44242. /**
  44243. * Instantiates a new PBRMaterial instance.
  44244. *
  44245. * @param name The material name
  44246. * @param scene The scene the material will be use in.
  44247. */
  44248. function PBRMaterial(name, scene) {
  44249. var _this = this;
  44250. _super.call(this, name, scene);
  44251. /**
  44252. * Intensity of the direct lights e.g. the four lights available in your scene.
  44253. * This impacts both the direct diffuse and specular highlights.
  44254. */
  44255. this.directIntensity = 1.0;
  44256. /**
  44257. * Intensity of the emissive part of the material.
  44258. * This helps controlling the emissive effect without modifying the emissive color.
  44259. */
  44260. this.emissiveIntensity = 1.0;
  44261. /**
  44262. * Intensity of the environment e.g. how much the environment will light the object
  44263. * either through harmonics for rough material or through the refelction for shiny ones.
  44264. */
  44265. this.environmentIntensity = 1.0;
  44266. /**
  44267. * This is a special control allowing the reduction of the specular highlights coming from the
  44268. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44269. */
  44270. this.specularIntensity = 1.0;
  44271. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  44272. /**
  44273. * Debug Control allowing disabling the bump map on this material.
  44274. */
  44275. this.disableBumpMap = false;
  44276. /**
  44277. * Debug Control helping enforcing or dropping the darkness of shadows.
  44278. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  44279. */
  44280. this.overloadedShadowIntensity = 1.0;
  44281. /**
  44282. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  44283. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  44284. */
  44285. this.overloadedShadeIntensity = 1.0;
  44286. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  44287. /**
  44288. * The camera exposure used on this material.
  44289. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44290. * This corresponds to a photographic exposure.
  44291. */
  44292. this.cameraExposure = 1.0;
  44293. /**
  44294. * The camera contrast used on this material.
  44295. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  44296. */
  44297. this.cameraContrast = 1.0;
  44298. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  44299. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  44300. /**
  44301. * Debug Control allowing to overload the ambient color.
  44302. * This as to be use with the overloadedAmbientIntensity parameter.
  44303. */
  44304. this.overloadedAmbient = BABYLON.Color3.White();
  44305. /**
  44306. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  44307. */
  44308. this.overloadedAmbientIntensity = 0.0;
  44309. /**
  44310. * Debug Control allowing to overload the albedo color.
  44311. * This as to be use with the overloadedAlbedoIntensity parameter.
  44312. */
  44313. this.overloadedAlbedo = BABYLON.Color3.White();
  44314. /**
  44315. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  44316. */
  44317. this.overloadedAlbedoIntensity = 0.0;
  44318. /**
  44319. * Debug Control allowing to overload the reflectivity color.
  44320. * This as to be use with the overloadedReflectivityIntensity parameter.
  44321. */
  44322. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  44323. /**
  44324. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  44325. */
  44326. this.overloadedReflectivityIntensity = 0.0;
  44327. /**
  44328. * Debug Control allowing to overload the emissive color.
  44329. * This as to be use with the overloadedEmissiveIntensity parameter.
  44330. */
  44331. this.overloadedEmissive = BABYLON.Color3.White();
  44332. /**
  44333. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  44334. */
  44335. this.overloadedEmissiveIntensity = 0.0;
  44336. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  44337. /**
  44338. * Debug Control allowing to overload the reflection color.
  44339. * This as to be use with the overloadedReflectionIntensity parameter.
  44340. */
  44341. this.overloadedReflection = BABYLON.Color3.White();
  44342. /**
  44343. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  44344. */
  44345. this.overloadedReflectionIntensity = 0.0;
  44346. /**
  44347. * Debug Control allowing to overload the microsurface.
  44348. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  44349. */
  44350. this.overloadedMicroSurface = 0.0;
  44351. /**
  44352. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  44353. */
  44354. this.overloadedMicroSurfaceIntensity = 0.0;
  44355. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  44356. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44357. /**
  44358. * AKA Diffuse Color in other nomenclature.
  44359. */
  44360. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44361. /**
  44362. * AKA Specular Color in other nomenclature.
  44363. */
  44364. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44365. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  44366. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44367. /**
  44368. * AKA Glossiness in other nomenclature.
  44369. */
  44370. this.microSurface = 0.9;
  44371. /**
  44372. * source material index of refraction (IOR)' / 'destination material IOR.
  44373. */
  44374. this.indexOfRefraction = 0.66;
  44375. /**
  44376. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44377. */
  44378. this.invertRefractionY = false;
  44379. /**
  44380. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44381. * Materials half opaque for instance using refraction could benefit from this control.
  44382. */
  44383. this.linkRefractionWithTransparency = false;
  44384. /**
  44385. * The emissive and albedo are linked to never be more than one (Energy conservation).
  44386. */
  44387. this.linkEmissiveWithAlbedo = false;
  44388. this.useLightmapAsShadowmap = false;
  44389. /**
  44390. * In this mode, the emissive informtaion will always be added to the lighting once.
  44391. * A light for instance can be thought as emissive.
  44392. */
  44393. this.useEmissiveAsIllumination = false;
  44394. /**
  44395. * Secifies that the alpha is coming form the albedo channel alpha channel.
  44396. */
  44397. this.useAlphaFromAlbedoTexture = false;
  44398. /**
  44399. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44400. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44401. */
  44402. this.useSpecularOverAlpha = true;
  44403. /**
  44404. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44405. */
  44406. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44407. /**
  44408. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44409. * The material will try to infer what glossiness each pixel should be.
  44410. */
  44411. this.useAutoMicroSurfaceFromReflectivityMap = false;
  44412. /**
  44413. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  44414. * the creation of the material.
  44415. */
  44416. this.useScalarInLinearSpace = false;
  44417. /**
  44418. * BJS is using an harcoded light falloff based on a manually sets up range.
  44419. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44420. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44421. */
  44422. this.usePhysicalLightFalloff = true;
  44423. /**
  44424. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44425. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44426. */
  44427. this.useRadianceOverAlpha = true;
  44428. /**
  44429. * Allows using the bump map in parallax mode.
  44430. */
  44431. this.useParallax = false;
  44432. /**
  44433. * Allows using the bump map in parallax occlusion mode.
  44434. */
  44435. this.useParallaxOcclusion = false;
  44436. /**
  44437. * Controls the scale bias of the parallax mode.
  44438. */
  44439. this.parallaxScaleBias = 0.05;
  44440. this.disableLighting = false;
  44441. this._renderTargets = new BABYLON.SmartArray(16);
  44442. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  44443. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44444. this._tempColor = new BABYLON.Color3();
  44445. this._defines = new PBRMaterialDefines();
  44446. this._cachedDefines = new PBRMaterialDefines();
  44447. this._myScene = null;
  44448. this._myShadowGenerator = null;
  44449. this._cachedDefines.BonesPerMesh = -1;
  44450. this.getRenderTargetTextures = function () {
  44451. _this._renderTargets.reset();
  44452. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  44453. _this._renderTargets.push(_this.reflectionTexture);
  44454. }
  44455. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  44456. _this._renderTargets.push(_this.refractionTexture);
  44457. }
  44458. return _this._renderTargets;
  44459. };
  44460. }
  44461. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  44462. get: function () {
  44463. return this._useLogarithmicDepth;
  44464. },
  44465. set: function (value) {
  44466. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44467. },
  44468. enumerable: true,
  44469. configurable: true
  44470. });
  44471. PBRMaterial.prototype.needAlphaBlending = function () {
  44472. if (this.linkRefractionWithTransparency) {
  44473. return false;
  44474. }
  44475. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  44476. };
  44477. PBRMaterial.prototype.needAlphaTesting = function () {
  44478. if (this.linkRefractionWithTransparency) {
  44479. return false;
  44480. }
  44481. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  44482. };
  44483. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44484. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  44485. };
  44486. PBRMaterial.prototype.getAlphaTestTexture = function () {
  44487. return this.albedoTexture;
  44488. };
  44489. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  44490. if (!mesh) {
  44491. return true;
  44492. }
  44493. if (this._defines.INSTANCES !== useInstances) {
  44494. return false;
  44495. }
  44496. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  44497. return true;
  44498. }
  44499. return false;
  44500. };
  44501. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  44502. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  44503. };
  44504. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  44505. if (!useScalarInLinear) {
  44506. color.toLinearSpaceToRef(ref);
  44507. }
  44508. else {
  44509. ref.r = color.r;
  44510. ref.g = color.g;
  44511. ref.b = color.b;
  44512. }
  44513. };
  44514. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace) {
  44515. var lightIndex = 0;
  44516. var depthValuesAlreadySet = false;
  44517. for (var index = 0; index < scene.lights.length; index++) {
  44518. var light = scene.lights[index];
  44519. if (!light.isEnabled()) {
  44520. continue;
  44521. }
  44522. if (!light.canAffectMesh(mesh)) {
  44523. continue;
  44524. }
  44525. this._lightRadiuses[lightIndex] = light.radius;
  44526. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  44527. // GAMMA CORRECTION.
  44528. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  44529. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  44530. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, light.range);
  44531. if (defines["SPECULARTERM"]) {
  44532. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  44533. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  44534. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  44535. }
  44536. // Shadows
  44537. if (scene.shadowsEnabled) {
  44538. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  44539. }
  44540. lightIndex++;
  44541. if (lightIndex === maxSimultaneousLights)
  44542. break;
  44543. }
  44544. effect.setFloat4("vLightRadiuses", this._lightRadiuses[0], this._lightRadiuses[1], this._lightRadiuses[2], this._lightRadiuses[3]);
  44545. };
  44546. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  44547. if (this.checkReadyOnlyOnce) {
  44548. if (this._wasPreviouslyReady) {
  44549. return true;
  44550. }
  44551. }
  44552. var scene = this.getScene();
  44553. if (!this.checkReadyOnEveryCall) {
  44554. if (this._renderId === scene.getRenderId()) {
  44555. if (this._checkCache(scene, mesh, useInstances)) {
  44556. return true;
  44557. }
  44558. }
  44559. }
  44560. var engine = scene.getEngine();
  44561. var needNormals = false;
  44562. var needUVs = false;
  44563. this._defines.reset();
  44564. if (scene.texturesEnabled) {
  44565. // Textures
  44566. if (scene.texturesEnabled) {
  44567. if (scene.getEngine().getCaps().textureLOD) {
  44568. this._defines.LODBASEDMICROSFURACE = true;
  44569. }
  44570. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44571. if (!this.albedoTexture.isReady()) {
  44572. return false;
  44573. }
  44574. else {
  44575. needUVs = true;
  44576. this._defines.ALBEDO = true;
  44577. }
  44578. }
  44579. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44580. if (!this.ambientTexture.isReady()) {
  44581. return false;
  44582. }
  44583. else {
  44584. needUVs = true;
  44585. this._defines.AMBIENT = true;
  44586. }
  44587. }
  44588. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44589. if (!this.opacityTexture.isReady()) {
  44590. return false;
  44591. }
  44592. else {
  44593. needUVs = true;
  44594. this._defines.OPACITY = true;
  44595. if (this.opacityTexture.getAlphaFromRGB) {
  44596. this._defines.OPACITYRGB = true;
  44597. }
  44598. }
  44599. }
  44600. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44601. if (!this.reflectionTexture.isReady()) {
  44602. return false;
  44603. }
  44604. else {
  44605. needNormals = true;
  44606. this._defines.REFLECTION = true;
  44607. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44608. this._defines.INVERTCUBICMAP = true;
  44609. }
  44610. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  44611. switch (this.reflectionTexture.coordinatesMode) {
  44612. case BABYLON.Texture.CUBIC_MODE:
  44613. case BABYLON.Texture.INVCUBIC_MODE:
  44614. this._defines.REFLECTIONMAP_CUBIC = true;
  44615. break;
  44616. case BABYLON.Texture.EXPLICIT_MODE:
  44617. this._defines.REFLECTIONMAP_EXPLICIT = true;
  44618. break;
  44619. case BABYLON.Texture.PLANAR_MODE:
  44620. this._defines.REFLECTIONMAP_PLANAR = true;
  44621. break;
  44622. case BABYLON.Texture.PROJECTION_MODE:
  44623. this._defines.REFLECTIONMAP_PROJECTION = true;
  44624. break;
  44625. case BABYLON.Texture.SKYBOX_MODE:
  44626. this._defines.REFLECTIONMAP_SKYBOX = true;
  44627. break;
  44628. case BABYLON.Texture.SPHERICAL_MODE:
  44629. this._defines.REFLECTIONMAP_SPHERICAL = true;
  44630. break;
  44631. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44632. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44633. break;
  44634. }
  44635. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  44636. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  44637. needNormals = true;
  44638. if (this.reflectionTexture.isPMREM) {
  44639. this._defines.USEPMREMREFLECTION = true;
  44640. }
  44641. }
  44642. }
  44643. }
  44644. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44645. if (!this.lightmapTexture.isReady()) {
  44646. return false;
  44647. }
  44648. else {
  44649. needUVs = true;
  44650. this._defines.LIGHTMAP = true;
  44651. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  44652. }
  44653. }
  44654. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44655. if (!this.emissiveTexture.isReady()) {
  44656. return false;
  44657. }
  44658. else {
  44659. needUVs = true;
  44660. this._defines.EMISSIVE = true;
  44661. }
  44662. }
  44663. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44664. if (!this.reflectivityTexture.isReady()) {
  44665. return false;
  44666. }
  44667. else {
  44668. needUVs = true;
  44669. this._defines.REFLECTIVITY = true;
  44670. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  44671. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  44672. }
  44673. }
  44674. }
  44675. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  44676. if (!this.bumpTexture.isReady()) {
  44677. return false;
  44678. }
  44679. else {
  44680. needUVs = true;
  44681. this._defines.BUMP = true;
  44682. if (this.useParallax) {
  44683. this._defines.PARALLAX = true;
  44684. if (this.useParallaxOcclusion) {
  44685. this._defines.PARALLAXOCCLUSION = true;
  44686. }
  44687. }
  44688. }
  44689. }
  44690. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44691. if (!this.refractionTexture.isReady()) {
  44692. return false;
  44693. }
  44694. else {
  44695. needUVs = true;
  44696. this._defines.REFRACTION = true;
  44697. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  44698. if (this.linkRefractionWithTransparency) {
  44699. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44700. }
  44701. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  44702. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  44703. if (this.refractionTexture.isPMREM) {
  44704. this._defines.USEPMREMREFRACTION = true;
  44705. }
  44706. }
  44707. }
  44708. }
  44709. }
  44710. // Effect
  44711. if (scene.clipPlane) {
  44712. this._defines.CLIPPLANE = true;
  44713. }
  44714. if (engine.getAlphaTesting()) {
  44715. this._defines.ALPHATEST = true;
  44716. }
  44717. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44718. this._defines.ALPHAFROMALBEDO = true;
  44719. }
  44720. if (this.useEmissiveAsIllumination) {
  44721. this._defines.EMISSIVEASILLUMINATION = true;
  44722. }
  44723. if (this.linkEmissiveWithAlbedo) {
  44724. this._defines.LINKEMISSIVEWITHALBEDO = true;
  44725. }
  44726. if (this.useLogarithmicDepth) {
  44727. this._defines.LOGARITHMICDEPTH = true;
  44728. }
  44729. if (this.cameraContrast != 1) {
  44730. this._defines.CAMERACONTRAST = true;
  44731. }
  44732. if (this.cameraExposure != 1) {
  44733. this._defines.CAMERATONEMAP = true;
  44734. }
  44735. if (this.overloadedShadeIntensity != 1 ||
  44736. this.overloadedShadowIntensity != 1) {
  44737. this._defines.OVERLOADEDSHADOWVALUES = true;
  44738. }
  44739. if (this.overloadedMicroSurfaceIntensity > 0 ||
  44740. this.overloadedEmissiveIntensity > 0 ||
  44741. this.overloadedReflectivityIntensity > 0 ||
  44742. this.overloadedAlbedoIntensity > 0 ||
  44743. this.overloadedAmbientIntensity > 0 ||
  44744. this.overloadedReflectionIntensity > 0) {
  44745. this._defines.OVERLOADEDVALUES = true;
  44746. }
  44747. // Point size
  44748. if (this.pointsCloud || scene.forcePointsCloud) {
  44749. this._defines.POINTSIZE = true;
  44750. }
  44751. // Fog
  44752. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  44753. this._defines.FOG = true;
  44754. }
  44755. if (scene.lightsEnabled && !this.disableLighting) {
  44756. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines) || needNormals;
  44757. }
  44758. if (BABYLON.StandardMaterial.FresnelEnabled) {
  44759. // Fresnel
  44760. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  44761. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44762. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  44763. this._defines.OPACITYFRESNEL = true;
  44764. }
  44765. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44766. this._defines.EMISSIVEFRESNEL = true;
  44767. }
  44768. needNormals = true;
  44769. this._defines.FRESNEL = true;
  44770. }
  44771. }
  44772. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  44773. this._defines.SPECULAROVERALPHA = true;
  44774. }
  44775. if (this.usePhysicalLightFalloff) {
  44776. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  44777. }
  44778. if (this.useRadianceOverAlpha) {
  44779. this._defines.RADIANCEOVERALPHA = true;
  44780. }
  44781. // Attribs
  44782. if (mesh) {
  44783. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44784. this._defines.NORMAL = true;
  44785. }
  44786. if (needUVs) {
  44787. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44788. this._defines.UV1 = true;
  44789. }
  44790. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  44791. this._defines.UV2 = true;
  44792. }
  44793. }
  44794. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  44795. this._defines.VERTEXCOLOR = true;
  44796. if (mesh.hasVertexAlpha) {
  44797. this._defines.VERTEXALPHA = true;
  44798. }
  44799. }
  44800. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44801. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  44802. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  44803. }
  44804. // Instances
  44805. if (useInstances) {
  44806. this._defines.INSTANCES = true;
  44807. }
  44808. }
  44809. // Get correct effect
  44810. if (!this._defines.isEqual(this._cachedDefines)) {
  44811. this._defines.cloneTo(this._cachedDefines);
  44812. scene.resetCachedMaterial();
  44813. // Fallbacks
  44814. var fallbacks = new BABYLON.EffectFallbacks();
  44815. if (this._defines.REFLECTION) {
  44816. fallbacks.addFallback(0, "REFLECTION");
  44817. }
  44818. if (this._defines.REFRACTION) {
  44819. fallbacks.addFallback(0, "REFRACTION");
  44820. }
  44821. if (this._defines.REFLECTIVITY) {
  44822. fallbacks.addFallback(0, "REFLECTIVITY");
  44823. }
  44824. if (this._defines.BUMP) {
  44825. fallbacks.addFallback(0, "BUMP");
  44826. }
  44827. if (this._defines.PARALLAX) {
  44828. fallbacks.addFallback(1, "PARALLAX");
  44829. }
  44830. if (this._defines.PARALLAXOCCLUSION) {
  44831. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  44832. }
  44833. if (this._defines.SPECULAROVERALPHA) {
  44834. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  44835. }
  44836. if (this._defines.FOG) {
  44837. fallbacks.addFallback(1, "FOG");
  44838. }
  44839. if (this._defines.POINTSIZE) {
  44840. fallbacks.addFallback(0, "POINTSIZE");
  44841. }
  44842. if (this._defines.LOGARITHMICDEPTH) {
  44843. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  44844. }
  44845. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  44846. if (this._defines.SPECULARTERM) {
  44847. fallbacks.addFallback(0, "SPECULARTERM");
  44848. }
  44849. if (this._defines.OPACITYFRESNEL) {
  44850. fallbacks.addFallback(1, "OPACITYFRESNEL");
  44851. }
  44852. if (this._defines.EMISSIVEFRESNEL) {
  44853. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  44854. }
  44855. if (this._defines.FRESNEL) {
  44856. fallbacks.addFallback(3, "FRESNEL");
  44857. }
  44858. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  44859. fallbacks.addCPUSkinningFallback(0, mesh);
  44860. }
  44861. //Attributes
  44862. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44863. if (this._defines.NORMAL) {
  44864. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44865. }
  44866. if (this._defines.UV1) {
  44867. attribs.push(BABYLON.VertexBuffer.UVKind);
  44868. }
  44869. if (this._defines.UV2) {
  44870. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44871. }
  44872. if (this._defines.VERTEXCOLOR) {
  44873. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44874. }
  44875. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  44876. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  44877. // Legacy browser patch
  44878. var shaderName = "pbr";
  44879. if (!scene.getEngine().getCaps().standardDerivatives) {
  44880. shaderName = "legacypbr";
  44881. }
  44882. var join = this._defines.toString();
  44883. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44884. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  44885. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  44886. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  44887. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  44888. "vFogInfos", "vFogColor", "pointSize",
  44889. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44890. "mBones",
  44891. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44892. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  44893. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  44894. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vCameraInfos", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  44895. "logarithmicDepthConstant",
  44896. "vSphericalX", "vSphericalY", "vSphericalZ",
  44897. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44898. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44899. "vMicrosurfaceTextureLods", "vLightRadiuses"
  44900. ], ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  44901. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  44902. ], join, fallbacks, this.onCompiled, this.onError);
  44903. }
  44904. if (!this._effect.isReady()) {
  44905. return false;
  44906. }
  44907. this._renderId = scene.getRenderId();
  44908. this._wasPreviouslyReady = true;
  44909. if (mesh) {
  44910. if (!mesh._materialDefines) {
  44911. mesh._materialDefines = new PBRMaterialDefines();
  44912. }
  44913. this._defines.cloneTo(mesh._materialDefines);
  44914. }
  44915. return true;
  44916. };
  44917. PBRMaterial.prototype.unbind = function () {
  44918. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  44919. this._effect.setTexture("reflection2DSampler", null);
  44920. }
  44921. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  44922. this._effect.setTexture("refraction2DSampler", null);
  44923. }
  44924. _super.prototype.unbind.call(this);
  44925. };
  44926. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  44927. this._effect.setMatrix("world", world);
  44928. };
  44929. PBRMaterial.prototype.bind = function (world, mesh) {
  44930. this._myScene = this.getScene();
  44931. // Matrices
  44932. this.bindOnlyWorldMatrix(world);
  44933. // Bones
  44934. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  44935. if (this._myScene.getCachedMaterial() !== this) {
  44936. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  44937. if (BABYLON.StandardMaterial.FresnelEnabled) {
  44938. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  44939. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  44940. }
  44941. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44942. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  44943. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  44944. }
  44945. }
  44946. // Textures
  44947. if (this._myScene.texturesEnabled) {
  44948. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44949. this._effect.setTexture("albedoSampler", this.albedoTexture);
  44950. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  44951. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  44952. }
  44953. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44954. this._effect.setTexture("ambientSampler", this.ambientTexture);
  44955. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  44956. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  44957. }
  44958. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44959. this._effect.setTexture("opacitySampler", this.opacityTexture);
  44960. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  44961. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  44962. }
  44963. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44964. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  44965. if (this.reflectionTexture.isCube) {
  44966. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  44967. }
  44968. else {
  44969. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  44970. }
  44971. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  44972. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  44973. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  44974. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  44975. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  44976. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  44977. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  44978. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  44979. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  44980. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  44981. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  44982. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  44983. }
  44984. }
  44985. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44986. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  44987. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  44988. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  44989. }
  44990. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44991. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  44992. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  44993. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  44994. }
  44995. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44996. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  44997. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  44998. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  44999. }
  45000. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  45001. this._effect.setTexture("bumpSampler", this.bumpTexture);
  45002. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  45003. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  45004. }
  45005. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45006. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  45007. var depth = 1.0;
  45008. if (this.refractionTexture.isCube) {
  45009. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  45010. }
  45011. else {
  45012. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  45013. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  45014. if (this.refractionTexture.depth) {
  45015. depth = this.refractionTexture.depth;
  45016. }
  45017. }
  45018. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  45019. }
  45020. if ((this.reflectionTexture || this.refractionTexture)) {
  45021. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  45022. }
  45023. }
  45024. // Clip plane
  45025. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  45026. // Point size
  45027. if (this.pointsCloud) {
  45028. this._effect.setFloat("pointSize", this.pointSize);
  45029. }
  45030. // Colors
  45031. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  45032. // GAMMA CORRECTION.
  45033. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  45034. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  45035. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45036. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  45037. // GAMMA CORRECTION.
  45038. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  45039. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  45040. // GAMMA CORRECTION.
  45041. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  45042. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  45043. }
  45044. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  45045. // GAMMA CORRECTION.
  45046. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  45047. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  45048. // Lights
  45049. if (this._myScene.lightsEnabled && !this.disableLighting) {
  45050. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace);
  45051. }
  45052. // View
  45053. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  45054. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  45055. }
  45056. // Fog
  45057. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  45058. this._lightingInfos.x = this.directIntensity;
  45059. this._lightingInfos.y = this.emissiveIntensity;
  45060. this._lightingInfos.z = this.environmentIntensity;
  45061. this._lightingInfos.w = this.specularIntensity;
  45062. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  45063. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  45064. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  45065. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  45066. this._cameraInfos.x = this.cameraExposure;
  45067. this._cameraInfos.y = this.cameraContrast;
  45068. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  45069. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  45070. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  45071. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  45072. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  45073. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  45074. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  45075. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  45076. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  45077. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  45078. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  45079. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  45080. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  45081. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  45082. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  45083. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  45084. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  45085. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  45086. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  45087. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  45088. // Log. depth
  45089. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  45090. }
  45091. _super.prototype.bind.call(this, world, mesh);
  45092. this._myScene = null;
  45093. };
  45094. PBRMaterial.prototype.getAnimatables = function () {
  45095. var results = [];
  45096. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  45097. results.push(this.albedoTexture);
  45098. }
  45099. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  45100. results.push(this.ambientTexture);
  45101. }
  45102. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  45103. results.push(this.opacityTexture);
  45104. }
  45105. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  45106. results.push(this.reflectionTexture);
  45107. }
  45108. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  45109. results.push(this.emissiveTexture);
  45110. }
  45111. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  45112. results.push(this.reflectivityTexture);
  45113. }
  45114. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  45115. results.push(this.bumpTexture);
  45116. }
  45117. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  45118. results.push(this.lightmapTexture);
  45119. }
  45120. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  45121. results.push(this.refractionTexture);
  45122. }
  45123. return results;
  45124. };
  45125. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45126. if (forceDisposeTextures) {
  45127. if (this.albedoTexture) {
  45128. this.albedoTexture.dispose();
  45129. }
  45130. if (this.ambientTexture) {
  45131. this.ambientTexture.dispose();
  45132. }
  45133. if (this.opacityTexture) {
  45134. this.opacityTexture.dispose();
  45135. }
  45136. if (this.reflectionTexture) {
  45137. this.reflectionTexture.dispose();
  45138. }
  45139. if (this.emissiveTexture) {
  45140. this.emissiveTexture.dispose();
  45141. }
  45142. if (this.reflectivityTexture) {
  45143. this.reflectivityTexture.dispose();
  45144. }
  45145. if (this.bumpTexture) {
  45146. this.bumpTexture.dispose();
  45147. }
  45148. if (this.lightmapTexture) {
  45149. this.lightmapTexture.dispose();
  45150. }
  45151. if (this.refractionTexture) {
  45152. this.refractionTexture.dispose();
  45153. }
  45154. }
  45155. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45156. };
  45157. PBRMaterial.prototype.clone = function (name) {
  45158. var _this = this;
  45159. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45160. };
  45161. PBRMaterial.prototype.serialize = function () {
  45162. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45163. serializationObject.customType = "BABYLON.PBRMaterial";
  45164. return serializationObject;
  45165. };
  45166. // Statics
  45167. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45168. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45169. };
  45170. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  45171. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  45172. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  45173. PBRMaterial._scaledReflection = new BABYLON.Color3();
  45174. PBRMaterial._lightRadiuses = [1, 1, 1, 1];
  45175. __decorate([
  45176. BABYLON.serialize()
  45177. ], PBRMaterial.prototype, "directIntensity", void 0);
  45178. __decorate([
  45179. BABYLON.serialize()
  45180. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45181. __decorate([
  45182. BABYLON.serialize()
  45183. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45184. __decorate([
  45185. BABYLON.serialize()
  45186. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45187. __decorate([
  45188. BABYLON.serialize()
  45189. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45190. __decorate([
  45191. BABYLON.serialize()
  45192. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  45193. __decorate([
  45194. BABYLON.serialize()
  45195. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  45196. __decorate([
  45197. BABYLON.serialize()
  45198. ], PBRMaterial.prototype, "cameraExposure", void 0);
  45199. __decorate([
  45200. BABYLON.serialize()
  45201. ], PBRMaterial.prototype, "cameraContrast", void 0);
  45202. __decorate([
  45203. BABYLON.serializeAsColor3()
  45204. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  45205. __decorate([
  45206. BABYLON.serialize()
  45207. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  45208. __decorate([
  45209. BABYLON.serializeAsColor3()
  45210. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  45211. __decorate([
  45212. BABYLON.serialize()
  45213. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  45214. __decorate([
  45215. BABYLON.serializeAsColor3()
  45216. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  45217. __decorate([
  45218. BABYLON.serialize()
  45219. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  45220. __decorate([
  45221. BABYLON.serializeAsColor3()
  45222. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  45223. __decorate([
  45224. BABYLON.serialize()
  45225. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  45226. __decorate([
  45227. BABYLON.serializeAsColor3()
  45228. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  45229. __decorate([
  45230. BABYLON.serialize()
  45231. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  45232. __decorate([
  45233. BABYLON.serialize()
  45234. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  45235. __decorate([
  45236. BABYLON.serialize()
  45237. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  45238. __decorate([
  45239. BABYLON.serializeAsTexture()
  45240. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45241. __decorate([
  45242. BABYLON.serializeAsTexture()
  45243. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45244. __decorate([
  45245. BABYLON.serializeAsTexture()
  45246. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45247. __decorate([
  45248. BABYLON.serializeAsTexture()
  45249. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45250. __decorate([
  45251. BABYLON.serializeAsTexture()
  45252. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45253. __decorate([
  45254. BABYLON.serializeAsTexture()
  45255. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45256. __decorate([
  45257. BABYLON.serializeAsTexture()
  45258. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45259. __decorate([
  45260. BABYLON.serializeAsTexture()
  45261. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45262. __decorate([
  45263. BABYLON.serializeAsTexture()
  45264. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45265. __decorate([
  45266. BABYLON.serializeAsColor3("ambient")
  45267. ], PBRMaterial.prototype, "ambientColor", void 0);
  45268. __decorate([
  45269. BABYLON.serializeAsColor3("albedo")
  45270. ], PBRMaterial.prototype, "albedoColor", void 0);
  45271. __decorate([
  45272. BABYLON.serializeAsColor3("reflectivity")
  45273. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45274. __decorate([
  45275. BABYLON.serializeAsColor3("reflection")
  45276. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45277. __decorate([
  45278. BABYLON.serializeAsColor3("emissive")
  45279. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45280. __decorate([
  45281. BABYLON.serialize()
  45282. ], PBRMaterial.prototype, "microSurface", void 0);
  45283. __decorate([
  45284. BABYLON.serialize()
  45285. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45286. __decorate([
  45287. BABYLON.serialize()
  45288. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45289. __decorate([
  45290. BABYLON.serializeAsFresnelParameters()
  45291. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  45292. __decorate([
  45293. BABYLON.serializeAsFresnelParameters()
  45294. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  45295. __decorate([
  45296. BABYLON.serialize()
  45297. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45298. __decorate([
  45299. BABYLON.serialize()
  45300. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  45301. __decorate([
  45302. BABYLON.serialize()
  45303. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45304. __decorate([
  45305. BABYLON.serialize()
  45306. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  45307. __decorate([
  45308. BABYLON.serialize()
  45309. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45310. __decorate([
  45311. BABYLON.serialize()
  45312. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45313. __decorate([
  45314. BABYLON.serialize()
  45315. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45316. __decorate([
  45317. BABYLON.serialize()
  45318. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45319. __decorate([
  45320. BABYLON.serialize()
  45321. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  45322. __decorate([
  45323. BABYLON.serialize()
  45324. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45325. __decorate([
  45326. BABYLON.serialize()
  45327. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45328. __decorate([
  45329. BABYLON.serialize()
  45330. ], PBRMaterial.prototype, "useParallax", void 0);
  45331. __decorate([
  45332. BABYLON.serialize()
  45333. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45334. __decorate([
  45335. BABYLON.serialize()
  45336. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45337. __decorate([
  45338. BABYLON.serialize()
  45339. ], PBRMaterial.prototype, "disableLighting", void 0);
  45340. __decorate([
  45341. BABYLON.serialize()
  45342. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  45343. return PBRMaterial;
  45344. })(BABYLON.Material);
  45345. BABYLON.PBRMaterial = PBRMaterial;
  45346. })(BABYLON || (BABYLON = {}));
  45347. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nvec2 diffuseUV=vDiffuseUV;\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,diffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","legacydefaultPixelShader":"#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\nuniform vec2 vReflectionInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 normalW=normalize(vNormalW);\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\nglossiness=vSpecularColor.a;\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0]\n#include<lightFragment>[1]\n#include<lightFragment>[2]\n#include<lightFragment>[3]\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n\nfloat alpha=vDiffuseColor.a;\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor=texture2D(specularSampler,vSpecularUV).rgb*vSpecularInfos.y;\n#endif\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}","legacydefaultVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform mat4 reflectionMatrix;\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 coords=vec3(view*vec4(worldNormal,0.0));\nreturn vec3(reflectionMatrix*vec4(coords,1.0));\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn position;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef REFLECTION\nvReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),vNormalW);\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","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]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[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]\n#include<pbrLightFunctionsCall>[1]\n#include<pbrLightFunctionsCall>[2]\n#include<pbrLightFunctionsCall>[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]\n#include<lightFragmentDeclaration>[1]\n#include<lightFragmentDeclaration>[2]\n#include<lightFragmentDeclaration>[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]\n#include<pbrLightFunctionsCall>[1]\n#include<pbrLightFunctionsCall>[2]\n#include<pbrLightFunctionsCall>[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;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"vec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=pack(depth);\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}","ssaoPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvarying vec2 vUV;\nvec3 normalFromDepth(float depth,vec2 coords) {\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 sample=texture2D(lightScatteringSampler,tc)*0.4;\nsample*=illuminationDecay*weight;\ncolor+=sample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\n}\n}"};
  45348. 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"};
  45349. 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],o=t.x*i.m[1]+t.y*i.m[5];return new n(r,o)},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},n}();t.Vector2=o;var s=function(){function n(t,i,n){this.x=t,this.y=i,this.z=n}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},n.prototype.toQuaternion=function(){var t=new h(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),e=Math.sin(.5*this.y);return t.x=r*e,t.y=-o*e,t.z=n*s,t.w=i*s,t},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},n.prototype.subtractFromFloats=function(t,i,r){return new n(this.x-t,this.y-i,this.z-r)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},n.prototype.negate=function(){return new n(-this.x,-this.y,-this.z)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)},n.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},n.prototype.multiplyByFloats=function(t,i,r){return new n(this.x*t,this.y*i,this.z*r)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},n.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},n.prototype.clone=function(){return new n(this.x,this.y,this.z)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},n.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},n.GetClipFactor=function(t,i,r,o){var s=n.Dot(t,r)-o,e=n.Dot(i,r)-o,h=s/(s-e);return h},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromFloatArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},n.Zero=function(){return new n(0,0,0)},n.Up=function(){return new n(0,1,0)},n.TransformCoordinates=function(t,i){var r=n.Zero();return n.TransformCoordinatesToRef(t,i,r),r},n.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/e,n.y=o/e,n.z=s/e},n.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var s=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],e=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=s/a,o.y=e/a,o.z=h/a},n.TransformNormal=function(t,i){var r=n.Zero();return n.TransformNormalToRef(t,i,r),r},n.TransformNormalToRef=function(t,i,n){n.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],n.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],n.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},n.TransformNormalFromFloatsToRef=function(t,i,n,r,o){o.x=t*r.m[0]+i*r.m[4]+n*r.m[8],o.y=t*r.m[1]+i*r.m[5]+n*r.m[9],o.z=t*r.m[2]+i*r.m[6]+n*r.m[10]},n.CatmullRom=function(t,i,r,o,s){var e=s*s,h=s*e,a=.5*(2*i.x+(-t.x+r.x)*s+(2*t.x-5*i.x+4*r.x-o.x)*e+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*s+(2*t.y-5*i.y+4*r.y-o.y)*e+(-t.y+3*i.y-3*r.y+o.y)*h),m=.5*(2*i.z+(-t.z+r.z)*s+(2*t.z-5*i.z+4*r.z-o.z)*e+(-t.z+3*i.z-3*r.z+o.z)*h);return new n(a,u,m)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var s=t.y;s=s>r.y?r.y:s,s=s<i.y?i.y:s;var e=t.z;return e=e>r.z?r.z:e,e=e<i.z?i.z:e,new n(o,s,e)},n.Hermite=function(t,i,r,o,s){var e=s*s,h=s*e,a=2*h-3*e+1,u=-2*h+3*e,m=h-2*e+s,y=h-e,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y,f=t.z*a+r.z*u+i.z*m+o.z*y;return new n(c,p,f)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,s=t.y+(i.y-t.y)*r,e=t.z+(i.z-t.z)*r;return new n(o,s,e)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},n.Cross=function(t,i){var r=n.Zero();return n.CrossToRef(t,i,r),r},n.CrossToRef=function(t,i,n){n.x=t.y*i.z-t.z*i.y,n.y=t.z*i.x-t.x*i.z,n.z=t.x*i.y-t.y*i.x},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Project=function(t,i,r,o){var s=o.width,e=o.height,h=o.x,u=o.y,m=a.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+u,0,1),y=i.multiply(r).multiply(m);return n.TransformCoordinates(t,y)},n.UnprojectFromTransform=function(t,r,o,s,e){var h=s.multiply(e);h.invert(),t.x=t.x/r*2-1,t.y=-(t.y/o*2-1);var a=n.TransformCoordinates(t,h),u=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(u,1)&&(a=a.scale(1/u)),a},n.Unproject=function(t,r,o,s,e,h){var a=s.multiply(e).multiply(h);a.invert();var u=new n(t.x/r*2-1,-(t.y/o*2-1),t.z),m=n.TransformCoordinates(u,a),y=u.x*a.m[3]+u.y*a.m[7]+u.z*a.m[11]+a.m[15];return i.WithinEpsilon(y,1)&&(m=m.scale(1/y)),m},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.RotationFromAxis=function(t,i,r){var o=n.Zero();return n.RotationFromAxisToRef(t,i,r,o),o},n.RotationFromAxisToRef=function(r,o,s,e){var h=r.normalize(),a=s.normalize(),u=c.X,m=c.Y,y=0,p=0,f=0,l=0,x=0,z=0,w=0,v=-1,d=0,g=_.Vector3[0],T=0,R=_.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?l=1:(w=a.z/a.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),R.x=l,R.y=x,R.z=z,R.normalize(),n.CrossToRef(h,R,g),g.normalize(),n.Dot(a,g)<0&&(v=1),T=n.Dot(h,R),T=Math.min(1,Math.max(-1,T)),f=Math.acos(T)*v,n.Dot(R,u)<0&&(f=Math.PI+f,R=R.scaleInPlace(-1),d++);var M=_.Vector3[2],F=_.Vector3[3];l=0,x=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?l=1:(w=R.z/R.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),M.x=l,M.y=x,M.z=z,M.normalize(),n.CrossToRef(M,R,F),F.normalize(),n.CrossToRef(a,M,g),g.normalize(),n.Dot(R,g)<0&&(v=1),T=n.Dot(a,M),T=Math.min(1,Math.max(-1,T)),p=Math.acos(T)*v,n.Dot(F,m)<0&&(p=Math.PI+p,d++),v=-1,n.CrossToRef(u,R,g),g.normalize(),n.Dot(g,m)<0&&(v=1),T=n.Dot(R,u),T=Math.min(1,Math.max(-1,T)),y=-Math.acos(T)*v,0>T&&2>d&&(y=Math.PI+y),e.x=p,e.y=y,e.z=f},n}();t.Vector3=s;var e=function(){function n(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},n.prototype.subtractFromFloats=function(t,i,r,o){return new n(this.x-t,this.y-i,this.z-r,this.w-o)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},n.prototype.negate=function(){return new n(-this.x,-this.y,-this.z,-this.w)},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t,this.w*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)&&i.WithinEpsilon(this.w,n.w,r)},n.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},n.prototype.multiplyByFloats=function(t,i,r,o){return new n(this.x*t,this.y*i,this.z*r,this.w*o)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},n.prototype.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,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,s),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t(-this.x,-this.y,-this.z,this.w);return i},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=s.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n,r,o,s=this.x,e=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=s*e+h*a;if(u>.499&&(n=2*Math.atan2(s,a),r=Math.PI/2,o=0),-.499>u&&(n=-2*Math.atan2(s,a),r=-Math.PI/2,o=0),isNaN(n)){var m=s*s,y=e*e,c=h*h;n=Math.atan2(2*e*a-2*s*h,1-2*y-2*c),r=Math.asin(2*u),o=Math.atan2(2*s*a-2*e*h,1-2*m-2*c)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=n,t.z=r,t.x=o,this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,n=this.y*this.y,r=this.z*this.z,o=this.x*this.y,s=this.z*this.w,e=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+s),t.m[2]=2*(e-h),t.m[3]=0,t.m[4]=2*(o-s),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(e+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],s=r[4],e=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(e-m)*n,i.z=(h-s)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(s+h)/n,i.z=(e+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(e-m)/n,i.x=(s+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-s)/n,i.x=(e+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){var r=new t,o=Math.sin(n/2);return i.normalize(),r.w=Math.cos(n/2),r.x=i.x*o,r.y=i.y*o,r.z=i.z*o,r},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,s=.5*i,e=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(s),m=Math.cos(s),y=Math.sin(e),c=Math.cos(e);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),s=.5*(n-t),e=.5*i;r.x=Math.cos(s)*Math.sin(e),r.y=Math.sin(s)*Math.sin(e),r.z=Math.sin(o)*Math.cos(e),r.w=Math.cos(o)*Math.cos(e)},t.Slerp=function(i,n,r){var o,s,e=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(0>h&&(a=!0,h=-h),h>.999999)s=1-e,o=a?-e:e;else{var u=Math.acos(h),m=1/Math.sin(u);s=Math.sin((1-e)*u)*m,o=a?-Math.sin(e*u)*m:Math.sin(e*u)*m}return new t(s*i.x+o*n.x,s*i.y+o*n.y,s*i.z+o*n.z,s*i.w+o*n.w)},t}();t.Quaternion=h;var a=function(){function t(){this.m=new Float32Array(16)}return t.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14]},t.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*s)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*s)},t.prototype.toArray=function(){return this.m},t.prototype.asArray=function(){return this.toArray()},t.prototype.invert=function(){return this.invertToRef(this),this},t.prototype.reset=function(){for(var t=0;16>t;t++)this.m[t]=0;return this},t.prototype.add=function(i){var n=new t;return this.addToRef(i,n),n},t.prototype.addToRef=function(t,i){for(var n=0;16>n;n++)i.m[n]=this.m[n]+t.m[n];return this},t.prototype.addToSelf=function(t){for(var i=0;16>i;i++)this.m[i]+=t.m[i];return this},t.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],s=this.m[4],e=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],l=this.m[14],x=this.m[15],z=y*x-c*l,w=m*x-c*f,v=m*l-y*f,d=u*x-c*p,g=u*l-y*p,T=u*f-m*p,R=e*z-h*w+a*v,_=-(s*z-h*d+a*g),M=s*w-e*d+a*T,F=-(s*v-e*g+h*T),b=1/(i*R+n*_+r*M+o*F),A=h*x-a*l,L=e*x-a*f,P=e*l-h*f,Z=s*x-a*p,C=s*l-h*p,S=s*f-e*p,I=h*c-a*y,q=e*c-a*m,E=e*y-h*m,D=s*c-a*u,V=s*y-h*u,W=s*m-e*u;return t.m[0]=R*b,t.m[4]=_*b,t.m[8]=M*b,t.m[12]=F*b,t.m[1]=-(n*z-r*w+o*v)*b,t.m[5]=(i*z-r*d+o*g)*b,t.m[9]=-(i*w-n*d+o*T)*b,t.m[13]=(i*v-n*g+r*T)*b,t.m[2]=(n*A-r*L+o*P)*b,t.m[6]=-(i*A-r*Z+o*C)*b,t.m[10]=(i*L-n*Z+o*S)*b,t.m[14]=-(i*P-n*C+r*S)*b,t.m[3]=-(n*I-r*q+o*E)*b,t.m[7]=(i*I-r*D+o*V)*b,t.m[11]=-(i*q-n*D+o*W)*b,t.m[15]=(i*E-n*V+r*W)*b,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.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],F=t.m[7],b=t.m[8],A=t.m[9],L=t.m[10],P=t.m[11],Z=t.m[12],C=t.m[13],S=t.m[14],I=t.m[15];return i[n]=r*v+o*R+s*b+e*Z,i[n+1]=r*d+o*_+s*A+e*C,i[n+2]=r*g+o*M+s*L+e*S,i[n+3]=r*T+o*F+s*P+e*I,i[n+4]=h*v+a*R+u*b+m*Z,i[n+5]=h*d+a*_+u*A+m*C,i[n+6]=h*g+a*M+u*L+m*S,i[n+7]=h*T+a*F+u*P+m*I,i[n+8]=y*v+c*R+p*b+f*Z,i[n+9]=y*d+c*_+p*A+f*C,i[n+10]=y*g+c*M+p*L+f*S,i[n+11]=y*T+c*F+p*P+f*I,i[n+12]=l*v+x*R+z*b+w*Z,i[n+13]=l*d+x*_+z*A+w*C,i[n+14]=l*g+x*M+z*L+w*S,i[n+15]=l*T+x*F+z*P+w*I,this},t.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},t.prototype.clone=function(){return t.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},t.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var s=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,e=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,a=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(n.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=e*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=a*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=t.FromValues(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1);return h.FromRotationMatrixToRef(u,r),!0},t.FromArray=function(i,n){var r=new t;return n||(n=0),t.FromArrayToRef(i,n,r),r},t.FromArrayToRef=function(t,i,n){for(var r=0;16>r;r++)n.m[r]=t[r+i]},t.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;16>o;o++)r.m[o]=t[o+i]*n},t.FromValuesToRef=function(t,i,n,r,o,s,e,h,a,u,m,y,c,p,f,l,x){x.m[0]=t,x.m[1]=i,x.m[2]=n,x.m[3]=r,x.m[4]=o,x.m[5]=s,x.m[6]=e,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=p,x.m[14]=f,x.m[15]=l},t.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){var o=t.FromValues(i.x,0,0,0,0,i.y,0,0,0,0,i.z,0,0,0,0,1),s=t.Identity();return n.toRotationMatrix(s),o=o.multiply(s),o.setTranslation(r),o},t.Identity=function(){return t.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},t.IdentityToRef=function(i){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,i)},t.Zero=function(){return t.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},t.RotationX=function(i){var n=new t;return t.RotationXToRef(i,n),\nn},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){h.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},t.Scaling=function(i,n,r){var o=t.Zero();return t.ScalingToRef(i,n,r,o),o},t.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},t.Translation=function(i,n,r){var o=t.Identity();return t.TranslationToRef(i,n,r,o),o},t.TranslationToRef=function(i,n,r,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,n,r,1,o)},t.Lerp=function(i,n,r){var o=new s(0,0,0),e=new h,a=new s(0,0,0);i.decompose(o,e,a);var u=new s(0,0,0),m=new h,y=new s(0,0,0);n.decompose(u,m,y);var c=s.Lerp(o,u,r),p=h.Slerp(e,m,r),f=s.Lerp(a,y,r);return t.Compose(c,p,f)},t.LookAtLH=function(i,n,r){var o=t.Zero();return t.LookAtLHToRef(i,n,r,o),o},t.LookAtLHToRef=function(i,n,r,o){n.subtractToRef(i,this._zAxis),this._zAxis.normalize(),s.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),s.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-s.Dot(this._xAxis,i),h=-s.Dot(this._yAxis,i),a=-s.Dot(this._zAxis,i);return t.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,e,h,a,1,o)},t.OrthoLH=function(i,n,r,o){var s=t.Zero();return t.OrthoLHToRef(i,n,r,o,s),s},t.OrthoLHToRef=function(i,n,r,o,s){var e=2/i,h=2/n,a=1/(o-r),u=r/(r-o);t.FromValuesToRef(e,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,s)},t.OrthoOffCenterLH=function(i,n,r,o,s,e){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,n,r,o,s,e,h),h},t.OrthoOffCenterLHToRef=function(t,i,n,r,o,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(r-n),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(o-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(r+n)/(n-r),e.m[14]=o/(o-s),e.m[15]=1},t.PerspectiveLH=function(i,n,r,o){var s=t.Zero();return s.m[0]=2*r/i,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*r/n,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-o/(r-o),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=r*o/(r-o),s},t.PerspectiveFovLH=function(i,n,r,o){var s=t.Zero();return t.PerspectiveFovLHToRef(i,n,r,o,s),s},t.PerspectiveFovLHToRef=function(t,i,n,r,o,s){void 0===s&&(s=!0);var e=1/Math.tan(.5*t);s?o.m[0]=e/i:o.m[0]=e,o.m[1]=o.m[2]=o.m[3]=0,s?o.m[5]=e:o.m[5]=e*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=-r/(n-r),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=n*r/(n-r)},t.GetFinalMatrix=function(i,n,r,o,s,e){var h=i.width,a=i.height,u=i.x,m=i.y,y=t.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,e-s,0,u+h/2,a/2+m,s,1);return n.multiply(r).multiply(o).multiply(y)},t.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},t.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},t.Transpose=function(i){var n=new t;return n.m[0]=i.m[0],n.m[1]=i.m[4],n.m[2]=i.m[8],n.m[3]=i.m[12],n.m[4]=i.m[1],n.m[5]=i.m[5],n.m[6]=i.m[9],n.m[7]=i.m[13],n.m[8]=i.m[2],n.m[9]=i.m[6],n.m[10]=i.m[10],n.m[11]=i.m[14],n.m[12]=i.m[3],n.m[13]=i.m[7],n.m[14]=i.m[11],n.m[15]=i.m[15],n},t.Reflection=function(i){var n=new t;return t.ReflectionToRef(i,n),n},t.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,s=-2*n,e=-2*r,h=-2*o;i.m[0]=s*n+1,i.m[1]=e*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=s*r,i.m[5]=e*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=s*o,i.m[9]=e*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=h*t.d,i.m[15]=1},t._tempQuaternion=new h,t._xAxis=s.Zero(),t._yAxis=s.Zero(),t._zAxis=s.Zero(),t}();t.Matrix=a;var u=function(){function t(t,i,n,r){this.normal=new s(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=a.Transpose(i),r=this.normal.x,o=this.normal.y,s=this.normal.z,e=this.d,h=r*n.m[0]+o*n.m[1]+s*n.m[2]+e*n.m[3],u=r*n.m[4]+o*n.m[5]+s*n.m[6]+e*n.m[7],m=r*n.m[8]+o*n.m[9]+s*n.m[10]+e*n.m[11],y=r*n.m[12]+o*n.m[13]+s*n.m[14]+e*n.m[15];return new t(h,u,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,s=i.y-t.y,e=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=s*u-e*a,y=e*h-o*u,c=o*a-s*h,p=Math.sqrt(m*m+y*y+c*c);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=s.Dot(this.normal,t);return i>=n},t.prototype.signedDistanceTo=function(t){return s.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return s.Dot(n,i)+r},t}();t.Plane=u;var m=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i,n){return new t(this.x*i,this.y*n,this.width*i,this.height*n)},t}();t.Viewport=m;var y=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;6>r;r++)n.push(new u(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=y,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var c=(t.Space,function(){function t(){}return t.X=new s(1,0,0),t.Y=new s(0,1,0),t.Z=new s(0,0,1),t}());t.Axis=c;var p=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var s=1-3*r+3*i,e=3*r-6*i,h=3*i,a=t,u=0;5>u;u++){var m=a*a,y=m*a,c=s*y+e*m+h*a,p=1/(3*s*m+2*e*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=p,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var f=t.Orientation,l=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=l;var x=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new o((s*(i.y-n.y)-e*(t.y-i.y))/h,((t.x-i.x)*e-(i.x-n.x)*s)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=l.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=l.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=l.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),-180>u-a&&(u+=360),m-u>180&&(m-=360),-180>m-u&&(m+=360),this.orientation=0>u-a?f.CW:f.CCW,this.angle=l.FromDegrees(this.orientation===f.CW?a-m:m-a)}return t}();t.Arc2=x;var z=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var n=new o(t,i),r=this._points[this._points.length-1];return this._points.push(n),this._length+=n.subtract(r).length(),this},t.prototype.addArcTo=function(t,i,n,r,s){if(void 0===s&&(s=36),closed)return this;var e=this._points[this._points.length-1],h=new o(t,i),a=new o(n,r),u=new x(e,h,a),m=u.angle.radians()/s;u.orientation===f.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;s>c;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,l=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,l),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(0>t||t>1)return o.Zero();for(var i=t*this.length(),n=0,r=0;r<this._points.length;r++){var s=(r+1)%this._points.length,e=this._points[r],h=this._points[s],a=h.subtract(e),u=a.length()+n;if(i>=n&&u>=i){var m=a.normalize(),y=i-n;return new o(e.x+m.x*y,e.y+m.y*y)}n=u}return o.Zero()},t.StartingAt=function(i,n){return new t(i,n)},t}();t.Path2=z;var w=function(){function n(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return n.prototype.getCurve=function(){return this._curve},n.prototype.getTangents=function(){return this._tangents},n.prototype.getNormals=function(){return this._normals},n.prototype.getBinormals=function(){return this._binormals},n.prototype.getDistances=function(){return this._distances},n.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},n.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=s.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,e,h,a,u=1;i>u;u++)o=this._getLastNonNullVector(u),i-1>u&&(e=this._getFirstNonNullVector(u),this._tangents[u]=o.add(e),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=s.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=s.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},n.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},n.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},n.prototype._normalVector=function(n,r,o){var e;if(void 0===o||null===o){var h;i.WithinEpsilon(r.y,1,t.Epsilon)?i.WithinEpsilon(r.x,1,t.Epsilon)?i.WithinEpsilon(r.z,1,t.Epsilon)||(h=new s(0,0,1)):h=new s(1,0,0):h=new s(0,-1,0),e=s.Cross(r,h)}else e=s.Cross(r,o),s.CrossToRef(e,r,e);return e.normalize(),e},n}();t.Path3D=w;var v=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var e=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;o>=a;a++)e.push(new s(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(e)},t.CreateCubicBezier=function(i,n,r,o,e){e=e>3?e:4;for(var h=new Array,a=function(t,i,n,r,o){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return s},u=0;e>=u;u++)h.push(new s(a(u/e,i.x,n.x,r.x,o.x),a(u/e,i.y,n.y,r.y,o.y),a(u/e,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,e){for(var h=new Array,a=1/e,u=0;e>=u;u++)h.push(s.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),s=1;s<o.length;s++)r.push(o[s].subtract(o[0]).add(n));var e=new t(r);return e},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=v;var d=function(){function t(){this.L00=s.Zero(),this.L1_1=s.Zero(),this.L10=s.Zero(),this.L11=s.Zero(),this.L2_2=s.Zero(),this.L2_1=s.Zero(),this.L20=s.Zero(),this.L21=s.Zero(),this.L22=s.Zero()}return t.prototype.addLight=function(t,i,n){var r=new s(i.r,i.g,i.b),o=r.scale(n);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=d;var g=function(){function t(){this.x=s.Zero(),this.y=s.Zero(),this.z=s.Zero(),this.xx=s.Zero(),this.yy=s.Zero(),this.zz=s.Zero(),this.xy=s.Zero(),this.yz=s.Zero(),this.zx=s.Zero()}return t.prototype.addAmbient=function(t){var i=new s(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var n=new t;return n.x=i.L11.scale(1.02333),n.y=i.L1_1.scale(1.02333),n.z=i.L10.scale(1.02333),n.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),n.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),n.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),n.yz=i.L2_1.scale(.858086),n.zx=i.L21.scale(.858086),n.xy=i.L2_2.scale(.858086),n},t}();t.SphericalPolynomial=g;var T=function(){function t(t,i){void 0===t&&(t=s.Zero()),void 0===i&&(i=s.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=T;var R=function(){function t(t,i,n){void 0===t&&(t=s.Zero()),void 0===i&&(i=s.Up()),void 0===n&&(n=o.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=R;var _=function(){function t(){}return t.Color3=[n.Black(),n.Black(),n.Black()],t.Vector2=[o.Zero(),o.Zero(),o.Zero()],t.Vector3=[s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero(),s.Zero()],t.Vector4=[e.Zero(),e.Zero(),e.Zero()],t.Quaternion=[new h(0,0,0,0)],t.Matrix=[a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero(),a.Zero()],t}();t.Tmp=_}(BABYLON||(BABYLON={}));";
  45350. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  45351. module.exports = BABYLON;
  45352. };