babylon.max.js 2.3 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878
  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.clone = function () {
  1188. return new Vector4(this.x, this.y, this.z, this.w);
  1189. };
  1190. Vector4.prototype.copyFrom = function (source) {
  1191. this.x = source.x;
  1192. this.y = source.y;
  1193. this.z = source.z;
  1194. this.w = source.w;
  1195. return this;
  1196. };
  1197. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1198. this.x = x;
  1199. this.y = y;
  1200. this.z = z;
  1201. this.w = w;
  1202. return this;
  1203. };
  1204. // Statics
  1205. Vector4.FromArray = function (array, offset) {
  1206. if (!offset) {
  1207. offset = 0;
  1208. }
  1209. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1210. };
  1211. Vector4.FromArrayToRef = function (array, offset, result) {
  1212. result.x = array[offset];
  1213. result.y = array[offset + 1];
  1214. result.z = array[offset + 2];
  1215. result.w = array[offset + 3];
  1216. };
  1217. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1218. result.x = array[offset];
  1219. result.y = array[offset + 1];
  1220. result.z = array[offset + 2];
  1221. result.w = array[offset + 3];
  1222. };
  1223. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1224. result.x = x;
  1225. result.y = y;
  1226. result.z = z;
  1227. result.w = w;
  1228. };
  1229. Vector4.Zero = function () {
  1230. return new Vector4(0, 0, 0, 0);
  1231. };
  1232. Vector4.Normalize = function (vector) {
  1233. var result = Vector4.Zero();
  1234. Vector4.NormalizeToRef(vector, result);
  1235. return result;
  1236. };
  1237. Vector4.NormalizeToRef = function (vector, result) {
  1238. result.copyFrom(vector);
  1239. result.normalize();
  1240. };
  1241. Vector4.Minimize = function (left, right) {
  1242. var min = left.clone();
  1243. min.MinimizeInPlace(right);
  1244. return min;
  1245. };
  1246. Vector4.Maximize = function (left, right) {
  1247. var max = left.clone();
  1248. max.MaximizeInPlace(right);
  1249. return max;
  1250. };
  1251. Vector4.Distance = function (value1, value2) {
  1252. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1253. };
  1254. Vector4.DistanceSquared = function (value1, value2) {
  1255. var x = value1.x - value2.x;
  1256. var y = value1.y - value2.y;
  1257. var z = value1.z - value2.z;
  1258. var w = value1.w - value2.w;
  1259. return (x * x) + (y * y) + (z * z) + (w * w);
  1260. };
  1261. Vector4.Center = function (value1, value2) {
  1262. var center = value1.add(value2);
  1263. center.scaleInPlace(0.5);
  1264. return center;
  1265. };
  1266. return Vector4;
  1267. })();
  1268. BABYLON.Vector4 = Vector4;
  1269. var Quaternion = (function () {
  1270. function Quaternion(x, y, z, w) {
  1271. if (x === void 0) { x = 0; }
  1272. if (y === void 0) { y = 0; }
  1273. if (z === void 0) { z = 0; }
  1274. if (w === void 0) { w = 1; }
  1275. this.x = x;
  1276. this.y = y;
  1277. this.z = z;
  1278. this.w = w;
  1279. }
  1280. Quaternion.prototype.toString = function () {
  1281. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1282. };
  1283. Quaternion.prototype.asArray = function () {
  1284. return [this.x, this.y, this.z, this.w];
  1285. };
  1286. Quaternion.prototype.equals = function (otherQuaternion) {
  1287. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1288. };
  1289. Quaternion.prototype.clone = function () {
  1290. return new Quaternion(this.x, this.y, this.z, this.w);
  1291. };
  1292. Quaternion.prototype.copyFrom = function (other) {
  1293. this.x = other.x;
  1294. this.y = other.y;
  1295. this.z = other.z;
  1296. this.w = other.w;
  1297. return this;
  1298. };
  1299. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1300. this.x = x;
  1301. this.y = y;
  1302. this.z = z;
  1303. this.w = w;
  1304. return this;
  1305. };
  1306. Quaternion.prototype.add = function (other) {
  1307. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1308. };
  1309. Quaternion.prototype.subtract = 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.scale = function (value) {
  1313. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1314. };
  1315. Quaternion.prototype.multiply = function (q1) {
  1316. var result = new Quaternion(0, 0, 0, 1.0);
  1317. this.multiplyToRef(q1, result);
  1318. return result;
  1319. };
  1320. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1321. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1322. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1323. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1324. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1325. result.copyFromFloats(x, y, z, w);
  1326. return this;
  1327. };
  1328. Quaternion.prototype.multiplyInPlace = function (q1) {
  1329. this.multiplyToRef(q1, this);
  1330. return this;
  1331. };
  1332. Quaternion.prototype.conjugateToRef = function (ref) {
  1333. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1334. return this;
  1335. };
  1336. Quaternion.prototype.conjugateInPlace = function () {
  1337. this.x *= -1;
  1338. this.y *= -1;
  1339. this.z *= -1;
  1340. return this;
  1341. };
  1342. Quaternion.prototype.conjugate = function () {
  1343. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1344. return result;
  1345. };
  1346. Quaternion.prototype.length = function () {
  1347. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1348. };
  1349. Quaternion.prototype.normalize = function () {
  1350. var length = 1.0 / this.length();
  1351. this.x *= length;
  1352. this.y *= length;
  1353. this.z *= length;
  1354. this.w *= length;
  1355. return this;
  1356. };
  1357. Quaternion.prototype.toEulerAngles = function (order) {
  1358. if (order === void 0) { order = "YZX"; }
  1359. var result = Vector3.Zero();
  1360. this.toEulerAnglesToRef(result, order);
  1361. return result;
  1362. };
  1363. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1364. if (order === void 0) { order = "YZX"; }
  1365. var heading, attitude, bank;
  1366. var x = this.x, y = this.y, z = this.z, w = this.w;
  1367. switch (order) {
  1368. case "YZX":
  1369. var test = x * y + z * w;
  1370. if (test > 0.499) {
  1371. heading = 2 * Math.atan2(x, w);
  1372. attitude = Math.PI / 2;
  1373. bank = 0;
  1374. }
  1375. if (test < -0.499) {
  1376. heading = -2 * Math.atan2(x, w);
  1377. attitude = -Math.PI / 2;
  1378. bank = 0;
  1379. }
  1380. if (isNaN(heading)) {
  1381. var sqx = x * x;
  1382. var sqy = y * y;
  1383. var sqz = z * z;
  1384. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1385. attitude = Math.asin(2 * test); // attitude
  1386. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1387. }
  1388. break;
  1389. default:
  1390. throw new Error("Euler order " + order + " not supported yet.");
  1391. }
  1392. result.y = heading;
  1393. result.z = attitude;
  1394. result.x = bank;
  1395. return this;
  1396. };
  1397. ;
  1398. Quaternion.prototype.toRotationMatrix = function (result) {
  1399. var xx = this.x * this.x;
  1400. var yy = this.y * this.y;
  1401. var zz = this.z * this.z;
  1402. var xy = this.x * this.y;
  1403. var zw = this.z * this.w;
  1404. var zx = this.z * this.x;
  1405. var yw = this.y * this.w;
  1406. var yz = this.y * this.z;
  1407. var xw = this.x * this.w;
  1408. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1409. result.m[1] = 2.0 * (xy + zw);
  1410. result.m[2] = 2.0 * (zx - yw);
  1411. result.m[3] = 0;
  1412. result.m[4] = 2.0 * (xy - zw);
  1413. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1414. result.m[6] = 2.0 * (yz + xw);
  1415. result.m[7] = 0;
  1416. result.m[8] = 2.0 * (zx + yw);
  1417. result.m[9] = 2.0 * (yz - xw);
  1418. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1419. result.m[11] = 0;
  1420. result.m[12] = 0;
  1421. result.m[13] = 0;
  1422. result.m[14] = 0;
  1423. result.m[15] = 1.0;
  1424. return this;
  1425. };
  1426. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1427. Quaternion.FromRotationMatrixToRef(matrix, this);
  1428. return this;
  1429. };
  1430. // Statics
  1431. Quaternion.FromRotationMatrix = function (matrix) {
  1432. var result = new Quaternion();
  1433. Quaternion.FromRotationMatrixToRef(matrix, result);
  1434. return result;
  1435. };
  1436. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1437. var data = matrix.m;
  1438. var m11 = data[0], m12 = data[4], m13 = data[8];
  1439. var m21 = data[1], m22 = data[5], m23 = data[9];
  1440. var m31 = data[2], m32 = data[6], m33 = data[10];
  1441. var trace = m11 + m22 + m33;
  1442. var s;
  1443. if (trace > 0) {
  1444. s = 0.5 / Math.sqrt(trace + 1.0);
  1445. result.w = 0.25 / s;
  1446. result.x = (m32 - m23) * s;
  1447. result.y = (m13 - m31) * s;
  1448. result.z = (m21 - m12) * s;
  1449. }
  1450. else if (m11 > m22 && m11 > m33) {
  1451. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1452. result.w = (m32 - m23) / s;
  1453. result.x = 0.25 * s;
  1454. result.y = (m12 + m21) / s;
  1455. result.z = (m13 + m31) / s;
  1456. }
  1457. else if (m22 > m33) {
  1458. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1459. result.w = (m13 - m31) / s;
  1460. result.x = (m12 + m21) / s;
  1461. result.y = 0.25 * s;
  1462. result.z = (m23 + m32) / s;
  1463. }
  1464. else {
  1465. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1466. result.w = (m21 - m12) / s;
  1467. result.x = (m13 + m31) / s;
  1468. result.y = (m23 + m32) / s;
  1469. result.z = 0.25 * s;
  1470. }
  1471. };
  1472. Quaternion.Inverse = function (q) {
  1473. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1474. };
  1475. Quaternion.Identity = function () {
  1476. return new Quaternion(0, 0, 0, 1);
  1477. };
  1478. Quaternion.RotationAxis = function (axis, angle) {
  1479. var result = new Quaternion();
  1480. var sin = Math.sin(angle / 2);
  1481. axis.normalize();
  1482. result.w = Math.cos(angle / 2);
  1483. result.x = axis.x * sin;
  1484. result.y = axis.y * sin;
  1485. result.z = axis.z * sin;
  1486. return result;
  1487. };
  1488. Quaternion.FromArray = function (array, offset) {
  1489. if (!offset) {
  1490. offset = 0;
  1491. }
  1492. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1493. };
  1494. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1495. var result = new Quaternion();
  1496. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1497. return result;
  1498. };
  1499. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1500. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1501. var halfRoll = roll * 0.5;
  1502. var halfPitch = pitch * 0.5;
  1503. var halfYaw = yaw * 0.5;
  1504. var sinRoll = Math.sin(halfRoll);
  1505. var cosRoll = Math.cos(halfRoll);
  1506. var sinPitch = Math.sin(halfPitch);
  1507. var cosPitch = Math.cos(halfPitch);
  1508. var sinYaw = Math.sin(halfYaw);
  1509. var cosYaw = Math.cos(halfYaw);
  1510. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1511. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1512. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1513. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1514. };
  1515. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1516. var result = new Quaternion();
  1517. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1518. return result;
  1519. };
  1520. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1521. // Produces a quaternion from Euler angles in the z-x-z orientation
  1522. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1523. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1524. var halfBeta = beta * 0.5;
  1525. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1526. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1527. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1528. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1529. };
  1530. Quaternion.Slerp = function (left, right, amount) {
  1531. var num2;
  1532. var num3;
  1533. var num = amount;
  1534. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1535. var flag = false;
  1536. if (num4 < 0) {
  1537. flag = true;
  1538. num4 = -num4;
  1539. }
  1540. if (num4 > 0.999999) {
  1541. num3 = 1 - num;
  1542. num2 = flag ? -num : num;
  1543. }
  1544. else {
  1545. var num5 = Math.acos(num4);
  1546. var num6 = (1.0 / Math.sin(num5));
  1547. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1548. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1549. }
  1550. 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));
  1551. };
  1552. return Quaternion;
  1553. })();
  1554. BABYLON.Quaternion = Quaternion;
  1555. var Matrix = (function () {
  1556. function Matrix() {
  1557. this.m = new Float32Array(16);
  1558. }
  1559. // Properties
  1560. Matrix.prototype.isIdentity = function () {
  1561. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1562. return false;
  1563. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1564. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1565. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1566. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1567. return false;
  1568. return true;
  1569. };
  1570. Matrix.prototype.determinant = function () {
  1571. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1572. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1573. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1574. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1575. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1576. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1577. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1578. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1579. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1580. };
  1581. // Methods
  1582. Matrix.prototype.toArray = function () {
  1583. return this.m;
  1584. };
  1585. Matrix.prototype.asArray = function () {
  1586. return this.toArray();
  1587. };
  1588. Matrix.prototype.invert = function () {
  1589. this.invertToRef(this);
  1590. return this;
  1591. };
  1592. Matrix.prototype.reset = function () {
  1593. for (var index = 0; index < 16; index++) {
  1594. this.m[index] = 0;
  1595. }
  1596. return this;
  1597. };
  1598. Matrix.prototype.add = function (other) {
  1599. var result = new Matrix();
  1600. this.addToRef(other, result);
  1601. return result;
  1602. };
  1603. Matrix.prototype.addToRef = function (other, result) {
  1604. for (var index = 0; index < 16; index++) {
  1605. result.m[index] = this.m[index] + other.m[index];
  1606. }
  1607. return this;
  1608. };
  1609. Matrix.prototype.addToSelf = function (other) {
  1610. for (var index = 0; index < 16; index++) {
  1611. this.m[index] += other.m[index];
  1612. }
  1613. return this;
  1614. };
  1615. Matrix.prototype.invertToRef = function (other) {
  1616. var l1 = this.m[0];
  1617. var l2 = this.m[1];
  1618. var l3 = this.m[2];
  1619. var l4 = this.m[3];
  1620. var l5 = this.m[4];
  1621. var l6 = this.m[5];
  1622. var l7 = this.m[6];
  1623. var l8 = this.m[7];
  1624. var l9 = this.m[8];
  1625. var l10 = this.m[9];
  1626. var l11 = this.m[10];
  1627. var l12 = this.m[11];
  1628. var l13 = this.m[12];
  1629. var l14 = this.m[13];
  1630. var l15 = this.m[14];
  1631. var l16 = this.m[15];
  1632. var l17 = (l11 * l16) - (l12 * l15);
  1633. var l18 = (l10 * l16) - (l12 * l14);
  1634. var l19 = (l10 * l15) - (l11 * l14);
  1635. var l20 = (l9 * l16) - (l12 * l13);
  1636. var l21 = (l9 * l15) - (l11 * l13);
  1637. var l22 = (l9 * l14) - (l10 * l13);
  1638. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1639. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1640. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1641. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1642. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1643. var l28 = (l7 * l16) - (l8 * l15);
  1644. var l29 = (l6 * l16) - (l8 * l14);
  1645. var l30 = (l6 * l15) - (l7 * l14);
  1646. var l31 = (l5 * l16) - (l8 * l13);
  1647. var l32 = (l5 * l15) - (l7 * l13);
  1648. var l33 = (l5 * l14) - (l6 * l13);
  1649. var l34 = (l7 * l12) - (l8 * l11);
  1650. var l35 = (l6 * l12) - (l8 * l10);
  1651. var l36 = (l6 * l11) - (l7 * l10);
  1652. var l37 = (l5 * l12) - (l8 * l9);
  1653. var l38 = (l5 * l11) - (l7 * l9);
  1654. var l39 = (l5 * l10) - (l6 * l9);
  1655. other.m[0] = l23 * l27;
  1656. other.m[4] = l24 * l27;
  1657. other.m[8] = l25 * l27;
  1658. other.m[12] = l26 * l27;
  1659. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1660. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1661. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1662. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1663. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1664. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1665. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1666. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1667. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1668. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1669. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1670. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1671. return this;
  1672. };
  1673. Matrix.prototype.setTranslation = function (vector3) {
  1674. this.m[12] = vector3.x;
  1675. this.m[13] = vector3.y;
  1676. this.m[14] = vector3.z;
  1677. return this;
  1678. };
  1679. Matrix.prototype.multiply = function (other) {
  1680. var result = new Matrix();
  1681. this.multiplyToRef(other, result);
  1682. return result;
  1683. };
  1684. Matrix.prototype.copyFrom = function (other) {
  1685. for (var index = 0; index < 16; index++) {
  1686. this.m[index] = other.m[index];
  1687. }
  1688. return this;
  1689. };
  1690. Matrix.prototype.copyToArray = function (array, offset) {
  1691. if (offset === void 0) { offset = 0; }
  1692. for (var index = 0; index < 16; index++) {
  1693. array[offset + index] = this.m[index];
  1694. }
  1695. return this;
  1696. };
  1697. Matrix.prototype.multiplyToRef = function (other, result) {
  1698. this.multiplyToArray(other, result.m, 0);
  1699. return this;
  1700. };
  1701. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1702. var tm0 = this.m[0];
  1703. var tm1 = this.m[1];
  1704. var tm2 = this.m[2];
  1705. var tm3 = this.m[3];
  1706. var tm4 = this.m[4];
  1707. var tm5 = this.m[5];
  1708. var tm6 = this.m[6];
  1709. var tm7 = this.m[7];
  1710. var tm8 = this.m[8];
  1711. var tm9 = this.m[9];
  1712. var tm10 = this.m[10];
  1713. var tm11 = this.m[11];
  1714. var tm12 = this.m[12];
  1715. var tm13 = this.m[13];
  1716. var tm14 = this.m[14];
  1717. var tm15 = this.m[15];
  1718. var om0 = other.m[0];
  1719. var om1 = other.m[1];
  1720. var om2 = other.m[2];
  1721. var om3 = other.m[3];
  1722. var om4 = other.m[4];
  1723. var om5 = other.m[5];
  1724. var om6 = other.m[6];
  1725. var om7 = other.m[7];
  1726. var om8 = other.m[8];
  1727. var om9 = other.m[9];
  1728. var om10 = other.m[10];
  1729. var om11 = other.m[11];
  1730. var om12 = other.m[12];
  1731. var om13 = other.m[13];
  1732. var om14 = other.m[14];
  1733. var om15 = other.m[15];
  1734. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1735. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1736. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1737. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1738. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1739. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1740. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1741. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1742. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1743. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1744. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1745. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1746. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1747. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1748. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1749. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1750. return this;
  1751. };
  1752. Matrix.prototype.equals = function (value) {
  1753. return value &&
  1754. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1755. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1756. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1757. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1758. };
  1759. Matrix.prototype.clone = function () {
  1760. 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]);
  1761. };
  1762. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1763. translation.x = this.m[12];
  1764. translation.y = this.m[13];
  1765. translation.z = this.m[14];
  1766. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1767. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1768. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1769. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1770. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1771. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1772. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1773. rotation.x = 0;
  1774. rotation.y = 0;
  1775. rotation.z = 0;
  1776. rotation.w = 1;
  1777. return false;
  1778. }
  1779. 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);
  1780. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1781. return true;
  1782. };
  1783. // Statics
  1784. Matrix.FromArray = function (array, offset) {
  1785. var result = new Matrix();
  1786. if (!offset) {
  1787. offset = 0;
  1788. }
  1789. Matrix.FromArrayToRef(array, offset, result);
  1790. return result;
  1791. };
  1792. Matrix.FromArrayToRef = function (array, offset, result) {
  1793. for (var index = 0; index < 16; index++) {
  1794. result.m[index] = array[index + offset];
  1795. }
  1796. };
  1797. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  1798. for (var index = 0; index < 16; index++) {
  1799. result.m[index] = array[index + offset] * scale;
  1800. }
  1801. };
  1802. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1803. result.m[0] = initialM11;
  1804. result.m[1] = initialM12;
  1805. result.m[2] = initialM13;
  1806. result.m[3] = initialM14;
  1807. result.m[4] = initialM21;
  1808. result.m[5] = initialM22;
  1809. result.m[6] = initialM23;
  1810. result.m[7] = initialM24;
  1811. result.m[8] = initialM31;
  1812. result.m[9] = initialM32;
  1813. result.m[10] = initialM33;
  1814. result.m[11] = initialM34;
  1815. result.m[12] = initialM41;
  1816. result.m[13] = initialM42;
  1817. result.m[14] = initialM43;
  1818. result.m[15] = initialM44;
  1819. };
  1820. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1821. var result = new Matrix();
  1822. result.m[0] = initialM11;
  1823. result.m[1] = initialM12;
  1824. result.m[2] = initialM13;
  1825. result.m[3] = initialM14;
  1826. result.m[4] = initialM21;
  1827. result.m[5] = initialM22;
  1828. result.m[6] = initialM23;
  1829. result.m[7] = initialM24;
  1830. result.m[8] = initialM31;
  1831. result.m[9] = initialM32;
  1832. result.m[10] = initialM33;
  1833. result.m[11] = initialM34;
  1834. result.m[12] = initialM41;
  1835. result.m[13] = initialM42;
  1836. result.m[14] = initialM43;
  1837. result.m[15] = initialM44;
  1838. return result;
  1839. };
  1840. Matrix.Compose = function (scale, rotation, translation) {
  1841. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1842. var rotationMatrix = Matrix.Identity();
  1843. rotation.toRotationMatrix(rotationMatrix);
  1844. result = result.multiply(rotationMatrix);
  1845. result.setTranslation(translation);
  1846. return result;
  1847. };
  1848. Matrix.Identity = function () {
  1849. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1850. };
  1851. Matrix.IdentityToRef = function (result) {
  1852. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1853. };
  1854. Matrix.Zero = function () {
  1855. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1856. };
  1857. Matrix.RotationX = function (angle) {
  1858. var result = new Matrix();
  1859. Matrix.RotationXToRef(angle, result);
  1860. return result;
  1861. };
  1862. Matrix.Invert = function (source) {
  1863. var result = new Matrix();
  1864. source.invertToRef(result);
  1865. return result;
  1866. };
  1867. Matrix.RotationXToRef = function (angle, result) {
  1868. var s = Math.sin(angle);
  1869. var c = Math.cos(angle);
  1870. result.m[0] = 1.0;
  1871. result.m[15] = 1.0;
  1872. result.m[5] = c;
  1873. result.m[10] = c;
  1874. result.m[9] = -s;
  1875. result.m[6] = s;
  1876. result.m[1] = 0;
  1877. result.m[2] = 0;
  1878. result.m[3] = 0;
  1879. result.m[4] = 0;
  1880. result.m[7] = 0;
  1881. result.m[8] = 0;
  1882. result.m[11] = 0;
  1883. result.m[12] = 0;
  1884. result.m[13] = 0;
  1885. result.m[14] = 0;
  1886. };
  1887. Matrix.RotationY = function (angle) {
  1888. var result = new Matrix();
  1889. Matrix.RotationYToRef(angle, result);
  1890. return result;
  1891. };
  1892. Matrix.RotationYToRef = function (angle, result) {
  1893. var s = Math.sin(angle);
  1894. var c = Math.cos(angle);
  1895. result.m[5] = 1.0;
  1896. result.m[15] = 1.0;
  1897. result.m[0] = c;
  1898. result.m[2] = -s;
  1899. result.m[8] = s;
  1900. result.m[10] = c;
  1901. result.m[1] = 0;
  1902. result.m[3] = 0;
  1903. result.m[4] = 0;
  1904. result.m[6] = 0;
  1905. result.m[7] = 0;
  1906. result.m[9] = 0;
  1907. result.m[11] = 0;
  1908. result.m[12] = 0;
  1909. result.m[13] = 0;
  1910. result.m[14] = 0;
  1911. };
  1912. Matrix.RotationZ = function (angle) {
  1913. var result = new Matrix();
  1914. Matrix.RotationZToRef(angle, result);
  1915. return result;
  1916. };
  1917. Matrix.RotationZToRef = function (angle, result) {
  1918. var s = Math.sin(angle);
  1919. var c = Math.cos(angle);
  1920. result.m[10] = 1.0;
  1921. result.m[15] = 1.0;
  1922. result.m[0] = c;
  1923. result.m[1] = s;
  1924. result.m[4] = -s;
  1925. result.m[5] = c;
  1926. result.m[2] = 0;
  1927. result.m[3] = 0;
  1928. result.m[6] = 0;
  1929. result.m[7] = 0;
  1930. result.m[8] = 0;
  1931. result.m[9] = 0;
  1932. result.m[11] = 0;
  1933. result.m[12] = 0;
  1934. result.m[13] = 0;
  1935. result.m[14] = 0;
  1936. };
  1937. Matrix.RotationAxis = function (axis, angle) {
  1938. var result = Matrix.Zero();
  1939. Matrix.RotationAxisToRef(axis, angle, result);
  1940. return result;
  1941. };
  1942. Matrix.RotationAxisToRef = function (axis, angle, result) {
  1943. var s = Math.sin(-angle);
  1944. var c = Math.cos(-angle);
  1945. var c1 = 1 - c;
  1946. axis.normalize();
  1947. result.m[0] = (axis.x * axis.x) * c1 + c;
  1948. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1949. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1950. result.m[3] = 0.0;
  1951. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1952. result.m[5] = (axis.y * axis.y) * c1 + c;
  1953. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1954. result.m[7] = 0.0;
  1955. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1956. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1957. result.m[10] = (axis.z * axis.z) * c1 + c;
  1958. result.m[11] = 0.0;
  1959. result.m[15] = 1.0;
  1960. };
  1961. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1962. var result = new Matrix();
  1963. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1964. return result;
  1965. };
  1966. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1967. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1968. this._tempQuaternion.toRotationMatrix(result);
  1969. };
  1970. Matrix.Scaling = function (x, y, z) {
  1971. var result = Matrix.Zero();
  1972. Matrix.ScalingToRef(x, y, z, result);
  1973. return result;
  1974. };
  1975. Matrix.ScalingToRef = function (x, y, z, result) {
  1976. result.m[0] = x;
  1977. result.m[1] = 0;
  1978. result.m[2] = 0;
  1979. result.m[3] = 0;
  1980. result.m[4] = 0;
  1981. result.m[5] = y;
  1982. result.m[6] = 0;
  1983. result.m[7] = 0;
  1984. result.m[8] = 0;
  1985. result.m[9] = 0;
  1986. result.m[10] = z;
  1987. result.m[11] = 0;
  1988. result.m[12] = 0;
  1989. result.m[13] = 0;
  1990. result.m[14] = 0;
  1991. result.m[15] = 1.0;
  1992. };
  1993. Matrix.Translation = function (x, y, z) {
  1994. var result = Matrix.Identity();
  1995. Matrix.TranslationToRef(x, y, z, result);
  1996. return result;
  1997. };
  1998. Matrix.TranslationToRef = function (x, y, z, result) {
  1999. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2000. };
  2001. Matrix.Lerp = function (startValue, endValue, gradient) {
  2002. var startScale = new Vector3(0, 0, 0);
  2003. var startRotation = new Quaternion();
  2004. var startTranslation = new Vector3(0, 0, 0);
  2005. startValue.decompose(startScale, startRotation, startTranslation);
  2006. var endScale = new Vector3(0, 0, 0);
  2007. var endRotation = new Quaternion();
  2008. var endTranslation = new Vector3(0, 0, 0);
  2009. endValue.decompose(endScale, endRotation, endTranslation);
  2010. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2011. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2012. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2013. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2014. };
  2015. Matrix.LookAtLH = function (eye, target, up) {
  2016. var result = Matrix.Zero();
  2017. Matrix.LookAtLHToRef(eye, target, up, result);
  2018. return result;
  2019. };
  2020. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2021. // Z axis
  2022. target.subtractToRef(eye, this._zAxis);
  2023. this._zAxis.normalize();
  2024. // X axis
  2025. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2026. if (this._xAxis.lengthSquared() === 0) {
  2027. this._xAxis.x = 1.0;
  2028. }
  2029. else {
  2030. this._xAxis.normalize();
  2031. }
  2032. // Y axis
  2033. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2034. this._yAxis.normalize();
  2035. // Eye angles
  2036. var ex = -Vector3.Dot(this._xAxis, eye);
  2037. var ey = -Vector3.Dot(this._yAxis, eye);
  2038. var ez = -Vector3.Dot(this._zAxis, eye);
  2039. 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);
  2040. };
  2041. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2042. var matrix = Matrix.Zero();
  2043. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2044. return matrix;
  2045. };
  2046. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2047. var hw = 2.0 / width;
  2048. var hh = 2.0 / height;
  2049. var id = 1.0 / (zfar - znear);
  2050. var nid = znear / (znear - zfar);
  2051. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2052. };
  2053. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2054. var matrix = Matrix.Zero();
  2055. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2056. return matrix;
  2057. };
  2058. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2059. result.m[0] = 2.0 / (right - left);
  2060. result.m[1] = result.m[2] = result.m[3] = 0;
  2061. result.m[5] = 2.0 / (top - bottom);
  2062. result.m[4] = result.m[6] = result.m[7] = 0;
  2063. result.m[10] = -1.0 / (znear - zfar);
  2064. result.m[8] = result.m[9] = result.m[11] = 0;
  2065. result.m[12] = (left + right) / (left - right);
  2066. result.m[13] = (top + bottom) / (bottom - top);
  2067. result.m[14] = znear / (znear - zfar);
  2068. result.m[15] = 1.0;
  2069. };
  2070. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2071. var matrix = Matrix.Zero();
  2072. matrix.m[0] = (2.0 * znear) / width;
  2073. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2074. matrix.m[5] = (2.0 * znear) / height;
  2075. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2076. matrix.m[10] = -zfar / (znear - zfar);
  2077. matrix.m[8] = matrix.m[9] = 0.0;
  2078. matrix.m[11] = 1.0;
  2079. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2080. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2081. return matrix;
  2082. };
  2083. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2084. var matrix = Matrix.Zero();
  2085. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2086. return matrix;
  2087. };
  2088. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2089. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2090. var tan = 1.0 / (Math.tan(fov * 0.5));
  2091. if (isVerticalFovFixed) {
  2092. result.m[0] = tan / aspect;
  2093. }
  2094. else {
  2095. result.m[0] = tan;
  2096. }
  2097. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2098. if (isVerticalFovFixed) {
  2099. result.m[5] = tan;
  2100. }
  2101. else {
  2102. result.m[5] = tan * aspect;
  2103. }
  2104. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2105. result.m[8] = result.m[9] = 0.0;
  2106. result.m[10] = -zfar / (znear - zfar);
  2107. result.m[11] = 1.0;
  2108. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2109. result.m[14] = (znear * zfar) / (znear - zfar);
  2110. };
  2111. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2112. var cw = viewport.width;
  2113. var ch = viewport.height;
  2114. var cx = viewport.x;
  2115. var cy = viewport.y;
  2116. 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);
  2117. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2118. };
  2119. Matrix.GetAsMatrix2x2 = function (matrix) {
  2120. return new Float32Array([
  2121. matrix.m[0], matrix.m[1],
  2122. matrix.m[4], matrix.m[5]
  2123. ]);
  2124. };
  2125. Matrix.GetAsMatrix3x3 = function (matrix) {
  2126. return new Float32Array([
  2127. matrix.m[0], matrix.m[1], matrix.m[2],
  2128. matrix.m[4], matrix.m[5], matrix.m[6],
  2129. matrix.m[8], matrix.m[9], matrix.m[10]
  2130. ]);
  2131. };
  2132. Matrix.Transpose = function (matrix) {
  2133. var result = new Matrix();
  2134. result.m[0] = matrix.m[0];
  2135. result.m[1] = matrix.m[4];
  2136. result.m[2] = matrix.m[8];
  2137. result.m[3] = matrix.m[12];
  2138. result.m[4] = matrix.m[1];
  2139. result.m[5] = matrix.m[5];
  2140. result.m[6] = matrix.m[9];
  2141. result.m[7] = matrix.m[13];
  2142. result.m[8] = matrix.m[2];
  2143. result.m[9] = matrix.m[6];
  2144. result.m[10] = matrix.m[10];
  2145. result.m[11] = matrix.m[14];
  2146. result.m[12] = matrix.m[3];
  2147. result.m[13] = matrix.m[7];
  2148. result.m[14] = matrix.m[11];
  2149. result.m[15] = matrix.m[15];
  2150. return result;
  2151. };
  2152. Matrix.Reflection = function (plane) {
  2153. var matrix = new Matrix();
  2154. Matrix.ReflectionToRef(plane, matrix);
  2155. return matrix;
  2156. };
  2157. Matrix.ReflectionToRef = function (plane, result) {
  2158. plane.normalize();
  2159. var x = plane.normal.x;
  2160. var y = plane.normal.y;
  2161. var z = plane.normal.z;
  2162. var temp = -2 * x;
  2163. var temp2 = -2 * y;
  2164. var temp3 = -2 * z;
  2165. result.m[0] = (temp * x) + 1;
  2166. result.m[1] = temp2 * x;
  2167. result.m[2] = temp3 * x;
  2168. result.m[3] = 0.0;
  2169. result.m[4] = temp * y;
  2170. result.m[5] = (temp2 * y) + 1;
  2171. result.m[6] = temp3 * y;
  2172. result.m[7] = 0.0;
  2173. result.m[8] = temp * z;
  2174. result.m[9] = temp2 * z;
  2175. result.m[10] = (temp3 * z) + 1;
  2176. result.m[11] = 0.0;
  2177. result.m[12] = temp * plane.d;
  2178. result.m[13] = temp2 * plane.d;
  2179. result.m[14] = temp3 * plane.d;
  2180. result.m[15] = 1.0;
  2181. };
  2182. Matrix._tempQuaternion = new Quaternion();
  2183. Matrix._xAxis = Vector3.Zero();
  2184. Matrix._yAxis = Vector3.Zero();
  2185. Matrix._zAxis = Vector3.Zero();
  2186. return Matrix;
  2187. })();
  2188. BABYLON.Matrix = Matrix;
  2189. var Plane = (function () {
  2190. function Plane(a, b, c, d) {
  2191. this.normal = new Vector3(a, b, c);
  2192. this.d = d;
  2193. }
  2194. Plane.prototype.asArray = function () {
  2195. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2196. };
  2197. // Methods
  2198. Plane.prototype.clone = function () {
  2199. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2200. };
  2201. Plane.prototype.normalize = function () {
  2202. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2203. var magnitude = 0;
  2204. if (norm !== 0) {
  2205. magnitude = 1.0 / norm;
  2206. }
  2207. this.normal.x *= magnitude;
  2208. this.normal.y *= magnitude;
  2209. this.normal.z *= magnitude;
  2210. this.d *= magnitude;
  2211. return this;
  2212. };
  2213. Plane.prototype.transform = function (transformation) {
  2214. var transposedMatrix = Matrix.Transpose(transformation);
  2215. var x = this.normal.x;
  2216. var y = this.normal.y;
  2217. var z = this.normal.z;
  2218. var d = this.d;
  2219. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2220. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2221. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2222. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2223. return new Plane(normalX, normalY, normalZ, finalD);
  2224. };
  2225. Plane.prototype.dotCoordinate = function (point) {
  2226. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2227. };
  2228. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2229. var x1 = point2.x - point1.x;
  2230. var y1 = point2.y - point1.y;
  2231. var z1 = point2.z - point1.z;
  2232. var x2 = point3.x - point1.x;
  2233. var y2 = point3.y - point1.y;
  2234. var z2 = point3.z - point1.z;
  2235. var yz = (y1 * z2) - (z1 * y2);
  2236. var xz = (z1 * x2) - (x1 * z2);
  2237. var xy = (x1 * y2) - (y1 * x2);
  2238. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2239. var invPyth;
  2240. if (pyth !== 0) {
  2241. invPyth = 1.0 / pyth;
  2242. }
  2243. else {
  2244. invPyth = 0;
  2245. }
  2246. this.normal.x = yz * invPyth;
  2247. this.normal.y = xz * invPyth;
  2248. this.normal.z = xy * invPyth;
  2249. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2250. return this;
  2251. };
  2252. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2253. var dot = Vector3.Dot(this.normal, direction);
  2254. return (dot <= epsilon);
  2255. };
  2256. Plane.prototype.signedDistanceTo = function (point) {
  2257. return Vector3.Dot(point, this.normal) + this.d;
  2258. };
  2259. // Statics
  2260. Plane.FromArray = function (array) {
  2261. return new Plane(array[0], array[1], array[2], array[3]);
  2262. };
  2263. Plane.FromPoints = function (point1, point2, point3) {
  2264. var result = new Plane(0, 0, 0, 0);
  2265. result.copyFromPoints(point1, point2, point3);
  2266. return result;
  2267. };
  2268. Plane.FromPositionAndNormal = function (origin, normal) {
  2269. var result = new Plane(0, 0, 0, 0);
  2270. normal.normalize();
  2271. result.normal = normal;
  2272. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2273. return result;
  2274. };
  2275. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2276. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2277. return Vector3.Dot(point, normal) + d;
  2278. };
  2279. return Plane;
  2280. })();
  2281. BABYLON.Plane = Plane;
  2282. var Viewport = (function () {
  2283. function Viewport(x, y, width, height) {
  2284. this.x = x;
  2285. this.y = y;
  2286. this.width = width;
  2287. this.height = height;
  2288. }
  2289. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2290. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2291. };
  2292. return Viewport;
  2293. })();
  2294. BABYLON.Viewport = Viewport;
  2295. var Frustum = (function () {
  2296. function Frustum() {
  2297. }
  2298. Frustum.GetPlanes = function (transform) {
  2299. var frustumPlanes = [];
  2300. for (var index = 0; index < 6; index++) {
  2301. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2302. }
  2303. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2304. return frustumPlanes;
  2305. };
  2306. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2307. // Near
  2308. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2309. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2310. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2311. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2312. frustumPlanes[0].normalize();
  2313. // Far
  2314. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2315. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2316. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2317. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2318. frustumPlanes[1].normalize();
  2319. // Left
  2320. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2321. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2322. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2323. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2324. frustumPlanes[2].normalize();
  2325. // Right
  2326. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2327. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2328. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2329. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2330. frustumPlanes[3].normalize();
  2331. // Top
  2332. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2333. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2334. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2335. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2336. frustumPlanes[4].normalize();
  2337. // Bottom
  2338. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2339. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2340. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2341. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2342. frustumPlanes[5].normalize();
  2343. };
  2344. return Frustum;
  2345. })();
  2346. BABYLON.Frustum = Frustum;
  2347. (function (Space) {
  2348. Space[Space["LOCAL"] = 0] = "LOCAL";
  2349. Space[Space["WORLD"] = 1] = "WORLD";
  2350. })(BABYLON.Space || (BABYLON.Space = {}));
  2351. var Space = BABYLON.Space;
  2352. var Axis = (function () {
  2353. function Axis() {
  2354. }
  2355. Axis.X = new Vector3(1, 0, 0);
  2356. Axis.Y = new Vector3(0, 1, 0);
  2357. Axis.Z = new Vector3(0, 0, 1);
  2358. return Axis;
  2359. })();
  2360. BABYLON.Axis = Axis;
  2361. ;
  2362. var BezierCurve = (function () {
  2363. function BezierCurve() {
  2364. }
  2365. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2366. // Extract X (which is equal to time here)
  2367. var f0 = 1 - 3 * x2 + 3 * x1;
  2368. var f1 = 3 * x2 - 6 * x1;
  2369. var f2 = 3 * x1;
  2370. var refinedT = t;
  2371. for (var i = 0; i < 5; i++) {
  2372. var refinedT2 = refinedT * refinedT;
  2373. var refinedT3 = refinedT2 * refinedT;
  2374. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2375. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2376. refinedT -= (x - t) * slope;
  2377. refinedT = Math.min(1, Math.max(0, refinedT));
  2378. }
  2379. // Resolve cubic bezier for the given x
  2380. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2381. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2382. Math.pow(refinedT, 3);
  2383. };
  2384. return BezierCurve;
  2385. })();
  2386. BABYLON.BezierCurve = BezierCurve;
  2387. (function (Orientation) {
  2388. Orientation[Orientation["CW"] = 0] = "CW";
  2389. Orientation[Orientation["CCW"] = 1] = "CCW";
  2390. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2391. var Orientation = BABYLON.Orientation;
  2392. var Angle = (function () {
  2393. function Angle(radians) {
  2394. var _this = this;
  2395. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2396. this.radians = function () { return _this._radians; };
  2397. this._radians = radians;
  2398. if (this._radians < 0)
  2399. this._radians += (2 * Math.PI);
  2400. }
  2401. Angle.BetweenTwoPoints = function (a, b) {
  2402. var delta = b.subtract(a);
  2403. var theta = Math.atan2(delta.y, delta.x);
  2404. return new Angle(theta);
  2405. };
  2406. Angle.FromRadians = function (radians) {
  2407. return new Angle(radians);
  2408. };
  2409. Angle.FromDegrees = function (degrees) {
  2410. return new Angle(degrees * Math.PI / 180);
  2411. };
  2412. return Angle;
  2413. })();
  2414. BABYLON.Angle = Angle;
  2415. var Arc2 = (function () {
  2416. function Arc2(startPoint, midPoint, endPoint) {
  2417. this.startPoint = startPoint;
  2418. this.midPoint = midPoint;
  2419. this.endPoint = endPoint;
  2420. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2421. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2422. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2423. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2424. 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);
  2425. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2426. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2427. var a1 = this.startAngle.degrees();
  2428. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2429. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2430. // angles correction
  2431. if (a2 - a1 > +180.0)
  2432. a2 -= 360.0;
  2433. if (a2 - a1 < -180.0)
  2434. a2 += 360.0;
  2435. if (a3 - a2 > +180.0)
  2436. a3 -= 360.0;
  2437. if (a3 - a2 < -180.0)
  2438. a3 += 360.0;
  2439. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2440. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2441. }
  2442. return Arc2;
  2443. })();
  2444. BABYLON.Arc2 = Arc2;
  2445. var Path2 = (function () {
  2446. function Path2(x, y) {
  2447. this._points = new Array();
  2448. this._length = 0;
  2449. this.closed = false;
  2450. this._points.push(new Vector2(x, y));
  2451. }
  2452. Path2.prototype.addLineTo = function (x, y) {
  2453. if (closed) {
  2454. //Tools.Error("cannot add lines to closed paths");
  2455. return this;
  2456. }
  2457. var newPoint = new Vector2(x, y);
  2458. var previousPoint = this._points[this._points.length - 1];
  2459. this._points.push(newPoint);
  2460. this._length += newPoint.subtract(previousPoint).length();
  2461. return this;
  2462. };
  2463. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2464. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2465. if (closed) {
  2466. //Tools.Error("cannot add arcs to closed paths");
  2467. return this;
  2468. }
  2469. var startPoint = this._points[this._points.length - 1];
  2470. var midPoint = new Vector2(midX, midY);
  2471. var endPoint = new Vector2(endX, endY);
  2472. var arc = new Arc2(startPoint, midPoint, endPoint);
  2473. var increment = arc.angle.radians() / numberOfSegments;
  2474. if (arc.orientation === Orientation.CW)
  2475. increment *= -1;
  2476. var currentAngle = arc.startAngle.radians() + increment;
  2477. for (var i = 0; i < numberOfSegments; i++) {
  2478. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2479. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2480. this.addLineTo(x, y);
  2481. currentAngle += increment;
  2482. }
  2483. return this;
  2484. };
  2485. Path2.prototype.close = function () {
  2486. this.closed = true;
  2487. return this;
  2488. };
  2489. Path2.prototype.length = function () {
  2490. var result = this._length;
  2491. if (!this.closed) {
  2492. var lastPoint = this._points[this._points.length - 1];
  2493. var firstPoint = this._points[0];
  2494. result += (firstPoint.subtract(lastPoint).length());
  2495. }
  2496. return result;
  2497. };
  2498. Path2.prototype.getPoints = function () {
  2499. return this._points;
  2500. };
  2501. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2502. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2503. //Tools.Error("normalized length position should be between 0 and 1.");
  2504. return Vector2.Zero();
  2505. }
  2506. var lengthPosition = normalizedLengthPosition * this.length();
  2507. var previousOffset = 0;
  2508. for (var i = 0; i < this._points.length; i++) {
  2509. var j = (i + 1) % this._points.length;
  2510. var a = this._points[i];
  2511. var b = this._points[j];
  2512. var bToA = b.subtract(a);
  2513. var nextOffset = (bToA.length() + previousOffset);
  2514. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2515. var dir = bToA.normalize();
  2516. var localOffset = lengthPosition - previousOffset;
  2517. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2518. }
  2519. previousOffset = nextOffset;
  2520. }
  2521. //Tools.Error("internal error");
  2522. return Vector2.Zero();
  2523. };
  2524. Path2.StartingAt = function (x, y) {
  2525. return new Path2(x, y);
  2526. };
  2527. return Path2;
  2528. })();
  2529. BABYLON.Path2 = Path2;
  2530. var Path3D = (function () {
  2531. /**
  2532. * new Path3D(path, normal, raw)
  2533. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2534. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2535. * path : an array of Vector3, the curve axis of the Path3D
  2536. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2537. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2538. */
  2539. function Path3D(path, firstNormal, raw) {
  2540. this.path = path;
  2541. this._curve = new Array();
  2542. this._distances = new Array();
  2543. this._tangents = new Array();
  2544. this._normals = new Array();
  2545. this._binormals = new Array();
  2546. for (var p = 0; p < path.length; p++) {
  2547. this._curve[p] = path[p].clone(); // hard copy
  2548. }
  2549. this._raw = raw || false;
  2550. this._compute(firstNormal);
  2551. }
  2552. /**
  2553. * Returns the Path3D array of successive Vector3 designing its curve.
  2554. */
  2555. Path3D.prototype.getCurve = function () {
  2556. return this._curve;
  2557. };
  2558. /**
  2559. * Returns an array populated with tangent vectors on each Path3D curve point.
  2560. */
  2561. Path3D.prototype.getTangents = function () {
  2562. return this._tangents;
  2563. };
  2564. /**
  2565. * Returns an array populated with normal vectors on each Path3D curve point.
  2566. */
  2567. Path3D.prototype.getNormals = function () {
  2568. return this._normals;
  2569. };
  2570. /**
  2571. * Returns an array populated with binormal vectors on each Path3D curve point.
  2572. */
  2573. Path3D.prototype.getBinormals = function () {
  2574. return this._binormals;
  2575. };
  2576. /**
  2577. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2578. */
  2579. Path3D.prototype.getDistances = function () {
  2580. return this._distances;
  2581. };
  2582. /**
  2583. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2584. * Returns the same object updated.
  2585. */
  2586. Path3D.prototype.update = function (path, firstNormal) {
  2587. for (var p = 0; p < path.length; p++) {
  2588. this._curve[p].x = path[p].x;
  2589. this._curve[p].y = path[p].y;
  2590. this._curve[p].z = path[p].z;
  2591. }
  2592. this._compute(firstNormal);
  2593. return this;
  2594. };
  2595. // private function compute() : computes tangents, normals and binormals
  2596. Path3D.prototype._compute = function (firstNormal) {
  2597. var l = this._curve.length;
  2598. // first and last tangents
  2599. this._tangents[0] = this._getFirstNonNullVector(0);
  2600. if (!this._raw) {
  2601. this._tangents[0].normalize();
  2602. }
  2603. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2604. if (!this._raw) {
  2605. this._tangents[l - 1].normalize();
  2606. }
  2607. // normals and binormals at first point : arbitrary vector with _normalVector()
  2608. var tg0 = this._tangents[0];
  2609. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2610. this._normals[0] = pp0;
  2611. if (!this._raw) {
  2612. this._normals[0].normalize();
  2613. }
  2614. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2615. if (!this._raw) {
  2616. this._binormals[0].normalize();
  2617. }
  2618. this._distances[0] = 0;
  2619. // normals and binormals : next points
  2620. var prev; // previous vector (segment)
  2621. var cur; // current vector (segment)
  2622. var curTang; // current tangent
  2623. // previous normal
  2624. var prevBinor; // previous binormal
  2625. for (var i = 1; i < l; i++) {
  2626. // tangents
  2627. prev = this._getLastNonNullVector(i);
  2628. if (i < l - 1) {
  2629. cur = this._getFirstNonNullVector(i);
  2630. this._tangents[i] = prev.add(cur);
  2631. this._tangents[i].normalize();
  2632. }
  2633. this._distances[i] = this._distances[i - 1] + prev.length();
  2634. // normals and binormals
  2635. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2636. curTang = this._tangents[i];
  2637. prevBinor = this._binormals[i - 1];
  2638. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2639. if (!this._raw) {
  2640. this._normals[i].normalize();
  2641. }
  2642. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2643. if (!this._raw) {
  2644. this._binormals[i].normalize();
  2645. }
  2646. }
  2647. };
  2648. // private function getFirstNonNullVector(index)
  2649. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2650. Path3D.prototype._getFirstNonNullVector = function (index) {
  2651. var i = 1;
  2652. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2653. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2654. i++;
  2655. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2656. }
  2657. return nNVector;
  2658. };
  2659. // private function getLastNonNullVector(index)
  2660. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2661. Path3D.prototype._getLastNonNullVector = function (index) {
  2662. var i = 1;
  2663. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2664. while (nLVector.length() === 0 && index > i + 1) {
  2665. i++;
  2666. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2667. }
  2668. return nLVector;
  2669. };
  2670. // private function normalVector(v0, vt, va) :
  2671. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2672. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2673. Path3D.prototype._normalVector = function (v0, vt, va) {
  2674. var normal0;
  2675. if (va === undefined || va === null) {
  2676. var point;
  2677. if (!MathTools.WithinEpsilon(vt.y, 1, BABYLON.Epsilon)) {
  2678. point = new Vector3(0, -1, 0);
  2679. }
  2680. else if (!MathTools.WithinEpsilon(vt.x, 1, BABYLON.Epsilon)) {
  2681. point = new Vector3(1, 0, 0);
  2682. }
  2683. else if (!MathTools.WithinEpsilon(vt.z, 1, BABYLON.Epsilon)) {
  2684. point = new Vector3(0, 0, 1);
  2685. }
  2686. normal0 = Vector3.Cross(vt, point);
  2687. }
  2688. else {
  2689. normal0 = Vector3.Cross(vt, va);
  2690. Vector3.CrossToRef(normal0, vt, normal0);
  2691. }
  2692. normal0.normalize();
  2693. return normal0;
  2694. };
  2695. return Path3D;
  2696. })();
  2697. BABYLON.Path3D = Path3D;
  2698. var Curve3 = (function () {
  2699. /**
  2700. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  2701. * A Curve3 is designed from a series of successive Vector3.
  2702. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  2703. */
  2704. function Curve3(points) {
  2705. this._length = 0;
  2706. this._points = points;
  2707. this._length = this._computeLength(points);
  2708. }
  2709. /**
  2710. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  2711. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  2712. * @param v1 (Vector3) the control point
  2713. * @param v2 (Vector3) the end point of the Quadratic Bezier
  2714. * @param nbPoints (integer) the wanted number of points in the curve
  2715. */
  2716. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2717. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2718. var bez = new Array();
  2719. var equation = function (t, val0, val1, val2) {
  2720. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2721. return res;
  2722. };
  2723. for (var i = 0; i <= nbPoints; i++) {
  2724. 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)));
  2725. }
  2726. return new Curve3(bez);
  2727. };
  2728. /**
  2729. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  2730. * @param v0 (Vector3) the origin point of the Cubic Bezier
  2731. * @param v1 (Vector3) the first control point
  2732. * @param v2 (Vector3) the second control point
  2733. * @param v3 (Vector3) the end point of the Cubic Bezier
  2734. * @param nbPoints (integer) the wanted number of points in the curve
  2735. */
  2736. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2737. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2738. var bez = new Array();
  2739. var equation = function (t, val0, val1, val2, val3) {
  2740. 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;
  2741. return res;
  2742. };
  2743. for (var i = 0; i <= nbPoints; i++) {
  2744. 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)));
  2745. }
  2746. return new Curve3(bez);
  2747. };
  2748. /**
  2749. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  2750. * @param p1 (Vector3) the origin point of the Hermite Spline
  2751. * @param t1 (Vector3) the tangent vector at the origin point
  2752. * @param p2 (Vector3) the end point of the Hermite Spline
  2753. * @param t2 (Vector3) the tangent vector at the end point
  2754. * @param nbPoints (integer) the wanted number of points in the curve
  2755. */
  2756. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2757. var hermite = new Array();
  2758. var step = 1 / nbPoints;
  2759. for (var i = 0; i <= nbPoints; i++) {
  2760. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2761. }
  2762. return new Curve3(hermite);
  2763. };
  2764. /**
  2765. * Returns the Curve3 stored array of successive Vector3
  2766. */
  2767. Curve3.prototype.getPoints = function () {
  2768. return this._points;
  2769. };
  2770. /**
  2771. * Returns the computed length (float) of the curve.
  2772. */
  2773. Curve3.prototype.length = function () {
  2774. return this._length;
  2775. };
  2776. /**
  2777. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  2778. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  2779. * curveA and curveB keep unchanged.
  2780. */
  2781. Curve3.prototype.continue = function (curve) {
  2782. var lastPoint = this._points[this._points.length - 1];
  2783. var continuedPoints = this._points.slice();
  2784. var curvePoints = curve.getPoints();
  2785. for (var i = 1; i < curvePoints.length; i++) {
  2786. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2787. }
  2788. var continuedCurve = new Curve3(continuedPoints);
  2789. return continuedCurve;
  2790. };
  2791. Curve3.prototype._computeLength = function (path) {
  2792. var l = 0;
  2793. for (var i = 1; i < path.length; i++) {
  2794. l += (path[i].subtract(path[i - 1])).length();
  2795. }
  2796. return l;
  2797. };
  2798. return Curve3;
  2799. })();
  2800. BABYLON.Curve3 = Curve3;
  2801. // SphericalHarmonics
  2802. var SphericalHarmonics = (function () {
  2803. function SphericalHarmonics() {
  2804. this.L00 = Vector3.Zero();
  2805. this.L1_1 = Vector3.Zero();
  2806. this.L10 = Vector3.Zero();
  2807. this.L11 = Vector3.Zero();
  2808. this.L2_2 = Vector3.Zero();
  2809. this.L2_1 = Vector3.Zero();
  2810. this.L20 = Vector3.Zero();
  2811. this.L21 = Vector3.Zero();
  2812. this.L22 = Vector3.Zero();
  2813. }
  2814. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  2815. var colorVector = new Vector3(color.r, color.g, color.b);
  2816. var c = colorVector.scale(deltaSolidAngle);
  2817. this.L00 = this.L00.add(c.scale(0.282095));
  2818. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  2819. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  2820. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  2821. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  2822. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  2823. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  2824. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  2825. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  2826. };
  2827. SphericalHarmonics.prototype.scale = function (scale) {
  2828. this.L00 = this.L00.scale(scale);
  2829. this.L1_1 = this.L1_1.scale(scale);
  2830. this.L10 = this.L10.scale(scale);
  2831. this.L11 = this.L11.scale(scale);
  2832. this.L2_2 = this.L2_2.scale(scale);
  2833. this.L2_1 = this.L2_1.scale(scale);
  2834. this.L20 = this.L20.scale(scale);
  2835. this.L21 = this.L21.scale(scale);
  2836. this.L22 = this.L22.scale(scale);
  2837. };
  2838. return SphericalHarmonics;
  2839. })();
  2840. BABYLON.SphericalHarmonics = SphericalHarmonics;
  2841. // SphericalPolynomial
  2842. var SphericalPolynomial = (function () {
  2843. function SphericalPolynomial() {
  2844. this.x = Vector3.Zero();
  2845. this.y = Vector3.Zero();
  2846. this.z = Vector3.Zero();
  2847. this.xx = Vector3.Zero();
  2848. this.yy = Vector3.Zero();
  2849. this.zz = Vector3.Zero();
  2850. this.xy = Vector3.Zero();
  2851. this.yz = Vector3.Zero();
  2852. this.zx = Vector3.Zero();
  2853. }
  2854. SphericalPolynomial.prototype.addAmbient = function (color) {
  2855. var colorVector = new Vector3(color.r, color.g, color.b);
  2856. this.xx = this.xx.add(colorVector);
  2857. this.yy = this.yy.add(colorVector);
  2858. this.zz = this.zz.add(colorVector);
  2859. };
  2860. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  2861. var result = new SphericalPolynomial();
  2862. result.x = harmonics.L11.scale(1.02333);
  2863. result.y = harmonics.L1_1.scale(1.02333);
  2864. result.z = harmonics.L10.scale(1.02333);
  2865. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  2866. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  2867. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  2868. result.yz = harmonics.L2_1.scale(0.858086);
  2869. result.zx = harmonics.L21.scale(0.858086);
  2870. result.xy = harmonics.L2_2.scale(0.858086);
  2871. return result;
  2872. };
  2873. return SphericalPolynomial;
  2874. })();
  2875. BABYLON.SphericalPolynomial = SphericalPolynomial;
  2876. // Vertex formats
  2877. var PositionNormalVertex = (function () {
  2878. function PositionNormalVertex(position, normal) {
  2879. if (position === void 0) { position = Vector3.Zero(); }
  2880. if (normal === void 0) { normal = Vector3.Up(); }
  2881. this.position = position;
  2882. this.normal = normal;
  2883. }
  2884. PositionNormalVertex.prototype.clone = function () {
  2885. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2886. };
  2887. return PositionNormalVertex;
  2888. })();
  2889. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2890. var PositionNormalTextureVertex = (function () {
  2891. function PositionNormalTextureVertex(position, normal, uv) {
  2892. if (position === void 0) { position = Vector3.Zero(); }
  2893. if (normal === void 0) { normal = Vector3.Up(); }
  2894. if (uv === void 0) { uv = Vector2.Zero(); }
  2895. this.position = position;
  2896. this.normal = normal;
  2897. this.uv = uv;
  2898. }
  2899. PositionNormalTextureVertex.prototype.clone = function () {
  2900. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2901. };
  2902. return PositionNormalTextureVertex;
  2903. })();
  2904. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2905. // Temporary pre-allocated objects for engine internal use
  2906. // usage in any internal function :
  2907. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  2908. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  2909. var Tmp = (function () {
  2910. function Tmp() {
  2911. }
  2912. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  2913. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  2914. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  2915. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  2916. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  2917. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  2918. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  2919. Matrix.Zero(), Matrix.Zero(),
  2920. Matrix.Zero(), Matrix.Zero(),
  2921. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  2922. return Tmp;
  2923. })();
  2924. BABYLON.Tmp = Tmp;
  2925. })(BABYLON || (BABYLON = {}));
  2926. var BABYLON;
  2927. (function (BABYLON) {
  2928. function generateSerializableMember(type, sourceName) {
  2929. return function (target, propertyKey) {
  2930. if (!target.__serializableMembers) {
  2931. target.__serializableMembers = {};
  2932. }
  2933. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  2934. };
  2935. }
  2936. function serialize(sourceName) {
  2937. return generateSerializableMember(0, sourceName); // value member
  2938. }
  2939. BABYLON.serialize = serialize;
  2940. function serializeAsTexture(sourceName) {
  2941. return generateSerializableMember(1, sourceName); // texture member
  2942. }
  2943. BABYLON.serializeAsTexture = serializeAsTexture;
  2944. function serializeAsColor3(sourceName) {
  2945. return generateSerializableMember(2, sourceName); // color3 member
  2946. }
  2947. BABYLON.serializeAsColor3 = serializeAsColor3;
  2948. function serializeAsFresnelParameters(sourceName) {
  2949. return generateSerializableMember(3, sourceName); // fresnel parameters member
  2950. }
  2951. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  2952. function serializeAsVector2(sourceName) {
  2953. return generateSerializableMember(4, sourceName); // vector2 member
  2954. }
  2955. BABYLON.serializeAsVector2 = serializeAsVector2;
  2956. function serializeAsVector3(sourceName) {
  2957. return generateSerializableMember(5, sourceName); // vector3 member
  2958. }
  2959. BABYLON.serializeAsVector3 = serializeAsVector3;
  2960. function serializeAsMeshReference(sourceName) {
  2961. return generateSerializableMember(6, sourceName); // mesh reference member
  2962. }
  2963. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  2964. var SerializationHelper = (function () {
  2965. function SerializationHelper() {
  2966. }
  2967. SerializationHelper.Serialize = function (entity, serializationObject) {
  2968. if (!serializationObject) {
  2969. serializationObject = {};
  2970. }
  2971. // Tags
  2972. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  2973. // Properties
  2974. for (var property in entity.__serializableMembers) {
  2975. var propertyDescriptor = entity.__serializableMembers[property];
  2976. var targetPropertyName = propertyDescriptor.sourceName || property;
  2977. var propertyType = propertyDescriptor.type;
  2978. var sourceProperty = entity[property];
  2979. if (sourceProperty !== undefined && sourceProperty !== null) {
  2980. switch (propertyType) {
  2981. case 0:
  2982. serializationObject[targetPropertyName] = sourceProperty;
  2983. break;
  2984. case 1:
  2985. serializationObject[targetPropertyName] = sourceProperty.serialize();
  2986. break;
  2987. case 2:
  2988. serializationObject[targetPropertyName] = sourceProperty.asArray();
  2989. break;
  2990. case 3:
  2991. serializationObject[targetPropertyName] = sourceProperty.serialize();
  2992. break;
  2993. case 4:
  2994. serializationObject[targetPropertyName] = sourceProperty.asArray();
  2995. break;
  2996. case 5:
  2997. serializationObject[targetPropertyName] = sourceProperty.asArray();
  2998. break;
  2999. case 6:
  3000. serializationObject[targetPropertyName] = sourceProperty.id;
  3001. break;
  3002. }
  3003. }
  3004. }
  3005. return serializationObject;
  3006. };
  3007. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3008. var destination = creationFunction();
  3009. // Tags
  3010. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3011. // Properties
  3012. for (var property in destination.__serializableMembers) {
  3013. var propertyDescriptor = destination.__serializableMembers[property];
  3014. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3015. var propertyType = propertyDescriptor.type;
  3016. if (sourceProperty !== undefined && sourceProperty !== null) {
  3017. switch (propertyType) {
  3018. case 0:
  3019. destination[property] = sourceProperty;
  3020. break;
  3021. case 1:
  3022. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3023. break;
  3024. case 2:
  3025. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3026. break;
  3027. case 3:
  3028. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3029. break;
  3030. case 4:
  3031. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3032. break;
  3033. case 5:
  3034. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3035. break;
  3036. case 6:
  3037. destination[property] = scene.getLastMeshByID(sourceProperty);
  3038. break;
  3039. }
  3040. }
  3041. }
  3042. return destination;
  3043. };
  3044. SerializationHelper.Clone = function (creationFunction, source) {
  3045. var destination = creationFunction();
  3046. // Tags
  3047. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3048. // Properties
  3049. for (var property in destination.__serializableMembers) {
  3050. var propertyDescriptor = destination.__serializableMembers[property];
  3051. var sourceProperty = source[property];
  3052. var propertyType = propertyDescriptor.type;
  3053. if (sourceProperty !== undefined && sourceProperty !== null) {
  3054. switch (propertyType) {
  3055. case 0: // Value
  3056. case 6:
  3057. destination[property] = sourceProperty;
  3058. break;
  3059. case 1: // Texture
  3060. case 2: // Color3
  3061. case 3: // FresnelParameters
  3062. case 4: // Vector2
  3063. case 5:
  3064. destination[property] = sourceProperty.clone();
  3065. break;
  3066. }
  3067. }
  3068. }
  3069. return destination;
  3070. };
  3071. return SerializationHelper;
  3072. })();
  3073. BABYLON.SerializationHelper = SerializationHelper;
  3074. })(BABYLON || (BABYLON = {}));
  3075. var BABYLON;
  3076. (function (BABYLON) {
  3077. /**
  3078. * A class serves as a medium between the observable and its observers
  3079. */
  3080. var EventState = (function () {
  3081. /**
  3082. * If the callback of a given Observer set skipNextObervers to true the following observers will be ignored
  3083. */
  3084. function EventState(skipNextObervers) {
  3085. if (skipNextObervers === void 0) { skipNextObervers = false; }
  3086. this.skipNextObervers = skipNextObervers;
  3087. }
  3088. return EventState;
  3089. })();
  3090. BABYLON.EventState = EventState;
  3091. var Observer = (function () {
  3092. function Observer(callback, mask) {
  3093. this.callback = callback;
  3094. this.mask = mask;
  3095. }
  3096. return Observer;
  3097. })();
  3098. BABYLON.Observer = Observer;
  3099. var Observable = (function () {
  3100. function Observable() {
  3101. this._observers = new Array();
  3102. }
  3103. /**
  3104. * Create a new Observer with the specified callback
  3105. * @param callback the callback that will be executed for that Observer
  3106. * @param mash the mask used to filter observers
  3107. * @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.
  3108. */
  3109. Observable.prototype.add = function (callback, mask, insertFirst) {
  3110. if (mask === void 0) { mask = -1; }
  3111. if (insertFirst === void 0) { insertFirst = false; }
  3112. if (!callback) {
  3113. return null;
  3114. }
  3115. var observer = new Observer(callback, mask);
  3116. if (insertFirst) {
  3117. this._observers.unshift(observer);
  3118. }
  3119. else {
  3120. this._observers.push(observer);
  3121. }
  3122. return observer;
  3123. };
  3124. /**
  3125. * Remove an Observer from the Observable object
  3126. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3127. */
  3128. Observable.prototype.remove = function (observer) {
  3129. var index = this._observers.indexOf(observer);
  3130. if (index !== -1) {
  3131. this._observers.splice(index, 1);
  3132. return true;
  3133. }
  3134. return false;
  3135. };
  3136. /**
  3137. * Remove a callback from the Observable object
  3138. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3139. */
  3140. Observable.prototype.removeCallback = function (callback) {
  3141. for (var index = 0; index < this._observers.length; index++) {
  3142. if (this._observers[index].callback === callback) {
  3143. this._observers.splice(index, 1);
  3144. return true;
  3145. }
  3146. }
  3147. return false;
  3148. };
  3149. /**
  3150. * Notify all Observers by calling their respective callback with the given data
  3151. * @param eventData
  3152. * @param mask
  3153. */
  3154. Observable.prototype.notifyObservers = function (eventData, mask) {
  3155. if (mask === void 0) { mask = -1; }
  3156. var state = new EventState();
  3157. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3158. var obs = _a[_i];
  3159. if (obs.mask & mask) {
  3160. obs.callback(eventData, state);
  3161. }
  3162. if (state.skipNextObervers) {
  3163. break;
  3164. }
  3165. }
  3166. };
  3167. /**
  3168. * return true is the Observable has at least one Observer registered
  3169. */
  3170. Observable.prototype.hasObservers = function () {
  3171. return this._observers.length > 0;
  3172. };
  3173. /**
  3174. * Clear the list of observers
  3175. */
  3176. Observable.prototype.clear = function () {
  3177. this._observers = new Array();
  3178. };
  3179. /**
  3180. * Clone the current observable
  3181. */
  3182. Observable.prototype.clone = function () {
  3183. var result = new Observable();
  3184. result._observers = this._observers.slice(0);
  3185. return result;
  3186. };
  3187. return Observable;
  3188. })();
  3189. BABYLON.Observable = Observable;
  3190. })(BABYLON || (BABYLON = {}));
  3191. var BABYLON;
  3192. (function (BABYLON) {
  3193. var Database = (function () {
  3194. function Database(urlToScene, callbackManifestChecked) {
  3195. // Handling various flavors of prefixed version of IndexedDB
  3196. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3197. this.callbackManifestChecked = callbackManifestChecked;
  3198. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3199. this.db = null;
  3200. this.enableSceneOffline = false;
  3201. this.enableTexturesOffline = false;
  3202. this.manifestVersionFound = 0;
  3203. this.mustUpdateRessources = false;
  3204. this.hasReachedQuota = false;
  3205. if (!Database.IDBStorageEnabled) {
  3206. this.callbackManifestChecked(true);
  3207. }
  3208. else {
  3209. this.checkManifestFile();
  3210. }
  3211. }
  3212. Database.prototype.checkManifestFile = function () {
  3213. var _this = this;
  3214. function noManifestFile() {
  3215. that.enableSceneOffline = false;
  3216. that.enableTexturesOffline = false;
  3217. that.callbackManifestChecked(false);
  3218. }
  3219. var that = this;
  3220. var timeStampUsed = false;
  3221. var manifestURL = this.currentSceneUrl + ".manifest";
  3222. var xhr = new XMLHttpRequest();
  3223. if (navigator.onLine) {
  3224. // Adding a timestamp to by-pass browsers' cache
  3225. timeStampUsed = true;
  3226. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3227. }
  3228. xhr.open("GET", manifestURL, true);
  3229. xhr.addEventListener("load", function () {
  3230. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3231. try {
  3232. var manifestFile = JSON.parse(xhr.response);
  3233. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3234. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3235. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3236. _this.manifestVersionFound = manifestFile.version;
  3237. }
  3238. if (_this.callbackManifestChecked) {
  3239. _this.callbackManifestChecked(true);
  3240. }
  3241. }
  3242. catch (ex) {
  3243. noManifestFile();
  3244. }
  3245. }
  3246. else {
  3247. noManifestFile();
  3248. }
  3249. }, false);
  3250. xhr.addEventListener("error", function (event) {
  3251. if (timeStampUsed) {
  3252. timeStampUsed = false;
  3253. // Let's retry without the timeStamp
  3254. // It could fail when coupled with HTML5 Offline API
  3255. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3256. xhr.open("GET", retryManifestURL, true);
  3257. xhr.send();
  3258. }
  3259. else {
  3260. noManifestFile();
  3261. }
  3262. }, false);
  3263. try {
  3264. xhr.send();
  3265. }
  3266. catch (ex) {
  3267. BABYLON.Tools.Error("Error on XHR send request.");
  3268. that.callbackManifestChecked(false);
  3269. }
  3270. };
  3271. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3272. var _this = this;
  3273. function handleError() {
  3274. that.isSupported = false;
  3275. if (errorCallback)
  3276. errorCallback();
  3277. }
  3278. var that = this;
  3279. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3280. // Your browser doesn't support IndexedDB
  3281. this.isSupported = false;
  3282. if (errorCallback)
  3283. errorCallback();
  3284. }
  3285. else {
  3286. // If the DB hasn't been opened or created yet
  3287. if (!this.db) {
  3288. this.hasReachedQuota = false;
  3289. this.isSupported = true;
  3290. var request = this.idbFactory.open("babylonjs", 1);
  3291. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3292. request.onerror = function (event) {
  3293. handleError();
  3294. };
  3295. // executes when a version change transaction cannot complete due to other active transactions
  3296. request.onblocked = function (event) {
  3297. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3298. handleError();
  3299. };
  3300. // DB has been opened successfully
  3301. request.onsuccess = function (event) {
  3302. _this.db = request.result;
  3303. successCallback();
  3304. };
  3305. // Initialization of the DB. Creating Scenes & Textures stores
  3306. request.onupgradeneeded = function (event) {
  3307. _this.db = (event.target).result;
  3308. try {
  3309. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3310. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3311. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3312. }
  3313. catch (ex) {
  3314. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3315. handleError();
  3316. }
  3317. };
  3318. }
  3319. else {
  3320. if (successCallback)
  3321. successCallback();
  3322. }
  3323. }
  3324. };
  3325. Database.prototype.loadImageFromDB = function (url, image) {
  3326. var _this = this;
  3327. var completeURL = Database.ReturnFullUrlLocation(url);
  3328. var saveAndLoadImage = function () {
  3329. if (!_this.hasReachedQuota && _this.db !== null) {
  3330. // the texture is not yet in the DB, let's try to save it
  3331. _this._saveImageIntoDBAsync(completeURL, image);
  3332. }
  3333. else {
  3334. image.src = url;
  3335. }
  3336. };
  3337. if (!this.mustUpdateRessources) {
  3338. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3339. }
  3340. else {
  3341. saveAndLoadImage();
  3342. }
  3343. };
  3344. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3345. if (this.isSupported && this.db !== null) {
  3346. var texture;
  3347. var transaction = this.db.transaction(["textures"]);
  3348. transaction.onabort = function (event) {
  3349. image.src = url;
  3350. };
  3351. transaction.oncomplete = function (event) {
  3352. var blobTextureURL;
  3353. if (texture) {
  3354. var URL = window.URL || window.webkitURL;
  3355. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3356. image.onerror = function () {
  3357. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3358. image.src = url;
  3359. };
  3360. image.src = blobTextureURL;
  3361. }
  3362. else {
  3363. notInDBCallback();
  3364. }
  3365. };
  3366. var getRequest = transaction.objectStore("textures").get(url);
  3367. getRequest.onsuccess = function (event) {
  3368. texture = (event.target).result;
  3369. };
  3370. getRequest.onerror = function (event) {
  3371. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3372. image.src = url;
  3373. };
  3374. }
  3375. else {
  3376. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3377. image.src = url;
  3378. }
  3379. };
  3380. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3381. var _this = this;
  3382. if (this.isSupported) {
  3383. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3384. var generateBlobUrl = function () {
  3385. var blobTextureURL;
  3386. if (blob) {
  3387. var URL = window.URL || window.webkitURL;
  3388. try {
  3389. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3390. }
  3391. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3392. catch (ex) {
  3393. blobTextureURL = URL.createObjectURL(blob);
  3394. }
  3395. }
  3396. image.src = blobTextureURL;
  3397. };
  3398. if (Database.IsUASupportingBlobStorage) {
  3399. var xhr = new XMLHttpRequest(), blob;
  3400. xhr.open("GET", url, true);
  3401. xhr.responseType = "blob";
  3402. xhr.addEventListener("load", function () {
  3403. if (xhr.status === 200) {
  3404. // Blob as response (XHR2)
  3405. blob = xhr.response;
  3406. var transaction = _this.db.transaction(["textures"], "readwrite");
  3407. // the transaction could abort because of a QuotaExceededError error
  3408. transaction.onabort = function (event) {
  3409. try {
  3410. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3411. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3412. this.hasReachedQuota = true;
  3413. }
  3414. }
  3415. catch (ex) { }
  3416. generateBlobUrl();
  3417. };
  3418. transaction.oncomplete = function (event) {
  3419. generateBlobUrl();
  3420. };
  3421. var newTexture = { textureUrl: url, data: blob };
  3422. try {
  3423. // Put the blob into the dabase
  3424. var addRequest = transaction.objectStore("textures").put(newTexture);
  3425. addRequest.onsuccess = function (event) {
  3426. };
  3427. addRequest.onerror = function (event) {
  3428. generateBlobUrl();
  3429. };
  3430. }
  3431. catch (ex) {
  3432. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3433. if (ex.code === 25) {
  3434. Database.IsUASupportingBlobStorage = false;
  3435. }
  3436. image.src = url;
  3437. }
  3438. }
  3439. else {
  3440. image.src = url;
  3441. }
  3442. }, false);
  3443. xhr.addEventListener("error", function (event) {
  3444. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3445. image.src = url;
  3446. }, false);
  3447. xhr.send();
  3448. }
  3449. else {
  3450. image.src = url;
  3451. }
  3452. }
  3453. else {
  3454. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3455. image.src = url;
  3456. }
  3457. };
  3458. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3459. var _this = this;
  3460. var updateVersion = function (event) {
  3461. // the version is not yet in the DB or we need to update it
  3462. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3463. };
  3464. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3465. };
  3466. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3467. var _this = this;
  3468. if (this.isSupported) {
  3469. var version;
  3470. try {
  3471. var transaction = this.db.transaction(["versions"]);
  3472. transaction.oncomplete = function (event) {
  3473. if (version) {
  3474. // If the version in the JSON file is > than the version in DB
  3475. if (_this.manifestVersionFound > version.data) {
  3476. _this.mustUpdateRessources = true;
  3477. updateInDBCallback();
  3478. }
  3479. else {
  3480. callback(version.data);
  3481. }
  3482. }
  3483. else {
  3484. _this.mustUpdateRessources = true;
  3485. updateInDBCallback();
  3486. }
  3487. };
  3488. transaction.onabort = function (event) {
  3489. callback(-1);
  3490. };
  3491. var getRequest = transaction.objectStore("versions").get(url);
  3492. getRequest.onsuccess = function (event) {
  3493. version = (event.target).result;
  3494. };
  3495. getRequest.onerror = function (event) {
  3496. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3497. callback(-1);
  3498. };
  3499. }
  3500. catch (ex) {
  3501. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3502. callback(-1);
  3503. }
  3504. }
  3505. else {
  3506. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3507. callback(-1);
  3508. }
  3509. };
  3510. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3511. var _this = this;
  3512. if (this.isSupported && !this.hasReachedQuota) {
  3513. try {
  3514. // Open a transaction to the database
  3515. var transaction = this.db.transaction(["versions"], "readwrite");
  3516. // the transaction could abort because of a QuotaExceededError error
  3517. transaction.onabort = function (event) {
  3518. try {
  3519. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3520. _this.hasReachedQuota = true;
  3521. }
  3522. }
  3523. catch (ex) { }
  3524. callback(-1);
  3525. };
  3526. transaction.oncomplete = function (event) {
  3527. callback(_this.manifestVersionFound);
  3528. };
  3529. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3530. // Put the scene into the database
  3531. var addRequest = transaction.objectStore("versions").put(newVersion);
  3532. addRequest.onsuccess = function (event) {
  3533. };
  3534. addRequest.onerror = function (event) {
  3535. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3536. };
  3537. }
  3538. catch (ex) {
  3539. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3540. callback(-1);
  3541. }
  3542. }
  3543. else {
  3544. callback(-1);
  3545. }
  3546. };
  3547. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3548. var _this = this;
  3549. var completeUrl = Database.ReturnFullUrlLocation(url);
  3550. var saveAndLoadFile = function (event) {
  3551. // the scene is not yet in the DB, let's try to save it
  3552. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3553. };
  3554. this._checkVersionFromDB(completeUrl, function (version) {
  3555. if (version !== -1) {
  3556. if (!_this.mustUpdateRessources) {
  3557. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3558. }
  3559. else {
  3560. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3561. }
  3562. }
  3563. else {
  3564. errorCallback();
  3565. }
  3566. });
  3567. };
  3568. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3569. if (this.isSupported) {
  3570. var targetStore;
  3571. if (url.indexOf(".babylon") !== -1) {
  3572. targetStore = "scenes";
  3573. }
  3574. else {
  3575. targetStore = "textures";
  3576. }
  3577. var file;
  3578. var transaction = this.db.transaction([targetStore]);
  3579. transaction.oncomplete = function (event) {
  3580. if (file) {
  3581. callback(file.data);
  3582. }
  3583. else {
  3584. notInDBCallback();
  3585. }
  3586. };
  3587. transaction.onabort = function (event) {
  3588. notInDBCallback();
  3589. };
  3590. var getRequest = transaction.objectStore(targetStore).get(url);
  3591. getRequest.onsuccess = function (event) {
  3592. file = (event.target).result;
  3593. };
  3594. getRequest.onerror = function (event) {
  3595. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3596. notInDBCallback();
  3597. };
  3598. }
  3599. else {
  3600. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3601. callback();
  3602. }
  3603. };
  3604. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3605. var _this = this;
  3606. if (this.isSupported) {
  3607. var targetStore;
  3608. if (url.indexOf(".babylon") !== -1) {
  3609. targetStore = "scenes";
  3610. }
  3611. else {
  3612. targetStore = "textures";
  3613. }
  3614. // Create XHR
  3615. var xhr = new XMLHttpRequest(), fileData;
  3616. xhr.open("GET", url, true);
  3617. if (useArrayBuffer) {
  3618. xhr.responseType = "arraybuffer";
  3619. }
  3620. xhr.onprogress = progressCallback;
  3621. xhr.addEventListener("load", function () {
  3622. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3623. // Blob as response (XHR2)
  3624. //fileData = xhr.responseText;
  3625. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3626. if (!_this.hasReachedQuota) {
  3627. // Open a transaction to the database
  3628. var transaction = _this.db.transaction([targetStore], "readwrite");
  3629. // the transaction could abort because of a QuotaExceededError error
  3630. transaction.onabort = function (event) {
  3631. try {
  3632. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3633. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3634. this.hasReachedQuota = true;
  3635. }
  3636. }
  3637. catch (ex) { }
  3638. callback(fileData);
  3639. };
  3640. transaction.oncomplete = function (event) {
  3641. callback(fileData);
  3642. };
  3643. var newFile;
  3644. if (targetStore === "scenes") {
  3645. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3646. }
  3647. else {
  3648. newFile = { textureUrl: url, data: fileData };
  3649. }
  3650. try {
  3651. // Put the scene into the database
  3652. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3653. addRequest.onsuccess = function (event) {
  3654. };
  3655. addRequest.onerror = function (event) {
  3656. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3657. };
  3658. }
  3659. catch (ex) {
  3660. callback(fileData);
  3661. }
  3662. }
  3663. else {
  3664. callback(fileData);
  3665. }
  3666. }
  3667. else {
  3668. callback();
  3669. }
  3670. }, false);
  3671. xhr.addEventListener("error", function (event) {
  3672. BABYLON.Tools.Error("error on XHR request.");
  3673. callback();
  3674. }, false);
  3675. xhr.send();
  3676. }
  3677. else {
  3678. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3679. callback();
  3680. }
  3681. };
  3682. Database.IsUASupportingBlobStorage = true;
  3683. Database.IDBStorageEnabled = true;
  3684. Database.parseURL = function (url) {
  3685. var a = document.createElement('a');
  3686. a.href = url;
  3687. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3688. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3689. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3690. return absLocation;
  3691. };
  3692. Database.ReturnFullUrlLocation = function (url) {
  3693. if (url.indexOf("http:/") === -1) {
  3694. return (Database.parseURL(window.location.href) + url);
  3695. }
  3696. else {
  3697. return url;
  3698. }
  3699. };
  3700. return Database;
  3701. })();
  3702. BABYLON.Database = Database;
  3703. })(BABYLON || (BABYLON = {}));
  3704. var BABYLON;
  3705. (function (BABYLON) {
  3706. var Internals;
  3707. (function (Internals) {
  3708. /*
  3709. * Based on jsTGALoader - Javascript loader for TGA file
  3710. * By Vincent Thibault
  3711. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3712. */
  3713. var TGATools = (function () {
  3714. function TGATools() {
  3715. }
  3716. TGATools.GetTGAHeader = function (data) {
  3717. var offset = 0;
  3718. var header = {
  3719. id_length: data[offset++],
  3720. colormap_type: data[offset++],
  3721. image_type: data[offset++],
  3722. colormap_index: data[offset++] | data[offset++] << 8,
  3723. colormap_length: data[offset++] | data[offset++] << 8,
  3724. colormap_size: data[offset++],
  3725. origin: [
  3726. data[offset++] | data[offset++] << 8,
  3727. data[offset++] | data[offset++] << 8
  3728. ],
  3729. width: data[offset++] | data[offset++] << 8,
  3730. height: data[offset++] | data[offset++] << 8,
  3731. pixel_size: data[offset++],
  3732. flags: data[offset++]
  3733. };
  3734. return header;
  3735. };
  3736. TGATools.UploadContent = function (gl, data) {
  3737. // Not enough data to contain header ?
  3738. if (data.length < 19) {
  3739. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3740. return;
  3741. }
  3742. // Read Header
  3743. var offset = 18;
  3744. var header = TGATools.GetTGAHeader(data);
  3745. // Assume it's a valid Targa file.
  3746. if (header.id_length + offset > data.length) {
  3747. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3748. return;
  3749. }
  3750. // Skip not needed data
  3751. offset += header.id_length;
  3752. var use_rle = false;
  3753. var use_pal = false;
  3754. var use_rgb = false;
  3755. var use_grey = false;
  3756. // Get some informations.
  3757. switch (header.image_type) {
  3758. case TGATools._TYPE_RLE_INDEXED:
  3759. use_rle = true;
  3760. case TGATools._TYPE_INDEXED:
  3761. use_pal = true;
  3762. break;
  3763. case TGATools._TYPE_RLE_RGB:
  3764. use_rle = true;
  3765. case TGATools._TYPE_RGB:
  3766. use_rgb = true;
  3767. break;
  3768. case TGATools._TYPE_RLE_GREY:
  3769. use_rle = true;
  3770. case TGATools._TYPE_GREY:
  3771. use_grey = true;
  3772. break;
  3773. }
  3774. var pixel_data;
  3775. var numAlphaBits = header.flags & 0xf;
  3776. var pixel_size = header.pixel_size >> 3;
  3777. var pixel_total = header.width * header.height * pixel_size;
  3778. // Read palettes
  3779. var palettes;
  3780. if (use_pal) {
  3781. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3782. }
  3783. // Read LRE
  3784. if (use_rle) {
  3785. pixel_data = new Uint8Array(pixel_total);
  3786. var c, count, i;
  3787. var localOffset = 0;
  3788. var pixels = new Uint8Array(pixel_size);
  3789. while (offset < pixel_total && localOffset < pixel_total) {
  3790. c = data[offset++];
  3791. count = (c & 0x7f) + 1;
  3792. // RLE pixels
  3793. if (c & 0x80) {
  3794. // Bind pixel tmp array
  3795. for (i = 0; i < pixel_size; ++i) {
  3796. pixels[i] = data[offset++];
  3797. }
  3798. // Copy pixel array
  3799. for (i = 0; i < count; ++i) {
  3800. pixel_data.set(pixels, localOffset + i * pixel_size);
  3801. }
  3802. localOffset += pixel_size * count;
  3803. }
  3804. else {
  3805. count *= pixel_size;
  3806. for (i = 0; i < count; ++i) {
  3807. pixel_data[localOffset + i] = data[offset++];
  3808. }
  3809. localOffset += count;
  3810. }
  3811. }
  3812. }
  3813. else {
  3814. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3815. }
  3816. // Load to texture
  3817. var x_start, y_start, x_step, y_step, y_end, x_end;
  3818. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3819. default:
  3820. case TGATools._ORIGIN_UL:
  3821. x_start = 0;
  3822. x_step = 1;
  3823. x_end = header.width;
  3824. y_start = 0;
  3825. y_step = 1;
  3826. y_end = header.height;
  3827. break;
  3828. case TGATools._ORIGIN_BL:
  3829. x_start = 0;
  3830. x_step = 1;
  3831. x_end = header.width;
  3832. y_start = header.height - 1;
  3833. y_step = -1;
  3834. y_end = -1;
  3835. break;
  3836. case TGATools._ORIGIN_UR:
  3837. x_start = header.width - 1;
  3838. x_step = -1;
  3839. x_end = -1;
  3840. y_start = 0;
  3841. y_step = 1;
  3842. y_end = header.height;
  3843. break;
  3844. case TGATools._ORIGIN_BR:
  3845. x_start = header.width - 1;
  3846. x_step = -1;
  3847. x_end = -1;
  3848. y_start = header.height - 1;
  3849. y_step = -1;
  3850. y_end = -1;
  3851. break;
  3852. }
  3853. // Load the specify method
  3854. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3855. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3856. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3857. };
  3858. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3859. var image = pixel_data, colormap = palettes;
  3860. var width = header.width, height = header.height;
  3861. var color, i = 0, x, y;
  3862. var imageData = new Uint8Array(width * height * 4);
  3863. for (y = y_start; y !== y_end; y += y_step) {
  3864. for (x = x_start; x !== x_end; x += x_step, i++) {
  3865. color = image[i];
  3866. imageData[(x + width * y) * 4 + 3] = 255;
  3867. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3868. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3869. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3870. }
  3871. }
  3872. return imageData;
  3873. };
  3874. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3875. var image = pixel_data;
  3876. var width = header.width, height = header.height;
  3877. var color, i = 0, x, y;
  3878. var imageData = new Uint8Array(width * height * 4);
  3879. for (y = y_start; y !== y_end; y += y_step) {
  3880. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3881. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3882. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3883. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3884. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3885. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3886. }
  3887. }
  3888. return imageData;
  3889. };
  3890. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3891. var image = pixel_data;
  3892. var width = header.width, height = header.height;
  3893. var i = 0, x, y;
  3894. var imageData = new Uint8Array(width * height * 4);
  3895. for (y = y_start; y !== y_end; y += y_step) {
  3896. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3897. imageData[(x + width * y) * 4 + 3] = 255;
  3898. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3899. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3900. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3901. }
  3902. }
  3903. return imageData;
  3904. };
  3905. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3906. var image = pixel_data;
  3907. var width = header.width, height = header.height;
  3908. var i = 0, x, y;
  3909. var imageData = new Uint8Array(width * height * 4);
  3910. for (y = y_start; y !== y_end; y += y_step) {
  3911. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3912. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3913. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3914. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3915. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3916. }
  3917. }
  3918. return imageData;
  3919. };
  3920. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3921. var image = pixel_data;
  3922. var width = header.width, height = header.height;
  3923. var color, i = 0, x, y;
  3924. var imageData = new Uint8Array(width * height * 4);
  3925. for (y = y_start; y !== y_end; y += y_step) {
  3926. for (x = x_start; x !== x_end; x += x_step, i++) {
  3927. color = image[i];
  3928. imageData[(x + width * y) * 4 + 0] = color;
  3929. imageData[(x + width * y) * 4 + 1] = color;
  3930. imageData[(x + width * y) * 4 + 2] = color;
  3931. imageData[(x + width * y) * 4 + 3] = 255;
  3932. }
  3933. }
  3934. return imageData;
  3935. };
  3936. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3937. var image = pixel_data;
  3938. var width = header.width, height = header.height;
  3939. var i = 0, x, y;
  3940. var imageData = new Uint8Array(width * height * 4);
  3941. for (y = y_start; y !== y_end; y += y_step) {
  3942. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3943. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3944. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3945. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3946. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3947. }
  3948. }
  3949. return imageData;
  3950. };
  3951. TGATools._TYPE_NO_DATA = 0;
  3952. TGATools._TYPE_INDEXED = 1;
  3953. TGATools._TYPE_RGB = 2;
  3954. TGATools._TYPE_GREY = 3;
  3955. TGATools._TYPE_RLE_INDEXED = 9;
  3956. TGATools._TYPE_RLE_RGB = 10;
  3957. TGATools._TYPE_RLE_GREY = 11;
  3958. TGATools._ORIGIN_MASK = 0x30;
  3959. TGATools._ORIGIN_SHIFT = 0x04;
  3960. TGATools._ORIGIN_BL = 0x00;
  3961. TGATools._ORIGIN_BR = 0x01;
  3962. TGATools._ORIGIN_UL = 0x02;
  3963. TGATools._ORIGIN_UR = 0x03;
  3964. return TGATools;
  3965. })();
  3966. Internals.TGATools = TGATools;
  3967. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3968. })(BABYLON || (BABYLON = {}));
  3969. var BABYLON;
  3970. (function (BABYLON) {
  3971. var SmartArray = (function () {
  3972. function SmartArray(capacity) {
  3973. this.length = 0;
  3974. this._duplicateId = 0;
  3975. this.data = new Array(capacity);
  3976. this._id = SmartArray._GlobalId++;
  3977. }
  3978. SmartArray.prototype.push = function (value) {
  3979. this.data[this.length++] = value;
  3980. if (this.length > this.data.length) {
  3981. this.data.length *= 2;
  3982. }
  3983. if (!value.__smartArrayFlags) {
  3984. value.__smartArrayFlags = {};
  3985. }
  3986. value.__smartArrayFlags[this._id] = this._duplicateId;
  3987. };
  3988. SmartArray.prototype.pushNoDuplicate = function (value) {
  3989. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3990. return;
  3991. }
  3992. this.push(value);
  3993. };
  3994. SmartArray.prototype.sort = function (compareFn) {
  3995. this.data.sort(compareFn);
  3996. };
  3997. SmartArray.prototype.reset = function () {
  3998. this.length = 0;
  3999. this._duplicateId++;
  4000. };
  4001. SmartArray.prototype.concat = function (array) {
  4002. if (array.length === 0) {
  4003. return;
  4004. }
  4005. if (this.length + array.length > this.data.length) {
  4006. this.data.length = (this.length + array.length) * 2;
  4007. }
  4008. for (var index = 0; index < array.length; index++) {
  4009. this.data[this.length++] = (array.data || array)[index];
  4010. }
  4011. };
  4012. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4013. if (array.length === 0) {
  4014. return;
  4015. }
  4016. if (this.length + array.length > this.data.length) {
  4017. this.data.length = (this.length + array.length) * 2;
  4018. }
  4019. for (var index = 0; index < array.length; index++) {
  4020. var item = (array.data || array)[index];
  4021. this.pushNoDuplicate(item);
  4022. }
  4023. };
  4024. SmartArray.prototype.indexOf = function (value) {
  4025. var position = this.data.indexOf(value);
  4026. if (position >= this.length) {
  4027. return -1;
  4028. }
  4029. return position;
  4030. };
  4031. // Statics
  4032. SmartArray._GlobalId = 0;
  4033. return SmartArray;
  4034. })();
  4035. BABYLON.SmartArray = SmartArray;
  4036. })(BABYLON || (BABYLON = {}));
  4037. var BABYLON;
  4038. (function (BABYLON) {
  4039. var SmartCollection = (function () {
  4040. function SmartCollection(capacity) {
  4041. if (capacity === void 0) { capacity = 10; }
  4042. this.count = 0;
  4043. this._initialCapacity = capacity;
  4044. this.items = {};
  4045. this._keys = new Array(this._initialCapacity);
  4046. }
  4047. SmartCollection.prototype.add = function (key, item) {
  4048. if (this.items[key] != undefined) {
  4049. return -1;
  4050. }
  4051. this.items[key] = item;
  4052. //literal keys are always strings, but we keep source type of key in _keys array
  4053. this._keys[this.count++] = key;
  4054. if (this.count > this._keys.length) {
  4055. this._keys.length *= 2;
  4056. }
  4057. return this.count;
  4058. };
  4059. SmartCollection.prototype.remove = function (key) {
  4060. if (this.items[key] == undefined) {
  4061. return -1;
  4062. }
  4063. return this.removeItemOfIndex(this.indexOf(key));
  4064. };
  4065. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4066. if (index < this.count && index > -1) {
  4067. delete this.items[this._keys[index]];
  4068. //here, shifting by hand is better optimised than .splice
  4069. while (index < this.count) {
  4070. this._keys[index] = this._keys[index + 1];
  4071. index++;
  4072. }
  4073. }
  4074. else {
  4075. return -1;
  4076. }
  4077. return --this.count;
  4078. };
  4079. SmartCollection.prototype.indexOf = function (key) {
  4080. for (var i = 0; i !== this.count; i++) {
  4081. if (this._keys[i] === key) {
  4082. return i;
  4083. }
  4084. }
  4085. return -1;
  4086. };
  4087. SmartCollection.prototype.item = function (key) {
  4088. return this.items[key];
  4089. };
  4090. SmartCollection.prototype.getAllKeys = function () {
  4091. if (this.count > 0) {
  4092. var keys = new Array(this.count);
  4093. for (var i = 0; i < this.count; i++) {
  4094. keys[i] = this._keys[i];
  4095. }
  4096. return keys;
  4097. }
  4098. else {
  4099. return undefined;
  4100. }
  4101. };
  4102. SmartCollection.prototype.getKeyByIndex = function (index) {
  4103. if (index < this.count && index > -1) {
  4104. return this._keys[index];
  4105. }
  4106. else {
  4107. return undefined;
  4108. }
  4109. };
  4110. SmartCollection.prototype.getItemByIndex = function (index) {
  4111. if (index < this.count && index > -1) {
  4112. return this.items[this._keys[index]];
  4113. }
  4114. else {
  4115. return undefined;
  4116. }
  4117. };
  4118. SmartCollection.prototype.empty = function () {
  4119. if (this.count > 0) {
  4120. this.count = 0;
  4121. this.items = {};
  4122. this._keys = new Array(this._initialCapacity);
  4123. }
  4124. };
  4125. SmartCollection.prototype.forEach = function (block) {
  4126. var key;
  4127. for (key in this.items) {
  4128. if (this.items.hasOwnProperty(key)) {
  4129. block(this.items[key]);
  4130. }
  4131. }
  4132. };
  4133. return SmartCollection;
  4134. })();
  4135. BABYLON.SmartCollection = SmartCollection;
  4136. })(BABYLON || (BABYLON = {}));
  4137. var BABYLON;
  4138. (function (BABYLON) {
  4139. // Screenshots
  4140. var screenshotCanvas;
  4141. var cloneValue = function (source, destinationObject) {
  4142. if (!source)
  4143. return null;
  4144. if (source instanceof BABYLON.Mesh) {
  4145. return null;
  4146. }
  4147. if (source instanceof BABYLON.SubMesh) {
  4148. return source.clone(destinationObject);
  4149. }
  4150. else if (source.clone) {
  4151. return source.clone();
  4152. }
  4153. return null;
  4154. };
  4155. var Tools = (function () {
  4156. function Tools() {
  4157. }
  4158. Tools.Instantiate = function (className) {
  4159. var arr = className.split(".");
  4160. var fn = (window || this);
  4161. for (var i = 0, len = arr.length; i < len; i++) {
  4162. fn = fn[arr[i]];
  4163. }
  4164. if (typeof fn !== "function") {
  4165. return null;
  4166. }
  4167. return fn;
  4168. };
  4169. Tools.SetImmediate = function (action) {
  4170. if (window.setImmediate) {
  4171. window.setImmediate(action);
  4172. }
  4173. else {
  4174. setTimeout(action, 1);
  4175. }
  4176. };
  4177. Tools.IsExponentOfTwo = function (value) {
  4178. var count = 1;
  4179. do {
  4180. count *= 2;
  4181. } while (count < value);
  4182. return count === value;
  4183. };
  4184. Tools.GetExponentOfTwo = function (value, max) {
  4185. var count = 1;
  4186. do {
  4187. count *= 2;
  4188. } while (count < value);
  4189. if (count > max)
  4190. count = max;
  4191. return count;
  4192. };
  4193. Tools.GetFilename = function (path) {
  4194. var index = path.lastIndexOf("/");
  4195. if (index < 0)
  4196. return path;
  4197. return path.substring(index + 1);
  4198. };
  4199. Tools.GetDOMTextContent = function (element) {
  4200. var result = "";
  4201. var child = element.firstChild;
  4202. while (child) {
  4203. if (child.nodeType === 3) {
  4204. result += child.textContent;
  4205. }
  4206. child = child.nextSibling;
  4207. }
  4208. return result;
  4209. };
  4210. Tools.ToDegrees = function (angle) {
  4211. return angle * 180 / Math.PI;
  4212. };
  4213. Tools.ToRadians = function (angle) {
  4214. return angle * Math.PI / 180;
  4215. };
  4216. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4217. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4218. var output = "";
  4219. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4220. var i = 0;
  4221. var bytes = new Uint8Array(buffer);
  4222. while (i < bytes.length) {
  4223. chr1 = bytes[i++];
  4224. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4225. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4226. enc1 = chr1 >> 2;
  4227. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4228. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4229. enc4 = chr3 & 63;
  4230. if (isNaN(chr2)) {
  4231. enc3 = enc4 = 64;
  4232. }
  4233. else if (isNaN(chr3)) {
  4234. enc4 = 64;
  4235. }
  4236. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4237. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4238. }
  4239. return "data:image/png;base64," + output;
  4240. };
  4241. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4242. if (bias === void 0) { bias = null; }
  4243. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4244. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4245. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4246. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4247. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4248. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4249. }
  4250. if (bias) {
  4251. minimum.x -= minimum.x * bias.x + bias.y;
  4252. minimum.y -= minimum.y * bias.x + bias.y;
  4253. minimum.z -= minimum.z * bias.x + bias.y;
  4254. maximum.x += maximum.x * bias.x + bias.y;
  4255. maximum.y += maximum.y * bias.x + bias.y;
  4256. maximum.z += maximum.z * bias.x + bias.y;
  4257. }
  4258. return {
  4259. minimum: minimum,
  4260. maximum: maximum
  4261. };
  4262. };
  4263. Tools.ExtractMinAndMax = function (positions, start, count, bias) {
  4264. if (bias === void 0) { bias = null; }
  4265. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4266. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4267. for (var index = start; index < start + count; index++) {
  4268. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4269. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4270. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4271. }
  4272. if (bias) {
  4273. minimum.x -= minimum.x * bias.x + bias.y;
  4274. minimum.y -= minimum.y * bias.x + bias.y;
  4275. minimum.z -= minimum.z * bias.x + bias.y;
  4276. maximum.x += maximum.x * bias.x + bias.y;
  4277. maximum.y += maximum.y * bias.x + bias.y;
  4278. maximum.z += maximum.z * bias.x + bias.y;
  4279. }
  4280. return {
  4281. minimum: minimum,
  4282. maximum: maximum
  4283. };
  4284. };
  4285. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4286. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4287. return undefined;
  4288. return Array.isArray(obj) ? obj : [obj];
  4289. };
  4290. // Misc.
  4291. Tools.GetPointerPrefix = function () {
  4292. var eventPrefix = "pointer";
  4293. // Check if pointer events are supported
  4294. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4295. eventPrefix = "mouse";
  4296. }
  4297. return eventPrefix;
  4298. };
  4299. Tools.QueueNewFrame = function (func) {
  4300. if (window.requestAnimationFrame)
  4301. window.requestAnimationFrame(func);
  4302. else if (window.msRequestAnimationFrame)
  4303. window.msRequestAnimationFrame(func);
  4304. else if (window.webkitRequestAnimationFrame)
  4305. window.webkitRequestAnimationFrame(func);
  4306. else if (window.mozRequestAnimationFrame)
  4307. window.mozRequestAnimationFrame(func);
  4308. else if (window.oRequestAnimationFrame)
  4309. window.oRequestAnimationFrame(func);
  4310. else {
  4311. window.setTimeout(func, 16);
  4312. }
  4313. };
  4314. Tools.RequestFullscreen = function (element) {
  4315. if (element.requestFullscreen)
  4316. element.requestFullscreen();
  4317. else if (element.msRequestFullscreen)
  4318. element.msRequestFullscreen();
  4319. else if (element.webkitRequestFullscreen)
  4320. element.webkitRequestFullscreen();
  4321. else if (element.mozRequestFullScreen)
  4322. element.mozRequestFullScreen();
  4323. };
  4324. Tools.ExitFullscreen = function () {
  4325. if (document.exitFullscreen) {
  4326. document.exitFullscreen();
  4327. }
  4328. else if (document.mozCancelFullScreen) {
  4329. document.mozCancelFullScreen();
  4330. }
  4331. else if (document.webkitCancelFullScreen) {
  4332. document.webkitCancelFullScreen();
  4333. }
  4334. else if (document.msCancelFullScreen) {
  4335. document.msCancelFullScreen();
  4336. }
  4337. };
  4338. // External files
  4339. Tools.CleanUrl = function (url) {
  4340. url = url.replace(/#/mg, "%23");
  4341. return url;
  4342. };
  4343. Tools.LoadImage = function (url, onload, onerror, database) {
  4344. if (url instanceof ArrayBuffer) {
  4345. url = Tools.EncodeArrayBufferTobase64(url);
  4346. }
  4347. url = Tools.CleanUrl(url);
  4348. var img = new Image();
  4349. if (url.substr(0, 5) !== "data:") {
  4350. if (Tools.CorsBehavior) {
  4351. switch (typeof (Tools.CorsBehavior)) {
  4352. case "function":
  4353. var result = Tools.CorsBehavior(url);
  4354. if (result) {
  4355. img.crossOrigin = result;
  4356. }
  4357. break;
  4358. case "string":
  4359. default:
  4360. img.crossOrigin = Tools.CorsBehavior;
  4361. break;
  4362. }
  4363. }
  4364. }
  4365. img.onload = function () {
  4366. onload(img);
  4367. };
  4368. img.onerror = function (err) {
  4369. Tools.Error("Error while trying to load texture: " + url);
  4370. if (Tools.UseFallbackTexture) {
  4371. 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";
  4372. onload(img);
  4373. }
  4374. else {
  4375. onerror();
  4376. }
  4377. };
  4378. var noIndexedDB = function () {
  4379. img.src = url;
  4380. };
  4381. var loadFromIndexedDB = function () {
  4382. database.loadImageFromDB(url, img);
  4383. };
  4384. //ANY database to do!
  4385. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4386. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4387. }
  4388. else {
  4389. if (url.indexOf("file:") === -1) {
  4390. noIndexedDB();
  4391. }
  4392. else {
  4393. try {
  4394. var textureName = url.substring(5);
  4395. var blobURL;
  4396. try {
  4397. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4398. }
  4399. catch (ex) {
  4400. // Chrome doesn't support oneTimeOnly parameter
  4401. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4402. }
  4403. img.src = blobURL;
  4404. }
  4405. catch (e) {
  4406. img.src = null;
  4407. }
  4408. }
  4409. }
  4410. return img;
  4411. };
  4412. //ANY
  4413. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4414. url = Tools.CleanUrl(url);
  4415. var noIndexedDB = function () {
  4416. var request = new XMLHttpRequest();
  4417. var loadUrl = Tools.BaseUrl + url;
  4418. request.open('GET', loadUrl, true);
  4419. if (useArrayBuffer) {
  4420. request.responseType = "arraybuffer";
  4421. }
  4422. request.onprogress = progressCallBack;
  4423. request.onreadystatechange = function () {
  4424. if (request.readyState === 4) {
  4425. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4426. callback(!useArrayBuffer ? request.responseText : request.response);
  4427. }
  4428. else {
  4429. if (onError) {
  4430. onError();
  4431. }
  4432. else {
  4433. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4434. }
  4435. }
  4436. }
  4437. };
  4438. request.send(null);
  4439. };
  4440. var loadFromIndexedDB = function () {
  4441. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4442. };
  4443. if (url.indexOf("file:") !== -1) {
  4444. var fileName = url.substring(5).toLowerCase();
  4445. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4446. }
  4447. else {
  4448. // Caching all files
  4449. if (database && database.enableSceneOffline) {
  4450. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4451. }
  4452. else {
  4453. noIndexedDB();
  4454. }
  4455. }
  4456. };
  4457. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4458. var reader = new FileReader();
  4459. reader.onload = function (e) {
  4460. //target doesn't have result from ts 1.3
  4461. callback(e.target['result']);
  4462. };
  4463. reader.onprogress = progressCallback;
  4464. reader.readAsDataURL(fileToLoad);
  4465. };
  4466. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4467. var reader = new FileReader();
  4468. reader.onerror = function (e) {
  4469. Tools.Log("Error while reading file: " + fileToLoad.name);
  4470. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4471. };
  4472. reader.onload = function (e) {
  4473. //target doesn't have result from ts 1.3
  4474. callback(e.target['result']);
  4475. };
  4476. reader.onprogress = progressCallBack;
  4477. if (!useArrayBuffer) {
  4478. // Asynchronous read
  4479. reader.readAsText(fileToLoad);
  4480. }
  4481. else {
  4482. reader.readAsArrayBuffer(fileToLoad);
  4483. }
  4484. };
  4485. //returns a downloadable url to a file content.
  4486. Tools.FileAsURL = function (content) {
  4487. var fileBlob = new Blob([content]);
  4488. var url = window.URL || window.webkitURL;
  4489. var link = url.createObjectURL(fileBlob);
  4490. return link;
  4491. };
  4492. // Misc.
  4493. Tools.Format = function (value, decimals) {
  4494. if (decimals === void 0) { decimals = 2; }
  4495. return value.toFixed(decimals);
  4496. };
  4497. Tools.CheckExtends = function (v, min, max) {
  4498. if (v.x < min.x)
  4499. min.x = v.x;
  4500. if (v.y < min.y)
  4501. min.y = v.y;
  4502. if (v.z < min.z)
  4503. min.z = v.z;
  4504. if (v.x > max.x)
  4505. max.x = v.x;
  4506. if (v.y > max.y)
  4507. max.y = v.y;
  4508. if (v.z > max.z)
  4509. max.z = v.z;
  4510. };
  4511. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4512. for (var prop in source) {
  4513. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4514. continue;
  4515. }
  4516. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4517. continue;
  4518. }
  4519. var sourceValue = source[prop];
  4520. var typeOfSourceValue = typeof sourceValue;
  4521. if (typeOfSourceValue === "function") {
  4522. continue;
  4523. }
  4524. if (typeOfSourceValue === "object") {
  4525. if (sourceValue instanceof Array) {
  4526. destination[prop] = [];
  4527. if (sourceValue.length > 0) {
  4528. if (typeof sourceValue[0] == "object") {
  4529. for (var index = 0; index < sourceValue.length; index++) {
  4530. var clonedValue = cloneValue(sourceValue[index], destination);
  4531. if (destination[prop].indexOf(clonedValue) === -1) {
  4532. destination[prop].push(clonedValue);
  4533. }
  4534. }
  4535. }
  4536. else {
  4537. destination[prop] = sourceValue.slice(0);
  4538. }
  4539. }
  4540. }
  4541. else {
  4542. destination[prop] = cloneValue(sourceValue, destination);
  4543. }
  4544. }
  4545. else {
  4546. destination[prop] = sourceValue;
  4547. }
  4548. }
  4549. };
  4550. Tools.IsEmpty = function (obj) {
  4551. for (var i in obj) {
  4552. return false;
  4553. }
  4554. return true;
  4555. };
  4556. Tools.RegisterTopRootEvents = function (events) {
  4557. for (var index = 0; index < events.length; index++) {
  4558. var event = events[index];
  4559. window.addEventListener(event.name, event.handler, false);
  4560. try {
  4561. if (window.parent) {
  4562. window.parent.addEventListener(event.name, event.handler, false);
  4563. }
  4564. }
  4565. catch (e) {
  4566. }
  4567. }
  4568. };
  4569. Tools.UnregisterTopRootEvents = function (events) {
  4570. for (var index = 0; index < events.length; index++) {
  4571. var event = events[index];
  4572. window.removeEventListener(event.name, event.handler);
  4573. try {
  4574. if (window.parent) {
  4575. window.parent.removeEventListener(event.name, event.handler);
  4576. }
  4577. }
  4578. catch (e) {
  4579. }
  4580. }
  4581. };
  4582. Tools.DumpFramebuffer = function (width, height, engine, successCallback) {
  4583. // Read the contents of the framebuffer
  4584. var numberOfChannelsByLine = width * 4;
  4585. var halfHeight = height / 2;
  4586. //Reading datas from WebGL
  4587. var data = engine.readPixels(0, 0, width, height);
  4588. //To flip image on Y axis.
  4589. for (var i = 0; i < halfHeight; i++) {
  4590. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4591. var currentCell = j + i * numberOfChannelsByLine;
  4592. var targetLine = height - i - 1;
  4593. var targetCell = j + targetLine * numberOfChannelsByLine;
  4594. var temp = data[currentCell];
  4595. data[currentCell] = data[targetCell];
  4596. data[targetCell] = temp;
  4597. }
  4598. }
  4599. // Create a 2D canvas to store the result
  4600. if (!screenshotCanvas) {
  4601. screenshotCanvas = document.createElement('canvas');
  4602. }
  4603. screenshotCanvas.width = width;
  4604. screenshotCanvas.height = height;
  4605. var context = screenshotCanvas.getContext('2d');
  4606. // Copy the pixels to a 2D canvas
  4607. var imageData = context.createImageData(width, height);
  4608. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4609. var castData = imageData.data;
  4610. castData.set(data);
  4611. context.putImageData(imageData, 0, 0);
  4612. var base64Image = screenshotCanvas.toDataURL();
  4613. if (successCallback) {
  4614. successCallback(base64Image);
  4615. }
  4616. else {
  4617. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4618. if (("download" in document.createElement("a"))) {
  4619. var a = window.document.createElement("a");
  4620. a.href = base64Image;
  4621. var date = new Date();
  4622. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  4623. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  4624. window.document.body.appendChild(a);
  4625. a.addEventListener("click", function () {
  4626. a.parentElement.removeChild(a);
  4627. });
  4628. a.click();
  4629. }
  4630. else {
  4631. var newWindow = window.open("");
  4632. var img = newWindow.document.createElement("img");
  4633. img.src = base64Image;
  4634. newWindow.document.body.appendChild(img);
  4635. }
  4636. }
  4637. };
  4638. Tools.CreateScreenshot = function (engine, camera, size, successCallback) {
  4639. var width;
  4640. var height;
  4641. //If a precision value is specified
  4642. if (size.precision) {
  4643. width = Math.round(engine.getRenderWidth() * size.precision);
  4644. height = Math.round(width / engine.getAspectRatio(camera));
  4645. size = { width: width, height: height };
  4646. }
  4647. else if (size.width && size.height) {
  4648. width = size.width;
  4649. height = size.height;
  4650. }
  4651. else if (size.width && !size.height) {
  4652. width = size.width;
  4653. height = Math.round(width / engine.getAspectRatio(camera));
  4654. size = { width: width, height: height };
  4655. }
  4656. else if (size.height && !size.width) {
  4657. height = size.height;
  4658. width = Math.round(height * engine.getAspectRatio(camera));
  4659. size = { width: width, height: height };
  4660. }
  4661. else if (!isNaN(size)) {
  4662. height = size;
  4663. width = size;
  4664. }
  4665. else {
  4666. Tools.Error("Invalid 'size' parameter !");
  4667. return;
  4668. }
  4669. var scene = camera.getScene();
  4670. var previousCamera = null;
  4671. if (scene.activeCamera !== camera) {
  4672. previousCamera = scene.activeCamera;
  4673. scene.activeCamera = camera;
  4674. }
  4675. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4676. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4677. texture.renderList = scene.meshes;
  4678. texture.onAfterRender = function () {
  4679. Tools.DumpFramebuffer(width, height, engine, successCallback);
  4680. };
  4681. scene.incrementRenderId();
  4682. texture.render(true);
  4683. texture.dispose();
  4684. if (previousCamera) {
  4685. scene.activeCamera = previousCamera;
  4686. }
  4687. camera.getProjectionMatrix(true); // Force cache refresh;
  4688. };
  4689. // XHR response validator for local file scenario
  4690. Tools.ValidateXHRData = function (xhr, dataType) {
  4691. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4692. if (dataType === void 0) { dataType = 7; }
  4693. try {
  4694. if (dataType & 1) {
  4695. if (xhr.responseText && xhr.responseText.length > 0) {
  4696. return true;
  4697. }
  4698. else if (dataType === 1) {
  4699. return false;
  4700. }
  4701. }
  4702. if (dataType & 2) {
  4703. // Check header width and height since there is no "TGA" magic number
  4704. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4705. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4706. return true;
  4707. }
  4708. else if (dataType === 2) {
  4709. return false;
  4710. }
  4711. }
  4712. if (dataType & 4) {
  4713. // Check for the "DDS" magic number
  4714. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4715. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4716. return true;
  4717. }
  4718. else {
  4719. return false;
  4720. }
  4721. }
  4722. }
  4723. catch (e) {
  4724. }
  4725. return false;
  4726. };
  4727. Object.defineProperty(Tools, "NoneLogLevel", {
  4728. get: function () {
  4729. return Tools._NoneLogLevel;
  4730. },
  4731. enumerable: true,
  4732. configurable: true
  4733. });
  4734. Object.defineProperty(Tools, "MessageLogLevel", {
  4735. get: function () {
  4736. return Tools._MessageLogLevel;
  4737. },
  4738. enumerable: true,
  4739. configurable: true
  4740. });
  4741. Object.defineProperty(Tools, "WarningLogLevel", {
  4742. get: function () {
  4743. return Tools._WarningLogLevel;
  4744. },
  4745. enumerable: true,
  4746. configurable: true
  4747. });
  4748. Object.defineProperty(Tools, "ErrorLogLevel", {
  4749. get: function () {
  4750. return Tools._ErrorLogLevel;
  4751. },
  4752. enumerable: true,
  4753. configurable: true
  4754. });
  4755. Object.defineProperty(Tools, "AllLogLevel", {
  4756. get: function () {
  4757. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4758. },
  4759. enumerable: true,
  4760. configurable: true
  4761. });
  4762. Tools._AddLogEntry = function (entry) {
  4763. Tools._LogCache = entry + Tools._LogCache;
  4764. if (Tools.OnNewCacheEntry) {
  4765. Tools.OnNewCacheEntry(entry);
  4766. }
  4767. };
  4768. Tools._FormatMessage = function (message) {
  4769. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4770. var date = new Date();
  4771. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4772. };
  4773. Tools._LogDisabled = function (message) {
  4774. // nothing to do
  4775. };
  4776. Tools._LogEnabled = function (message) {
  4777. var formattedMessage = Tools._FormatMessage(message);
  4778. console.log("BJS - " + formattedMessage);
  4779. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4780. Tools._AddLogEntry(entry);
  4781. };
  4782. Tools._WarnDisabled = function (message) {
  4783. // nothing to do
  4784. };
  4785. Tools._WarnEnabled = function (message) {
  4786. var formattedMessage = Tools._FormatMessage(message);
  4787. console.warn("BJS - " + formattedMessage);
  4788. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4789. Tools._AddLogEntry(entry);
  4790. };
  4791. Tools._ErrorDisabled = function (message) {
  4792. // nothing to do
  4793. };
  4794. Tools._ErrorEnabled = function (message) {
  4795. Tools.errorsCount++;
  4796. var formattedMessage = Tools._FormatMessage(message);
  4797. console.error("BJS - " + formattedMessage);
  4798. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4799. Tools._AddLogEntry(entry);
  4800. };
  4801. Object.defineProperty(Tools, "LogCache", {
  4802. get: function () {
  4803. return Tools._LogCache;
  4804. },
  4805. enumerable: true,
  4806. configurable: true
  4807. });
  4808. Tools.ClearLogCache = function () {
  4809. Tools._LogCache = "";
  4810. Tools.errorsCount = 0;
  4811. };
  4812. Object.defineProperty(Tools, "LogLevels", {
  4813. set: function (level) {
  4814. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4815. Tools.Log = Tools._LogEnabled;
  4816. }
  4817. else {
  4818. Tools.Log = Tools._LogDisabled;
  4819. }
  4820. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4821. Tools.Warn = Tools._WarnEnabled;
  4822. }
  4823. else {
  4824. Tools.Warn = Tools._WarnDisabled;
  4825. }
  4826. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4827. Tools.Error = Tools._ErrorEnabled;
  4828. }
  4829. else {
  4830. Tools.Error = Tools._ErrorDisabled;
  4831. }
  4832. },
  4833. enumerable: true,
  4834. configurable: true
  4835. });
  4836. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4837. get: function () {
  4838. return Tools._PerformanceNoneLogLevel;
  4839. },
  4840. enumerable: true,
  4841. configurable: true
  4842. });
  4843. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4844. get: function () {
  4845. return Tools._PerformanceUserMarkLogLevel;
  4846. },
  4847. enumerable: true,
  4848. configurable: true
  4849. });
  4850. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4851. get: function () {
  4852. return Tools._PerformanceConsoleLogLevel;
  4853. },
  4854. enumerable: true,
  4855. configurable: true
  4856. });
  4857. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4858. set: function (level) {
  4859. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4860. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4861. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4862. return;
  4863. }
  4864. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4865. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4866. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4867. return;
  4868. }
  4869. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4870. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4871. },
  4872. enumerable: true,
  4873. configurable: true
  4874. });
  4875. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4876. };
  4877. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4878. };
  4879. Tools._StartUserMark = function (counterName, condition) {
  4880. if (condition === void 0) { condition = true; }
  4881. if (!condition || !Tools._performance.mark) {
  4882. return;
  4883. }
  4884. Tools._performance.mark(counterName + "-Begin");
  4885. };
  4886. Tools._EndUserMark = function (counterName, condition) {
  4887. if (condition === void 0) { condition = true; }
  4888. if (!condition || !Tools._performance.mark) {
  4889. return;
  4890. }
  4891. Tools._performance.mark(counterName + "-End");
  4892. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4893. };
  4894. Tools._StartPerformanceConsole = function (counterName, condition) {
  4895. if (condition === void 0) { condition = true; }
  4896. if (!condition) {
  4897. return;
  4898. }
  4899. Tools._StartUserMark(counterName, condition);
  4900. if (console.time) {
  4901. console.time(counterName);
  4902. }
  4903. };
  4904. Tools._EndPerformanceConsole = function (counterName, condition) {
  4905. if (condition === void 0) { condition = true; }
  4906. if (!condition) {
  4907. return;
  4908. }
  4909. Tools._EndUserMark(counterName, condition);
  4910. if (console.time) {
  4911. console.timeEnd(counterName);
  4912. }
  4913. };
  4914. Object.defineProperty(Tools, "Now", {
  4915. get: function () {
  4916. if (window.performance && window.performance.now) {
  4917. return window.performance.now();
  4918. }
  4919. return new Date().getTime();
  4920. },
  4921. enumerable: true,
  4922. configurable: true
  4923. });
  4924. Tools.BaseUrl = "";
  4925. Tools.CorsBehavior = "anonymous";
  4926. Tools.UseFallbackTexture = true;
  4927. // Logs
  4928. Tools._NoneLogLevel = 0;
  4929. Tools._MessageLogLevel = 1;
  4930. Tools._WarningLogLevel = 2;
  4931. Tools._ErrorLogLevel = 4;
  4932. Tools._LogCache = "";
  4933. Tools.errorsCount = 0;
  4934. Tools.Log = Tools._LogEnabled;
  4935. Tools.Warn = Tools._WarnEnabled;
  4936. Tools.Error = Tools._ErrorEnabled;
  4937. // Performances
  4938. Tools._PerformanceNoneLogLevel = 0;
  4939. Tools._PerformanceUserMarkLogLevel = 1;
  4940. Tools._PerformanceConsoleLogLevel = 2;
  4941. Tools._performance = window.performance;
  4942. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4943. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4944. return Tools;
  4945. })();
  4946. BABYLON.Tools = Tools;
  4947. /**
  4948. * An implementation of a loop for asynchronous functions.
  4949. */
  4950. var AsyncLoop = (function () {
  4951. /**
  4952. * Constroctor.
  4953. * @param iterations the number of iterations.
  4954. * @param _fn the function to run each iteration
  4955. * @param _successCallback the callback that will be called upon succesful execution
  4956. * @param offset starting offset.
  4957. */
  4958. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4959. if (offset === void 0) { offset = 0; }
  4960. this.iterations = iterations;
  4961. this._fn = _fn;
  4962. this._successCallback = _successCallback;
  4963. this.index = offset - 1;
  4964. this._done = false;
  4965. }
  4966. /**
  4967. * Execute the next iteration. Must be called after the last iteration was finished.
  4968. */
  4969. AsyncLoop.prototype.executeNext = function () {
  4970. if (!this._done) {
  4971. if (this.index + 1 < this.iterations) {
  4972. ++this.index;
  4973. this._fn(this);
  4974. }
  4975. else {
  4976. this.breakLoop();
  4977. }
  4978. }
  4979. };
  4980. /**
  4981. * Break the loop and run the success callback.
  4982. */
  4983. AsyncLoop.prototype.breakLoop = function () {
  4984. this._done = true;
  4985. this._successCallback();
  4986. };
  4987. /**
  4988. * Helper function
  4989. */
  4990. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4991. if (offset === void 0) { offset = 0; }
  4992. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4993. loop.executeNext();
  4994. return loop;
  4995. };
  4996. /**
  4997. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4998. * @param iterations total number of iterations
  4999. * @param syncedIterations number of synchronous iterations in each async iteration.
  5000. * @param fn the function to call each iteration.
  5001. * @param callback a success call back that will be called when iterating stops.
  5002. * @param breakFunction a break condition (optional)
  5003. * @param timeout timeout settings for the setTimeout function. default - 0.
  5004. * @constructor
  5005. */
  5006. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5007. if (timeout === void 0) { timeout = 0; }
  5008. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5009. if (breakFunction && breakFunction())
  5010. loop.breakLoop();
  5011. else {
  5012. setTimeout(function () {
  5013. for (var i = 0; i < syncedIterations; ++i) {
  5014. var iteration = (loop.index * syncedIterations) + i;
  5015. if (iteration >= iterations)
  5016. break;
  5017. fn(iteration);
  5018. if (breakFunction && breakFunction()) {
  5019. loop.breakLoop();
  5020. break;
  5021. }
  5022. }
  5023. loop.executeNext();
  5024. }, timeout);
  5025. }
  5026. }, callback);
  5027. };
  5028. return AsyncLoop;
  5029. })();
  5030. BABYLON.AsyncLoop = AsyncLoop;
  5031. })(BABYLON || (BABYLON = {}));
  5032. var BABYLON;
  5033. (function (BABYLON) {
  5034. var Internals;
  5035. (function (Internals) {
  5036. var _AlphaState = (function () {
  5037. function _AlphaState() {
  5038. this._isAlphaBlendDirty = false;
  5039. this._isBlendFunctionParametersDirty = false;
  5040. this._alphaBlend = false;
  5041. this._blendFunctionParameters = new Array(4);
  5042. }
  5043. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5044. get: function () {
  5045. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5046. },
  5047. enumerable: true,
  5048. configurable: true
  5049. });
  5050. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5051. get: function () {
  5052. return this._alphaBlend;
  5053. },
  5054. set: function (value) {
  5055. if (this._alphaBlend === value) {
  5056. return;
  5057. }
  5058. this._alphaBlend = value;
  5059. this._isAlphaBlendDirty = true;
  5060. },
  5061. enumerable: true,
  5062. configurable: true
  5063. });
  5064. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5065. if (this._blendFunctionParameters[0] === value0 &&
  5066. this._blendFunctionParameters[1] === value1 &&
  5067. this._blendFunctionParameters[2] === value2 &&
  5068. this._blendFunctionParameters[3] === value3) {
  5069. return;
  5070. }
  5071. this._blendFunctionParameters[0] = value0;
  5072. this._blendFunctionParameters[1] = value1;
  5073. this._blendFunctionParameters[2] = value2;
  5074. this._blendFunctionParameters[3] = value3;
  5075. this._isBlendFunctionParametersDirty = true;
  5076. };
  5077. _AlphaState.prototype.reset = function () {
  5078. this._alphaBlend = false;
  5079. this._blendFunctionParameters[0] = null;
  5080. this._blendFunctionParameters[1] = null;
  5081. this._blendFunctionParameters[2] = null;
  5082. this._blendFunctionParameters[3] = null;
  5083. this._isAlphaBlendDirty = true;
  5084. this._isBlendFunctionParametersDirty = false;
  5085. };
  5086. _AlphaState.prototype.apply = function (gl) {
  5087. if (!this.isDirty) {
  5088. return;
  5089. }
  5090. // Alpha blend
  5091. if (this._isAlphaBlendDirty) {
  5092. if (this._alphaBlend) {
  5093. gl.enable(gl.BLEND);
  5094. }
  5095. else {
  5096. gl.disable(gl.BLEND);
  5097. }
  5098. this._isAlphaBlendDirty = false;
  5099. }
  5100. // Alpha function
  5101. if (this._isBlendFunctionParametersDirty) {
  5102. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5103. this._isBlendFunctionParametersDirty = false;
  5104. }
  5105. };
  5106. return _AlphaState;
  5107. })();
  5108. Internals._AlphaState = _AlphaState;
  5109. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5110. })(BABYLON || (BABYLON = {}));
  5111. var BABYLON;
  5112. (function (BABYLON) {
  5113. var Internals;
  5114. (function (Internals) {
  5115. var _DepthCullingState = (function () {
  5116. function _DepthCullingState() {
  5117. this._isDepthTestDirty = false;
  5118. this._isDepthMaskDirty = false;
  5119. this._isDepthFuncDirty = false;
  5120. this._isCullFaceDirty = false;
  5121. this._isCullDirty = false;
  5122. this._isZOffsetDirty = false;
  5123. }
  5124. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5125. get: function () {
  5126. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5127. },
  5128. enumerable: true,
  5129. configurable: true
  5130. });
  5131. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5132. get: function () {
  5133. return this._zOffset;
  5134. },
  5135. set: function (value) {
  5136. if (this._zOffset === value) {
  5137. return;
  5138. }
  5139. this._zOffset = value;
  5140. this._isZOffsetDirty = true;
  5141. },
  5142. enumerable: true,
  5143. configurable: true
  5144. });
  5145. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5146. get: function () {
  5147. return this._cullFace;
  5148. },
  5149. set: function (value) {
  5150. if (this._cullFace === value) {
  5151. return;
  5152. }
  5153. this._cullFace = value;
  5154. this._isCullFaceDirty = true;
  5155. },
  5156. enumerable: true,
  5157. configurable: true
  5158. });
  5159. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5160. get: function () {
  5161. return this._cull;
  5162. },
  5163. set: function (value) {
  5164. if (this._cull === value) {
  5165. return;
  5166. }
  5167. this._cull = value;
  5168. this._isCullDirty = true;
  5169. },
  5170. enumerable: true,
  5171. configurable: true
  5172. });
  5173. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5174. get: function () {
  5175. return this._depthFunc;
  5176. },
  5177. set: function (value) {
  5178. if (this._depthFunc === value) {
  5179. return;
  5180. }
  5181. this._depthFunc = value;
  5182. this._isDepthFuncDirty = true;
  5183. },
  5184. enumerable: true,
  5185. configurable: true
  5186. });
  5187. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5188. get: function () {
  5189. return this._depthMask;
  5190. },
  5191. set: function (value) {
  5192. if (this._depthMask === value) {
  5193. return;
  5194. }
  5195. this._depthMask = value;
  5196. this._isDepthMaskDirty = true;
  5197. },
  5198. enumerable: true,
  5199. configurable: true
  5200. });
  5201. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5202. get: function () {
  5203. return this._depthTest;
  5204. },
  5205. set: function (value) {
  5206. if (this._depthTest === value) {
  5207. return;
  5208. }
  5209. this._depthTest = value;
  5210. this._isDepthTestDirty = true;
  5211. },
  5212. enumerable: true,
  5213. configurable: true
  5214. });
  5215. _DepthCullingState.prototype.reset = function () {
  5216. this._depthMask = true;
  5217. this._depthTest = true;
  5218. this._depthFunc = null;
  5219. this._cull = null;
  5220. this._cullFace = null;
  5221. this._zOffset = 0;
  5222. this._isDepthTestDirty = true;
  5223. this._isDepthMaskDirty = true;
  5224. this._isDepthFuncDirty = false;
  5225. this._isCullFaceDirty = false;
  5226. this._isCullDirty = false;
  5227. this._isZOffsetDirty = false;
  5228. };
  5229. _DepthCullingState.prototype.apply = function (gl) {
  5230. if (!this.isDirty) {
  5231. return;
  5232. }
  5233. // Cull
  5234. if (this._isCullDirty) {
  5235. if (this.cull) {
  5236. gl.enable(gl.CULL_FACE);
  5237. }
  5238. else {
  5239. gl.disable(gl.CULL_FACE);
  5240. }
  5241. this._isCullDirty = false;
  5242. }
  5243. // Cull face
  5244. if (this._isCullFaceDirty) {
  5245. gl.cullFace(this.cullFace);
  5246. this._isCullFaceDirty = false;
  5247. }
  5248. // Depth mask
  5249. if (this._isDepthMaskDirty) {
  5250. gl.depthMask(this.depthMask);
  5251. this._isDepthMaskDirty = false;
  5252. }
  5253. // Depth test
  5254. if (this._isDepthTestDirty) {
  5255. if (this.depthTest) {
  5256. gl.enable(gl.DEPTH_TEST);
  5257. }
  5258. else {
  5259. gl.disable(gl.DEPTH_TEST);
  5260. }
  5261. this._isDepthTestDirty = false;
  5262. }
  5263. // Depth func
  5264. if (this._isDepthFuncDirty) {
  5265. gl.depthFunc(this.depthFunc);
  5266. this._isDepthFuncDirty = false;
  5267. }
  5268. // zOffset
  5269. if (this._isZOffsetDirty) {
  5270. if (this.zOffset) {
  5271. gl.enable(gl.POLYGON_OFFSET_FILL);
  5272. gl.polygonOffset(this.zOffset, 0);
  5273. }
  5274. else {
  5275. gl.disable(gl.POLYGON_OFFSET_FILL);
  5276. }
  5277. this._isZOffsetDirty = false;
  5278. }
  5279. };
  5280. return _DepthCullingState;
  5281. })();
  5282. Internals._DepthCullingState = _DepthCullingState;
  5283. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5284. })(BABYLON || (BABYLON = {}));
  5285. var BABYLON;
  5286. (function (BABYLON) {
  5287. var compileShader = function (gl, source, type, defines) {
  5288. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5289. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5290. gl.compileShader(shader);
  5291. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5292. throw new Error(gl.getShaderInfoLog(shader));
  5293. }
  5294. return shader;
  5295. };
  5296. var getWebGLTextureType = function (gl, type) {
  5297. var textureType = gl.UNSIGNED_BYTE;
  5298. if (type === Engine.TEXTURETYPE_FLOAT)
  5299. textureType = gl.FLOAT;
  5300. return textureType;
  5301. };
  5302. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5303. var magFilter = gl.NEAREST;
  5304. var minFilter = gl.NEAREST;
  5305. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5306. magFilter = gl.LINEAR;
  5307. if (generateMipMaps) {
  5308. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5309. }
  5310. else {
  5311. minFilter = gl.LINEAR;
  5312. }
  5313. }
  5314. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5315. magFilter = gl.LINEAR;
  5316. if (generateMipMaps) {
  5317. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5318. }
  5319. else {
  5320. minFilter = gl.LINEAR;
  5321. }
  5322. }
  5323. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5324. magFilter = gl.NEAREST;
  5325. if (generateMipMaps) {
  5326. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5327. }
  5328. else {
  5329. minFilter = gl.NEAREST;
  5330. }
  5331. }
  5332. return {
  5333. min: minFilter,
  5334. mag: magFilter
  5335. };
  5336. };
  5337. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, onLoad, samplingMode) {
  5338. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5339. var engine = scene.getEngine();
  5340. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  5341. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  5342. gl.bindTexture(gl.TEXTURE_2D, texture);
  5343. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5344. texture._baseWidth = width;
  5345. texture._baseHeight = height;
  5346. texture._width = potWidth;
  5347. texture._height = potHeight;
  5348. texture.isReady = true;
  5349. processFunction(potWidth, potHeight);
  5350. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5351. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5352. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5353. if (!noMipmap && !isCompressed) {
  5354. gl.generateMipmap(gl.TEXTURE_2D);
  5355. }
  5356. gl.bindTexture(gl.TEXTURE_2D, null);
  5357. engine.resetTextureCache();
  5358. scene._removePendingData(texture);
  5359. if (onLoad) {
  5360. onLoad();
  5361. }
  5362. };
  5363. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5364. var img;
  5365. var onload = function () {
  5366. loadedImages[index] = img;
  5367. loadedImages._internalCount++;
  5368. scene._removePendingData(img);
  5369. if (loadedImages._internalCount === 6) {
  5370. onfinish(loadedImages);
  5371. }
  5372. };
  5373. var onerror = function () {
  5374. scene._removePendingData(img);
  5375. };
  5376. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5377. scene._addPendingData(img);
  5378. };
  5379. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  5380. var loadedImages = [];
  5381. loadedImages._internalCount = 0;
  5382. for (var index = 0; index < 6; index++) {
  5383. partialLoad(files[index], index, loadedImages, scene, onfinish);
  5384. }
  5385. };
  5386. var EngineCapabilities = (function () {
  5387. function EngineCapabilities() {
  5388. }
  5389. return EngineCapabilities;
  5390. })();
  5391. BABYLON.EngineCapabilities = EngineCapabilities;
  5392. /**
  5393. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5394. */
  5395. var Engine = (function () {
  5396. /**
  5397. * @constructor
  5398. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5399. * @param {boolean} [antialias] - enable antialias
  5400. * @param options - further options to be sent to the getContext function
  5401. */
  5402. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  5403. var _this = this;
  5404. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  5405. // Public members
  5406. this.isFullscreen = false;
  5407. this.isPointerLock = false;
  5408. this.cullBackFaces = true;
  5409. this.renderEvenInBackground = true;
  5410. // To enable/disable IDB support and avoid XHR on .manifest
  5411. this.enableOfflineSupport = true;
  5412. this.scenes = new Array();
  5413. this._windowIsBackground = false;
  5414. this._webGLVersion = "1.0";
  5415. this._drawCalls = 0;
  5416. this._renderingQueueLaunched = false;
  5417. this._activeRenderLoops = [];
  5418. // FPS
  5419. this.fpsRange = 60;
  5420. this.previousFramesDuration = [];
  5421. this.fps = 60;
  5422. this.deltaTime = 0;
  5423. // States
  5424. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  5425. this._alphaState = new BABYLON.Internals._AlphaState();
  5426. this._alphaMode = Engine.ALPHA_DISABLE;
  5427. // Cache
  5428. this._loadedTexturesCache = new Array();
  5429. this._maxTextureChannels = 16;
  5430. this._activeTexturesCache = new Array(this._maxTextureChannels);
  5431. this._compiledEffects = {};
  5432. this._uintIndicesCurrentlySet = false;
  5433. this._renderingCanvas = canvas;
  5434. options = options || {};
  5435. options.antialias = antialias;
  5436. if (options.preserveDrawingBuffer === undefined) {
  5437. options.preserveDrawingBuffer = false;
  5438. }
  5439. // GL
  5440. //try {
  5441. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  5442. // if (this._gl) {
  5443. // this._webGLVersion = "2.0";
  5444. // }
  5445. //} catch (e) {
  5446. // // Do nothing
  5447. //}
  5448. if (!this._gl) {
  5449. try {
  5450. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  5451. }
  5452. catch (e) {
  5453. throw new Error("WebGL not supported");
  5454. }
  5455. }
  5456. if (!this._gl) {
  5457. throw new Error("WebGL not supported");
  5458. }
  5459. this._onBlur = function () {
  5460. _this._windowIsBackground = true;
  5461. };
  5462. this._onFocus = function () {
  5463. _this._windowIsBackground = false;
  5464. };
  5465. window.addEventListener("blur", this._onBlur);
  5466. window.addEventListener("focus", this._onFocus);
  5467. // Viewport
  5468. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  5469. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  5470. this.resize();
  5471. // Caps
  5472. this._caps = new EngineCapabilities();
  5473. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5474. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5475. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5476. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5477. // Infos
  5478. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5479. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5480. if (rendererInfo != null) {
  5481. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5482. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5483. }
  5484. if (!this._glVendor) {
  5485. this._glVendor = "Unknown vendor";
  5486. }
  5487. if (!this._glRenderer) {
  5488. this._glRenderer = "Unknown renderer";
  5489. }
  5490. // Extensions
  5491. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5492. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5493. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5494. 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');
  5495. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5496. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5497. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5498. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  5499. this._caps.highPrecisionShaderSupported = true;
  5500. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  5501. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  5502. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  5503. if (this._gl.getShaderPrecisionFormat) {
  5504. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5505. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  5506. }
  5507. // Depth buffer
  5508. this.setDepthBuffer(true);
  5509. this.setDepthFunctionToLessOrEqual();
  5510. this.setDepthWrite(true);
  5511. // Fullscreen
  5512. this._onFullscreenChange = function () {
  5513. if (document.fullscreen !== undefined) {
  5514. _this.isFullscreen = document.fullscreen;
  5515. }
  5516. else if (document.mozFullScreen !== undefined) {
  5517. _this.isFullscreen = document.mozFullScreen;
  5518. }
  5519. else if (document.webkitIsFullScreen !== undefined) {
  5520. _this.isFullscreen = document.webkitIsFullScreen;
  5521. }
  5522. else if (document.msIsFullScreen !== undefined) {
  5523. _this.isFullscreen = document.msIsFullScreen;
  5524. }
  5525. // Pointer lock
  5526. if (_this.isFullscreen && _this._pointerLockRequested) {
  5527. canvas.requestPointerLock = canvas.requestPointerLock ||
  5528. canvas.msRequestPointerLock ||
  5529. canvas.mozRequestPointerLock ||
  5530. canvas.webkitRequestPointerLock;
  5531. if (canvas.requestPointerLock) {
  5532. canvas.requestPointerLock();
  5533. }
  5534. }
  5535. };
  5536. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5537. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5538. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5539. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5540. // Pointer lock
  5541. this._onPointerLockChange = function () {
  5542. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5543. document.webkitPointerLockElement === canvas ||
  5544. document.msPointerLockElement === canvas ||
  5545. document.pointerLockElement === canvas);
  5546. };
  5547. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5548. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5549. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5550. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5551. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  5552. Engine.audioEngine = new BABYLON.AudioEngine();
  5553. }
  5554. //default loading screen
  5555. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  5556. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5557. }
  5558. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5559. get: function () {
  5560. return Engine._ALPHA_DISABLE;
  5561. },
  5562. enumerable: true,
  5563. configurable: true
  5564. });
  5565. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  5566. get: function () {
  5567. return Engine._ALPHA_ONEONE;
  5568. },
  5569. enumerable: true,
  5570. configurable: true
  5571. });
  5572. Object.defineProperty(Engine, "ALPHA_ADD", {
  5573. get: function () {
  5574. return Engine._ALPHA_ADD;
  5575. },
  5576. enumerable: true,
  5577. configurable: true
  5578. });
  5579. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5580. get: function () {
  5581. return Engine._ALPHA_COMBINE;
  5582. },
  5583. enumerable: true,
  5584. configurable: true
  5585. });
  5586. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  5587. get: function () {
  5588. return Engine._ALPHA_SUBTRACT;
  5589. },
  5590. enumerable: true,
  5591. configurable: true
  5592. });
  5593. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  5594. get: function () {
  5595. return Engine._ALPHA_MULTIPLY;
  5596. },
  5597. enumerable: true,
  5598. configurable: true
  5599. });
  5600. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  5601. get: function () {
  5602. return Engine._ALPHA_MAXIMIZED;
  5603. },
  5604. enumerable: true,
  5605. configurable: true
  5606. });
  5607. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5608. get: function () {
  5609. return Engine._DELAYLOADSTATE_NONE;
  5610. },
  5611. enumerable: true,
  5612. configurable: true
  5613. });
  5614. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5615. get: function () {
  5616. return Engine._DELAYLOADSTATE_LOADED;
  5617. },
  5618. enumerable: true,
  5619. configurable: true
  5620. });
  5621. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5622. get: function () {
  5623. return Engine._DELAYLOADSTATE_LOADING;
  5624. },
  5625. enumerable: true,
  5626. configurable: true
  5627. });
  5628. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5629. get: function () {
  5630. return Engine._DELAYLOADSTATE_NOTLOADED;
  5631. },
  5632. enumerable: true,
  5633. configurable: true
  5634. });
  5635. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5636. get: function () {
  5637. return Engine._TEXTUREFORMAT_ALPHA;
  5638. },
  5639. enumerable: true,
  5640. configurable: true
  5641. });
  5642. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5643. get: function () {
  5644. return Engine._TEXTUREFORMAT_LUMINANCE;
  5645. },
  5646. enumerable: true,
  5647. configurable: true
  5648. });
  5649. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5650. get: function () {
  5651. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5652. },
  5653. enumerable: true,
  5654. configurable: true
  5655. });
  5656. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5657. get: function () {
  5658. return Engine._TEXTUREFORMAT_RGB;
  5659. },
  5660. enumerable: true,
  5661. configurable: true
  5662. });
  5663. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5664. get: function () {
  5665. return Engine._TEXTUREFORMAT_RGBA;
  5666. },
  5667. enumerable: true,
  5668. configurable: true
  5669. });
  5670. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5671. get: function () {
  5672. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5673. },
  5674. enumerable: true,
  5675. configurable: true
  5676. });
  5677. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5678. get: function () {
  5679. return Engine._TEXTURETYPE_FLOAT;
  5680. },
  5681. enumerable: true,
  5682. configurable: true
  5683. });
  5684. Object.defineProperty(Engine, "Version", {
  5685. get: function () {
  5686. return "2.4.0-alpha";
  5687. },
  5688. enumerable: true,
  5689. configurable: true
  5690. });
  5691. Object.defineProperty(Engine.prototype, "webGLVersion", {
  5692. get: function () {
  5693. return this._webGLVersion;
  5694. },
  5695. enumerable: true,
  5696. configurable: true
  5697. });
  5698. Engine.prototype._prepareWorkingCanvas = function () {
  5699. if (this._workingCanvas) {
  5700. return;
  5701. }
  5702. this._workingCanvas = document.createElement("canvas");
  5703. this._workingContext = this._workingCanvas.getContext("2d");
  5704. };
  5705. Engine.prototype.resetTextureCache = function () {
  5706. for (var index = 0; index < this._maxTextureChannels; index++) {
  5707. this._activeTexturesCache[index] = null;
  5708. }
  5709. };
  5710. Engine.prototype.getGlInfo = function () {
  5711. return {
  5712. vendor: this._glVendor,
  5713. renderer: this._glRenderer,
  5714. version: this._glVersion
  5715. };
  5716. };
  5717. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  5718. if (useScreen === void 0) { useScreen = false; }
  5719. var viewport = camera.viewport;
  5720. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  5721. };
  5722. Engine.prototype.getRenderWidth = function (useScreen) {
  5723. if (useScreen === void 0) { useScreen = false; }
  5724. if (!useScreen && this._currentRenderTarget) {
  5725. return this._currentRenderTarget._width;
  5726. }
  5727. return this._renderingCanvas.width;
  5728. };
  5729. Engine.prototype.getRenderHeight = function (useScreen) {
  5730. if (useScreen === void 0) { useScreen = false; }
  5731. if (!useScreen && this._currentRenderTarget) {
  5732. return this._currentRenderTarget._height;
  5733. }
  5734. return this._renderingCanvas.height;
  5735. };
  5736. Engine.prototype.getRenderingCanvas = function () {
  5737. return this._renderingCanvas;
  5738. };
  5739. Engine.prototype.getRenderingCanvasClientRect = function () {
  5740. return this._renderingCanvas.getBoundingClientRect();
  5741. };
  5742. Engine.prototype.setHardwareScalingLevel = function (level) {
  5743. this._hardwareScalingLevel = level;
  5744. this.resize();
  5745. };
  5746. Engine.prototype.getHardwareScalingLevel = function () {
  5747. return this._hardwareScalingLevel;
  5748. };
  5749. Engine.prototype.getLoadedTexturesCache = function () {
  5750. return this._loadedTexturesCache;
  5751. };
  5752. Engine.prototype.getCaps = function () {
  5753. return this._caps;
  5754. };
  5755. Object.defineProperty(Engine.prototype, "drawCalls", {
  5756. get: function () {
  5757. return this._drawCalls;
  5758. },
  5759. enumerable: true,
  5760. configurable: true
  5761. });
  5762. // Methods
  5763. Engine.prototype.resetDrawCalls = function () {
  5764. this._drawCalls = 0;
  5765. };
  5766. Engine.prototype.setDepthFunctionToGreater = function () {
  5767. this._depthCullingState.depthFunc = this._gl.GREATER;
  5768. };
  5769. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5770. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5771. };
  5772. Engine.prototype.setDepthFunctionToLess = function () {
  5773. this._depthCullingState.depthFunc = this._gl.LESS;
  5774. };
  5775. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5776. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5777. };
  5778. /**
  5779. * stop executing a render loop function and remove it from the execution array
  5780. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5781. */
  5782. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5783. if (!renderFunction) {
  5784. this._activeRenderLoops = [];
  5785. return;
  5786. }
  5787. var index = this._activeRenderLoops.indexOf(renderFunction);
  5788. if (index >= 0) {
  5789. this._activeRenderLoops.splice(index, 1);
  5790. }
  5791. };
  5792. Engine.prototype._renderLoop = function () {
  5793. var shouldRender = true;
  5794. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5795. shouldRender = false;
  5796. }
  5797. if (shouldRender) {
  5798. // Start new frame
  5799. this.beginFrame();
  5800. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5801. var renderFunction = this._activeRenderLoops[index];
  5802. renderFunction();
  5803. }
  5804. // Present
  5805. this.endFrame();
  5806. }
  5807. if (this._activeRenderLoops.length > 0) {
  5808. // Register new frame
  5809. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5810. }
  5811. else {
  5812. this._renderingQueueLaunched = false;
  5813. }
  5814. };
  5815. /**
  5816. * Register and execute a render loop. The engine can have more than one render function.
  5817. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5818. * @example
  5819. * engine.runRenderLoop(function () {
  5820. * scene.render()
  5821. * })
  5822. */
  5823. Engine.prototype.runRenderLoop = function (renderFunction) {
  5824. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5825. return;
  5826. }
  5827. this._activeRenderLoops.push(renderFunction);
  5828. if (!this._renderingQueueLaunched) {
  5829. this._renderingQueueLaunched = true;
  5830. this._bindedRenderFunction = this._renderLoop.bind(this);
  5831. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  5832. }
  5833. };
  5834. /**
  5835. * Toggle full screen mode.
  5836. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5837. */
  5838. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5839. if (this.isFullscreen) {
  5840. BABYLON.Tools.ExitFullscreen();
  5841. }
  5842. else {
  5843. this._pointerLockRequested = requestPointerLock;
  5844. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5845. }
  5846. };
  5847. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5848. this.applyStates();
  5849. if (backBuffer) {
  5850. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5851. }
  5852. if (depthStencil && this._depthCullingState.depthMask) {
  5853. this._gl.clearDepth(1.0);
  5854. }
  5855. var mode = 0;
  5856. if (backBuffer) {
  5857. mode |= this._gl.COLOR_BUFFER_BIT;
  5858. }
  5859. if (depthStencil && this._depthCullingState.depthMask) {
  5860. mode |= this._gl.DEPTH_BUFFER_BIT;
  5861. }
  5862. this._gl.clear(mode);
  5863. };
  5864. /**
  5865. * Set the WebGL's viewport
  5866. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5867. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5868. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5869. */
  5870. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5871. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5872. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5873. var x = viewport.x || 0;
  5874. var y = viewport.y || 0;
  5875. this._cachedViewport = viewport;
  5876. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5877. };
  5878. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5879. this._cachedViewport = null;
  5880. this._gl.viewport(x, y, width, height);
  5881. };
  5882. Engine.prototype.beginFrame = function () {
  5883. this._measureFps();
  5884. };
  5885. Engine.prototype.endFrame = function () {
  5886. //this.flushFramebuffer();
  5887. };
  5888. /**
  5889. * resize the view according to the canvas' size.
  5890. * @example
  5891. * window.addEventListener("resize", function () {
  5892. * engine.resize();
  5893. * });
  5894. */
  5895. Engine.prototype.resize = function () {
  5896. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5897. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5898. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5899. for (var index = 0; index < this.scenes.length; index++) {
  5900. var scene = this.scenes[index];
  5901. if (scene.debugLayer.isVisible()) {
  5902. scene.debugLayer._syncPositions();
  5903. }
  5904. }
  5905. };
  5906. /**
  5907. * force a specific size of the canvas
  5908. * @param {number} width - the new canvas' width
  5909. * @param {number} height - the new canvas' height
  5910. */
  5911. Engine.prototype.setSize = function (width, height) {
  5912. this._renderingCanvas.width = width;
  5913. this._renderingCanvas.height = height;
  5914. for (var index = 0; index < this.scenes.length; index++) {
  5915. var scene = this.scenes[index];
  5916. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5917. var cam = scene.cameras[camIndex];
  5918. cam._currentRenderId = 0;
  5919. }
  5920. }
  5921. };
  5922. Engine.prototype.bindFramebuffer = function (texture, faceIndex) {
  5923. this._currentRenderTarget = texture;
  5924. var gl = this._gl;
  5925. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5926. if (texture.isCube) {
  5927. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  5928. }
  5929. else {
  5930. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5931. }
  5932. this._gl.viewport(0, 0, texture._width, texture._height);
  5933. this.wipeCaches();
  5934. };
  5935. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  5936. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  5937. this._currentRenderTarget = null;
  5938. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  5939. var gl = this._gl;
  5940. gl.bindTexture(gl.TEXTURE_2D, texture);
  5941. gl.generateMipmap(gl.TEXTURE_2D);
  5942. gl.bindTexture(gl.TEXTURE_2D, null);
  5943. }
  5944. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5945. };
  5946. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  5947. if (texture.generateMipMaps) {
  5948. var gl = this._gl;
  5949. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5950. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5951. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5952. }
  5953. };
  5954. Engine.prototype.flushFramebuffer = function () {
  5955. this._gl.flush();
  5956. };
  5957. Engine.prototype.restoreDefaultFramebuffer = function () {
  5958. this._currentRenderTarget = null;
  5959. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5960. this.setViewport(this._cachedViewport);
  5961. this.wipeCaches();
  5962. };
  5963. // VBOs
  5964. Engine.prototype._resetVertexBufferBinding = function () {
  5965. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5966. this._cachedVertexBuffers = null;
  5967. };
  5968. Engine.prototype.createVertexBuffer = function (vertices) {
  5969. var vbo = this._gl.createBuffer();
  5970. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5971. if (vertices instanceof Float32Array) {
  5972. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  5973. }
  5974. else {
  5975. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5976. }
  5977. this._resetVertexBufferBinding();
  5978. vbo.references = 1;
  5979. return vbo;
  5980. };
  5981. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5982. var vbo = this._gl.createBuffer();
  5983. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5984. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5985. this._resetVertexBufferBinding();
  5986. vbo.references = 1;
  5987. return vbo;
  5988. };
  5989. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5990. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5991. if (offset === undefined) {
  5992. offset = 0;
  5993. }
  5994. if (vertices instanceof Float32Array) {
  5995. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5996. }
  5997. else {
  5998. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5999. }
  6000. this._resetVertexBufferBinding();
  6001. };
  6002. Engine.prototype._resetIndexBufferBinding = function () {
  6003. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  6004. this._cachedIndexBuffer = null;
  6005. };
  6006. Engine.prototype.createIndexBuffer = function (indices) {
  6007. var vbo = this._gl.createBuffer();
  6008. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  6009. // Check for 32 bits indices
  6010. var arrayBuffer;
  6011. var need32Bits = false;
  6012. if (this._caps.uintIndices) {
  6013. for (var index = 0; index < indices.length; index++) {
  6014. if (indices[index] > 65535) {
  6015. need32Bits = true;
  6016. break;
  6017. }
  6018. }
  6019. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  6020. }
  6021. else {
  6022. arrayBuffer = new Uint16Array(indices);
  6023. }
  6024. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  6025. this._resetIndexBufferBinding();
  6026. vbo.references = 1;
  6027. vbo.is32Bits = need32Bits;
  6028. return vbo;
  6029. };
  6030. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  6031. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  6032. this._cachedVertexBuffers = vertexBuffer;
  6033. this._cachedEffectForVertexBuffers = effect;
  6034. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  6035. var offset = 0;
  6036. for (var index = 0; index < vertexDeclaration.length; index++) {
  6037. var order = effect.getAttributeLocation(index);
  6038. if (order >= 0) {
  6039. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  6040. }
  6041. offset += vertexDeclaration[index] * 4;
  6042. }
  6043. }
  6044. if (this._cachedIndexBuffer !== indexBuffer) {
  6045. this._cachedIndexBuffer = indexBuffer;
  6046. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  6047. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  6048. }
  6049. };
  6050. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  6051. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  6052. this._cachedVertexBuffers = vertexBuffers;
  6053. this._cachedEffectForVertexBuffers = effect;
  6054. var attributes = effect.getAttributesNames();
  6055. for (var index = 0; index < attributes.length; index++) {
  6056. var order = effect.getAttributeLocation(index);
  6057. if (order >= 0) {
  6058. var vertexBuffer = vertexBuffers[attributes[index]];
  6059. if (!vertexBuffer) {
  6060. continue;
  6061. }
  6062. var stride = vertexBuffer.getStrideSize();
  6063. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  6064. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  6065. }
  6066. }
  6067. }
  6068. if (indexBuffer != null && 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._releaseBuffer = function (buffer) {
  6075. buffer.references--;
  6076. if (buffer.references === 0) {
  6077. this._gl.deleteBuffer(buffer);
  6078. return true;
  6079. }
  6080. return false;
  6081. };
  6082. Engine.prototype.createInstancesBuffer = function (capacity) {
  6083. var buffer = this._gl.createBuffer();
  6084. buffer.capacity = capacity;
  6085. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  6086. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  6087. return buffer;
  6088. };
  6089. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  6090. this._gl.deleteBuffer(buffer);
  6091. };
  6092. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  6093. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6094. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  6095. for (var index = 0; index < 4; index++) {
  6096. var offsetLocation = offsetLocations[index];
  6097. this._gl.enableVertexAttribArray(offsetLocation);
  6098. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  6099. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  6100. }
  6101. };
  6102. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  6103. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  6104. for (var index = 0; index < 4; index++) {
  6105. var offsetLocation = offsetLocations[index];
  6106. this._gl.disableVertexAttribArray(offsetLocation);
  6107. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  6108. }
  6109. };
  6110. Engine.prototype.applyStates = function () {
  6111. this._depthCullingState.apply(this._gl);
  6112. this._alphaState.apply(this._gl);
  6113. };
  6114. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  6115. // Apply states
  6116. this.applyStates();
  6117. this._drawCalls++;
  6118. // Render
  6119. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  6120. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  6121. if (instancesCount) {
  6122. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  6123. return;
  6124. }
  6125. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  6126. };
  6127. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  6128. // Apply states
  6129. this.applyStates();
  6130. this._drawCalls++;
  6131. if (instancesCount) {
  6132. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  6133. return;
  6134. }
  6135. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  6136. };
  6137. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  6138. // Apply states
  6139. this.applyStates();
  6140. this._drawCalls++;
  6141. if (instancesCount) {
  6142. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  6143. return;
  6144. }
  6145. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  6146. };
  6147. // Shaders
  6148. Engine.prototype._releaseEffect = function (effect) {
  6149. if (this._compiledEffects[effect._key]) {
  6150. delete this._compiledEffects[effect._key];
  6151. if (effect.getProgram()) {
  6152. this._gl.deleteProgram(effect.getProgram());
  6153. }
  6154. }
  6155. };
  6156. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6157. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  6158. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  6159. var name = vertex + "+" + fragment + "@" + defines;
  6160. if (this._compiledEffects[name]) {
  6161. return this._compiledEffects[name];
  6162. }
  6163. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  6164. effect._key = name;
  6165. this._compiledEffects[name] = effect;
  6166. return effect;
  6167. };
  6168. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  6169. if (uniformsNames === void 0) { uniformsNames = []; }
  6170. if (samplers === void 0) { samplers = []; }
  6171. if (defines === void 0) { defines = ""; }
  6172. return this.createEffect({
  6173. vertex: "particles",
  6174. fragmentElement: fragmentName
  6175. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  6176. };
  6177. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  6178. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  6179. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  6180. var shaderProgram = this._gl.createProgram();
  6181. this._gl.attachShader(shaderProgram, vertexShader);
  6182. this._gl.attachShader(shaderProgram, fragmentShader);
  6183. this._gl.linkProgram(shaderProgram);
  6184. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  6185. if (!linked) {
  6186. var error = this._gl.getProgramInfoLog(shaderProgram);
  6187. if (error) {
  6188. throw new Error(error);
  6189. }
  6190. }
  6191. this._gl.deleteShader(vertexShader);
  6192. this._gl.deleteShader(fragmentShader);
  6193. return shaderProgram;
  6194. };
  6195. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6196. var results = [];
  6197. for (var index = 0; index < uniformsNames.length; index++) {
  6198. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6199. }
  6200. return results;
  6201. };
  6202. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6203. var results = [];
  6204. for (var index = 0; index < attributesNames.length; index++) {
  6205. try {
  6206. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6207. }
  6208. catch (e) {
  6209. results.push(-1);
  6210. }
  6211. }
  6212. return results;
  6213. };
  6214. Engine.prototype.enableEffect = function (effect) {
  6215. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6216. if (effect && effect.onBind) {
  6217. effect.onBind(effect);
  6218. }
  6219. return;
  6220. }
  6221. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6222. // Use program
  6223. this._gl.useProgram(effect.getProgram());
  6224. for (var i in this._vertexAttribArrays) {
  6225. //make sure this is a number)
  6226. var iAsNumber = +i;
  6227. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  6228. continue;
  6229. }
  6230. this._vertexAttribArrays[iAsNumber] = false;
  6231. this._gl.disableVertexAttribArray(iAsNumber);
  6232. }
  6233. var attributesCount = effect.getAttributesCount();
  6234. for (var index = 0; index < attributesCount; index++) {
  6235. // Attributes
  6236. var order = effect.getAttributeLocation(index);
  6237. if (order >= 0) {
  6238. this._vertexAttribArrays[order] = true;
  6239. this._gl.enableVertexAttribArray(order);
  6240. }
  6241. }
  6242. this._currentEffect = effect;
  6243. if (effect.onBind) {
  6244. effect.onBind(effect);
  6245. }
  6246. };
  6247. Engine.prototype.setArray = function (uniform, array) {
  6248. if (!uniform)
  6249. return;
  6250. this._gl.uniform1fv(uniform, array);
  6251. };
  6252. Engine.prototype.setArray2 = function (uniform, array) {
  6253. if (!uniform || array.length % 2 !== 0)
  6254. return;
  6255. this._gl.uniform2fv(uniform, array);
  6256. };
  6257. Engine.prototype.setArray3 = function (uniform, array) {
  6258. if (!uniform || array.length % 3 !== 0)
  6259. return;
  6260. this._gl.uniform3fv(uniform, array);
  6261. };
  6262. Engine.prototype.setArray4 = function (uniform, array) {
  6263. if (!uniform || array.length % 4 !== 0)
  6264. return;
  6265. this._gl.uniform4fv(uniform, array);
  6266. };
  6267. Engine.prototype.setMatrices = function (uniform, matrices) {
  6268. if (!uniform)
  6269. return;
  6270. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6271. };
  6272. Engine.prototype.setMatrix = function (uniform, matrix) {
  6273. if (!uniform)
  6274. return;
  6275. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6276. };
  6277. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  6278. if (!uniform)
  6279. return;
  6280. this._gl.uniformMatrix3fv(uniform, false, matrix);
  6281. };
  6282. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  6283. if (!uniform)
  6284. return;
  6285. this._gl.uniformMatrix2fv(uniform, false, matrix);
  6286. };
  6287. Engine.prototype.setFloat = function (uniform, value) {
  6288. if (!uniform)
  6289. return;
  6290. this._gl.uniform1f(uniform, value);
  6291. };
  6292. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6293. if (!uniform)
  6294. return;
  6295. this._gl.uniform2f(uniform, x, y);
  6296. };
  6297. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6298. if (!uniform)
  6299. return;
  6300. this._gl.uniform3f(uniform, x, y, z);
  6301. };
  6302. Engine.prototype.setBool = function (uniform, bool) {
  6303. if (!uniform)
  6304. return;
  6305. this._gl.uniform1i(uniform, bool);
  6306. };
  6307. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6308. if (!uniform)
  6309. return;
  6310. this._gl.uniform4f(uniform, x, y, z, w);
  6311. };
  6312. Engine.prototype.setColor3 = function (uniform, color3) {
  6313. if (!uniform)
  6314. return;
  6315. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6316. };
  6317. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6318. if (!uniform)
  6319. return;
  6320. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6321. };
  6322. // States
  6323. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  6324. if (zOffset === void 0) { zOffset = 0; }
  6325. if (reverseSide === void 0) { reverseSide = false; }
  6326. // Culling
  6327. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  6328. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  6329. var cullFace = this.cullBackFaces ? showSide : hideSide;
  6330. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  6331. if (culling) {
  6332. this._depthCullingState.cullFace = cullFace;
  6333. this._depthCullingState.cull = true;
  6334. }
  6335. else {
  6336. this._depthCullingState.cull = false;
  6337. }
  6338. }
  6339. // Z offset
  6340. this._depthCullingState.zOffset = zOffset;
  6341. };
  6342. Engine.prototype.setDepthBuffer = function (enable) {
  6343. this._depthCullingState.depthTest = enable;
  6344. };
  6345. Engine.prototype.getDepthWrite = function () {
  6346. return this._depthCullingState.depthMask;
  6347. };
  6348. Engine.prototype.setDepthWrite = function (enable) {
  6349. this._depthCullingState.depthMask = enable;
  6350. };
  6351. Engine.prototype.setColorWrite = function (enable) {
  6352. this._gl.colorMask(enable, enable, enable, enable);
  6353. };
  6354. Engine.prototype.setAlphaMode = function (mode) {
  6355. if (this._alphaMode === mode) {
  6356. return;
  6357. }
  6358. switch (mode) {
  6359. case Engine.ALPHA_DISABLE:
  6360. this.setDepthWrite(true);
  6361. this._alphaState.alphaBlend = false;
  6362. break;
  6363. case Engine.ALPHA_COMBINE:
  6364. this.setDepthWrite(false);
  6365. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6366. this._alphaState.alphaBlend = true;
  6367. break;
  6368. case Engine.ALPHA_ONEONE:
  6369. this.setDepthWrite(false);
  6370. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6371. this._alphaState.alphaBlend = true;
  6372. break;
  6373. case Engine.ALPHA_ADD:
  6374. this.setDepthWrite(false);
  6375. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6376. this._alphaState.alphaBlend = true;
  6377. break;
  6378. case Engine.ALPHA_SUBTRACT:
  6379. this.setDepthWrite(false);
  6380. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6381. this._alphaState.alphaBlend = true;
  6382. break;
  6383. case Engine.ALPHA_MULTIPLY:
  6384. this.setDepthWrite(false);
  6385. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  6386. this._alphaState.alphaBlend = true;
  6387. break;
  6388. case Engine.ALPHA_MAXIMIZED:
  6389. this.setDepthWrite(false);
  6390. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  6391. this._alphaState.alphaBlend = true;
  6392. break;
  6393. }
  6394. this._alphaMode = mode;
  6395. };
  6396. Engine.prototype.getAlphaMode = function () {
  6397. return this._alphaMode;
  6398. };
  6399. Engine.prototype.setAlphaTesting = function (enable) {
  6400. this._alphaTest = enable;
  6401. };
  6402. Engine.prototype.getAlphaTesting = function () {
  6403. return this._alphaTest;
  6404. };
  6405. // Textures
  6406. Engine.prototype.wipeCaches = function () {
  6407. this.resetTextureCache();
  6408. this._currentEffect = null;
  6409. this._depthCullingState.reset();
  6410. this._alphaState.reset();
  6411. this._cachedVertexBuffers = null;
  6412. this._cachedIndexBuffer = null;
  6413. this._cachedEffectForVertexBuffers = null;
  6414. };
  6415. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6416. var gl = this._gl;
  6417. gl.bindTexture(gl.TEXTURE_2D, texture);
  6418. var magFilter = gl.NEAREST;
  6419. var minFilter = gl.NEAREST;
  6420. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6421. magFilter = gl.LINEAR;
  6422. minFilter = gl.LINEAR;
  6423. }
  6424. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6425. magFilter = gl.LINEAR;
  6426. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6427. }
  6428. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6429. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6430. gl.bindTexture(gl.TEXTURE_2D, null);
  6431. texture.samplingMode = samplingMode;
  6432. };
  6433. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6434. var _this = this;
  6435. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6436. if (onLoad === void 0) { onLoad = null; }
  6437. if (onError === void 0) { onError = null; }
  6438. if (buffer === void 0) { buffer = null; }
  6439. var texture = this._gl.createTexture();
  6440. var extension;
  6441. var fromData = false;
  6442. if (url.substr(0, 5) === "data:") {
  6443. fromData = true;
  6444. }
  6445. if (!fromData)
  6446. extension = url.substr(url.length - 4, 4).toLowerCase();
  6447. else {
  6448. var oldUrl = url;
  6449. fromData = oldUrl.split(':');
  6450. url = oldUrl;
  6451. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6452. }
  6453. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6454. var isTGA = (extension === ".tga");
  6455. scene._addPendingData(texture);
  6456. texture.url = url;
  6457. texture.noMipmap = noMipmap;
  6458. texture.references = 1;
  6459. texture.samplingMode = samplingMode;
  6460. this._loadedTexturesCache.push(texture);
  6461. var onerror = function () {
  6462. scene._removePendingData(texture);
  6463. if (onError) {
  6464. onError();
  6465. }
  6466. };
  6467. var callback;
  6468. if (isTGA) {
  6469. callback = function (arrayBuffer) {
  6470. var data = new Uint8Array(arrayBuffer);
  6471. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6472. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6473. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6474. }, onLoad, samplingMode);
  6475. };
  6476. if (!(fromData instanceof Array))
  6477. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6478. callback(arrayBuffer);
  6479. }, onerror, scene.database, true);
  6480. else
  6481. callback(buffer);
  6482. }
  6483. else if (isDDS) {
  6484. callback = function (data) {
  6485. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6486. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6487. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6488. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6489. }, onLoad, samplingMode);
  6490. };
  6491. if (!(fromData instanceof Array))
  6492. BABYLON.Tools.LoadFile(url, function (data) {
  6493. callback(data);
  6494. }, onerror, scene.database, true);
  6495. else
  6496. callback(buffer);
  6497. }
  6498. else {
  6499. var onload = function (img) {
  6500. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6501. var isPot = (img.width === potWidth && img.height === potHeight);
  6502. if (!isPot) {
  6503. _this._prepareWorkingCanvas();
  6504. _this._workingCanvas.width = potWidth;
  6505. _this._workingCanvas.height = potHeight;
  6506. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6507. _this._workingContext.imageSmoothingEnabled = false;
  6508. _this._workingContext.mozImageSmoothingEnabled = false;
  6509. _this._workingContext.oImageSmoothingEnabled = false;
  6510. _this._workingContext.webkitImageSmoothingEnabled = false;
  6511. _this._workingContext.msImageSmoothingEnabled = false;
  6512. }
  6513. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6514. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6515. _this._workingContext.imageSmoothingEnabled = true;
  6516. _this._workingContext.mozImageSmoothingEnabled = true;
  6517. _this._workingContext.oImageSmoothingEnabled = true;
  6518. _this._workingContext.webkitImageSmoothingEnabled = true;
  6519. _this._workingContext.msImageSmoothingEnabled = true;
  6520. }
  6521. }
  6522. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6523. }, onLoad, samplingMode);
  6524. };
  6525. if (!(fromData instanceof Array))
  6526. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6527. else
  6528. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6529. }
  6530. return texture;
  6531. };
  6532. Engine.prototype._getInternalFormat = function (format) {
  6533. var internalFormat = this._gl.RGBA;
  6534. switch (format) {
  6535. case Engine.TEXTUREFORMAT_ALPHA:
  6536. internalFormat = this._gl.ALPHA;
  6537. break;
  6538. case Engine.TEXTUREFORMAT_LUMINANCE:
  6539. internalFormat = this._gl.LUMINANCE;
  6540. break;
  6541. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6542. internalFormat = this._gl.LUMINANCE_ALPHA;
  6543. break;
  6544. case Engine.TEXTUREFORMAT_RGB:
  6545. internalFormat = this._gl.RGB;
  6546. break;
  6547. case Engine.TEXTUREFORMAT_RGBA:
  6548. internalFormat = this._gl.RGBA;
  6549. break;
  6550. }
  6551. return internalFormat;
  6552. };
  6553. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  6554. if (compression === void 0) { compression = null; }
  6555. var internalFormat = this._getInternalFormat(format);
  6556. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6557. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6558. if (compression) {
  6559. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  6560. }
  6561. else {
  6562. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6563. }
  6564. if (texture.generateMipMaps) {
  6565. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6566. }
  6567. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6568. this.resetTextureCache();
  6569. texture.isReady = true;
  6570. };
  6571. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  6572. if (compression === void 0) { compression = null; }
  6573. var texture = this._gl.createTexture();
  6574. texture._baseWidth = width;
  6575. texture._baseHeight = height;
  6576. texture._width = width;
  6577. texture._height = height;
  6578. texture.references = 1;
  6579. this.updateRawTexture(texture, data, format, invertY, compression);
  6580. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6581. // Filters
  6582. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6583. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6584. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6585. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6586. texture.samplingMode = samplingMode;
  6587. this._loadedTexturesCache.push(texture);
  6588. return texture;
  6589. };
  6590. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6591. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6592. var texture = this._gl.createTexture();
  6593. texture._baseWidth = width;
  6594. texture._baseHeight = height;
  6595. if (forceExponantOfTwo) {
  6596. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  6597. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  6598. }
  6599. this.resetTextureCache();
  6600. texture._width = width;
  6601. texture._height = height;
  6602. texture.isReady = false;
  6603. texture.generateMipMaps = generateMipMaps;
  6604. texture.references = 1;
  6605. texture.samplingMode = samplingMode;
  6606. this.updateTextureSamplingMode(samplingMode, texture);
  6607. this._loadedTexturesCache.push(texture);
  6608. return texture;
  6609. };
  6610. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6611. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6612. if (texture.isCube) {
  6613. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, texture);
  6614. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6615. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6616. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6617. }
  6618. else {
  6619. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6620. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6621. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6622. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6623. }
  6624. };
  6625. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6626. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6627. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6628. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6629. if (texture.generateMipMaps) {
  6630. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6631. }
  6632. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6633. this.resetTextureCache();
  6634. texture.isReady = true;
  6635. };
  6636. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6637. if (texture._isDisabled) {
  6638. return;
  6639. }
  6640. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6641. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6642. try {
  6643. // Testing video texture support
  6644. if (this._videoTextureSupported === undefined) {
  6645. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6646. if (this._gl.getError() !== 0) {
  6647. this._videoTextureSupported = false;
  6648. }
  6649. else {
  6650. this._videoTextureSupported = true;
  6651. }
  6652. }
  6653. // Copy video through the current working canvas if video texture is not supported
  6654. if (!this._videoTextureSupported) {
  6655. if (!texture._workingCanvas) {
  6656. texture._workingCanvas = document.createElement("canvas");
  6657. texture._workingContext = texture._workingCanvas.getContext("2d");
  6658. texture._workingCanvas.width = texture._width;
  6659. texture._workingCanvas.height = texture._height;
  6660. }
  6661. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6662. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6663. }
  6664. else {
  6665. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6666. }
  6667. if (texture.generateMipMaps) {
  6668. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6669. }
  6670. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6671. this.resetTextureCache();
  6672. texture.isReady = true;
  6673. }
  6674. catch (ex) {
  6675. // Something unexpected
  6676. // Let's disable the texture
  6677. texture._isDisabled = true;
  6678. }
  6679. };
  6680. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6681. // old version had a "generateMipMaps" arg instead of options.
  6682. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6683. // in the same way, generateDepthBuffer is defaulted to true
  6684. var generateMipMaps = false;
  6685. var generateDepthBuffer = true;
  6686. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6687. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6688. if (options !== undefined) {
  6689. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6690. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6691. type = options.type === undefined ? type : options.type;
  6692. if (options.samplingMode !== undefined) {
  6693. samplingMode = options.samplingMode;
  6694. }
  6695. if (type === Engine.TEXTURETYPE_FLOAT) {
  6696. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6697. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6698. }
  6699. }
  6700. var gl = this._gl;
  6701. var texture = gl.createTexture();
  6702. gl.bindTexture(gl.TEXTURE_2D, texture);
  6703. var width = size.width || size;
  6704. var height = size.height || size;
  6705. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6706. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6707. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6708. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6709. }
  6710. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6711. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6712. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6713. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6714. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6715. var depthBuffer;
  6716. // Create the depth buffer
  6717. if (generateDepthBuffer) {
  6718. depthBuffer = gl.createRenderbuffer();
  6719. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6720. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6721. }
  6722. // Create the framebuffer
  6723. var framebuffer = gl.createFramebuffer();
  6724. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6725. if (generateDepthBuffer) {
  6726. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6727. }
  6728. if (generateMipMaps) {
  6729. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6730. }
  6731. // Unbind
  6732. gl.bindTexture(gl.TEXTURE_2D, null);
  6733. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6734. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6735. texture._framebuffer = framebuffer;
  6736. if (generateDepthBuffer) {
  6737. texture._depthBuffer = depthBuffer;
  6738. }
  6739. texture._width = width;
  6740. texture._height = height;
  6741. texture.isReady = true;
  6742. texture.generateMipMaps = generateMipMaps;
  6743. texture.references = 1;
  6744. texture.samplingMode = samplingMode;
  6745. this.resetTextureCache();
  6746. this._loadedTexturesCache.push(texture);
  6747. return texture;
  6748. };
  6749. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  6750. var gl = this._gl;
  6751. var texture = gl.createTexture();
  6752. var generateMipMaps = true;
  6753. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6754. if (options !== undefined) {
  6755. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  6756. if (options.samplingMode !== undefined) {
  6757. samplingMode = options.samplingMode;
  6758. }
  6759. }
  6760. texture.isCube = true;
  6761. texture.references = 1;
  6762. texture.generateMipMaps = generateMipMaps;
  6763. texture.references = 1;
  6764. texture.samplingMode = samplingMode;
  6765. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6766. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6767. for (var face = 0; face < 6; face++) {
  6768. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  6769. }
  6770. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  6771. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  6772. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6773. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6774. // Create the depth buffer
  6775. var depthBuffer = gl.createRenderbuffer();
  6776. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6777. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  6778. // Create the framebuffer
  6779. var framebuffer = gl.createFramebuffer();
  6780. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6781. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6782. // Mipmaps
  6783. if (texture.generateMipMaps) {
  6784. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6785. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6786. }
  6787. // Unbind
  6788. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6789. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6790. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6791. texture._framebuffer = framebuffer;
  6792. texture._depthBuffer = depthBuffer;
  6793. this.resetTextureCache();
  6794. texture._width = size;
  6795. texture._height = size;
  6796. texture.isReady = true;
  6797. return texture;
  6798. };
  6799. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  6800. var _this = this;
  6801. var gl = this._gl;
  6802. var texture = gl.createTexture();
  6803. texture.isCube = true;
  6804. texture.url = rootUrl;
  6805. texture.references = 1;
  6806. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6807. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6808. if (isDDS) {
  6809. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6810. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6811. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6812. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6813. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6814. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6815. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6816. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6817. }
  6818. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6819. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6820. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6821. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6822. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6823. _this.resetTextureCache();
  6824. texture._width = info.width;
  6825. texture._height = info.height;
  6826. texture.isReady = true;
  6827. }, null, null, true);
  6828. }
  6829. else {
  6830. cascadeLoad(rootUrl, scene, function (imgs) {
  6831. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6832. var height = width;
  6833. _this._prepareWorkingCanvas();
  6834. _this._workingCanvas.width = width;
  6835. _this._workingCanvas.height = height;
  6836. var faces = [
  6837. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6838. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6839. ];
  6840. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6841. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6842. for (var index = 0; index < faces.length; index++) {
  6843. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6844. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6845. }
  6846. if (!noMipmap) {
  6847. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6848. }
  6849. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6850. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6851. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6852. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6853. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6854. _this.resetTextureCache();
  6855. texture._width = width;
  6856. texture._height = height;
  6857. texture.isReady = true;
  6858. }, files);
  6859. }
  6860. return texture;
  6861. };
  6862. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  6863. var _this = this;
  6864. var gl = this._gl;
  6865. var texture = gl.createTexture();
  6866. scene._addPendingData(texture);
  6867. texture.isCube = true;
  6868. texture.references = 1;
  6869. texture.url = url;
  6870. var internalFormat = this._getInternalFormat(format);
  6871. var textureType = gl.UNSIGNED_BYTE;
  6872. if (type === Engine.TEXTURETYPE_FLOAT) {
  6873. textureType = gl.FLOAT;
  6874. }
  6875. var width = size;
  6876. var height = width;
  6877. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  6878. texture._width = width;
  6879. texture._height = height;
  6880. var onerror = function () {
  6881. scene._removePendingData(texture);
  6882. };
  6883. var internalCallback = function (data) {
  6884. var rgbeDataArrays = callback(data);
  6885. var facesIndex = [
  6886. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6887. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6888. ];
  6889. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6890. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6891. if (!noMipmap && isPot) {
  6892. if (mipmmapGenerator) {
  6893. var arrayTemp = [];
  6894. // Data are known to be in +X +Y +Z -X -Y -Z
  6895. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  6896. arrayTemp.push(rgbeDataArrays[0]); // +X
  6897. arrayTemp.push(rgbeDataArrays[3]); // -X
  6898. arrayTemp.push(rgbeDataArrays[1]); // +Y
  6899. arrayTemp.push(rgbeDataArrays[4]); // -Y
  6900. arrayTemp.push(rgbeDataArrays[2]); // +Z
  6901. arrayTemp.push(rgbeDataArrays[5]); // -Z
  6902. var mipData = mipmmapGenerator(arrayTemp);
  6903. for (var level = 0; level < mipData.length; level++) {
  6904. var mipSize = width >> level;
  6905. // mipData is order in +X -X +Y -Y +Z -Z
  6906. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  6907. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  6908. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  6909. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  6910. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  6911. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  6912. }
  6913. }
  6914. else {
  6915. // Data are known to be in +X +Y +Z -X -Y -Z
  6916. for (var index = 0; index < facesIndex.length; index++) {
  6917. var faceData = rgbeDataArrays[index];
  6918. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  6919. }
  6920. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6921. }
  6922. }
  6923. else {
  6924. noMipmap = true;
  6925. }
  6926. if (textureType == gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  6927. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  6928. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  6929. }
  6930. else {
  6931. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6932. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6933. }
  6934. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6935. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6936. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6937. texture.isReady = true;
  6938. _this.resetTextureCache();
  6939. scene._removePendingData(texture);
  6940. };
  6941. BABYLON.Tools.LoadFile(url, function (data) {
  6942. internalCallback(data);
  6943. }, onerror, scene.database, true);
  6944. return texture;
  6945. };
  6946. ;
  6947. Engine.prototype._releaseTexture = function (texture) {
  6948. var gl = this._gl;
  6949. if (texture._framebuffer) {
  6950. gl.deleteFramebuffer(texture._framebuffer);
  6951. }
  6952. if (texture._depthBuffer) {
  6953. gl.deleteRenderbuffer(texture._depthBuffer);
  6954. }
  6955. gl.deleteTexture(texture);
  6956. // Unbind channels
  6957. this.unbindAllTextures();
  6958. var index = this._loadedTexturesCache.indexOf(texture);
  6959. if (index !== -1) {
  6960. this._loadedTexturesCache.splice(index, 1);
  6961. }
  6962. };
  6963. Engine.prototype.bindSamplers = function (effect) {
  6964. this._gl.useProgram(effect.getProgram());
  6965. var samplers = effect.getSamplers();
  6966. for (var index = 0; index < samplers.length; index++) {
  6967. var uniform = effect.getUniform(samplers[index]);
  6968. this._gl.uniform1i(uniform, index);
  6969. }
  6970. this._currentEffect = null;
  6971. };
  6972. Engine.prototype._bindTexture = function (channel, texture) {
  6973. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6974. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6975. this._activeTexturesCache[channel] = null;
  6976. };
  6977. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6978. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6979. };
  6980. Engine.prototype.unbindAllTextures = function () {
  6981. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6982. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6983. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6984. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6985. this._activeTexturesCache[channel] = null;
  6986. }
  6987. };
  6988. Engine.prototype.setTexture = function (channel, texture) {
  6989. if (channel < 0) {
  6990. return;
  6991. }
  6992. // Not ready?
  6993. if (!texture || !texture.isReady()) {
  6994. if (this._activeTexturesCache[channel] != null) {
  6995. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6996. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6997. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6998. this._activeTexturesCache[channel] = null;
  6999. }
  7000. return;
  7001. }
  7002. // Video
  7003. var alreadyActivated = false;
  7004. if (texture instanceof BABYLON.VideoTexture) {
  7005. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7006. alreadyActivated = true;
  7007. texture.update();
  7008. }
  7009. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  7010. texture.delayLoad();
  7011. return;
  7012. }
  7013. if (this._activeTexturesCache[channel] === texture) {
  7014. return;
  7015. }
  7016. this._activeTexturesCache[channel] = texture;
  7017. var internalTexture = texture.getInternalTexture();
  7018. if (!alreadyActivated) {
  7019. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  7020. }
  7021. if (internalTexture.isCube) {
  7022. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  7023. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  7024. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  7025. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  7026. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  7027. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  7028. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  7029. }
  7030. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  7031. }
  7032. else {
  7033. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  7034. if (internalTexture._cachedWrapU !== texture.wrapU) {
  7035. internalTexture._cachedWrapU = texture.wrapU;
  7036. switch (texture.wrapU) {
  7037. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7038. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  7039. break;
  7040. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7041. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  7042. break;
  7043. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7044. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  7045. break;
  7046. }
  7047. }
  7048. if (internalTexture._cachedWrapV !== texture.wrapV) {
  7049. internalTexture._cachedWrapV = texture.wrapV;
  7050. switch (texture.wrapV) {
  7051. case BABYLON.Texture.WRAP_ADDRESSMODE:
  7052. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  7053. break;
  7054. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  7055. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  7056. break;
  7057. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  7058. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  7059. break;
  7060. }
  7061. }
  7062. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  7063. }
  7064. };
  7065. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  7066. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  7067. var value = texture.anisotropicFilteringLevel;
  7068. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7069. value = 1;
  7070. }
  7071. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  7072. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  7073. texture._cachedAnisotropicFilteringLevel = value;
  7074. }
  7075. };
  7076. Engine.prototype.readPixels = function (x, y, width, height) {
  7077. var data = new Uint8Array(height * width * 4);
  7078. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  7079. return data;
  7080. };
  7081. Engine.prototype.releaseInternalTexture = function (texture) {
  7082. if (!texture) {
  7083. return;
  7084. }
  7085. texture.references--;
  7086. // Final reference ?
  7087. if (texture.references === 0) {
  7088. var texturesCache = this.getLoadedTexturesCache();
  7089. var index = texturesCache.indexOf(texture);
  7090. if (index > -1) {
  7091. texturesCache.splice(index, 1);
  7092. }
  7093. this._releaseTexture(texture);
  7094. }
  7095. };
  7096. // Dispose
  7097. Engine.prototype.dispose = function () {
  7098. this.hideLoadingUI();
  7099. this.stopRenderLoop();
  7100. // Release scenes
  7101. while (this.scenes.length) {
  7102. this.scenes[0].dispose();
  7103. }
  7104. // Release audio engine
  7105. Engine.audioEngine.dispose();
  7106. // Release effects
  7107. for (var name in this._compiledEffects) {
  7108. this._gl.deleteProgram(this._compiledEffects[name]._program);
  7109. }
  7110. // Unbind
  7111. for (var i in this._vertexAttribArrays) {
  7112. //making sure this is a string
  7113. var iAsNumber = +i;
  7114. if (iAsNumber > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[iAsNumber]) {
  7115. continue;
  7116. }
  7117. this._gl.disableVertexAttribArray(iAsNumber);
  7118. }
  7119. this._gl = null;
  7120. // Events
  7121. window.removeEventListener("blur", this._onBlur);
  7122. window.removeEventListener("focus", this._onFocus);
  7123. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  7124. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  7125. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  7126. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  7127. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  7128. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  7129. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  7130. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  7131. };
  7132. // Loading screen
  7133. Engine.prototype.displayLoadingUI = function () {
  7134. this._loadingScreen.displayLoadingUI();
  7135. };
  7136. Engine.prototype.hideLoadingUI = function () {
  7137. this._loadingScreen.hideLoadingUI();
  7138. };
  7139. Object.defineProperty(Engine.prototype, "loadingScreen", {
  7140. get: function () {
  7141. return this._loadingScreen;
  7142. },
  7143. set: function (loadingScreen) {
  7144. this._loadingScreen = loadingScreen;
  7145. },
  7146. enumerable: true,
  7147. configurable: true
  7148. });
  7149. Object.defineProperty(Engine.prototype, "loadingUIText", {
  7150. set: function (text) {
  7151. this._loadingScreen.loadingUIText = text;
  7152. },
  7153. enumerable: true,
  7154. configurable: true
  7155. });
  7156. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  7157. set: function (color) {
  7158. this._loadingScreen.loadingUIBackgroundColor = color;
  7159. },
  7160. enumerable: true,
  7161. configurable: true
  7162. });
  7163. // FPS
  7164. Engine.prototype.getFps = function () {
  7165. return this.fps;
  7166. };
  7167. Engine.prototype.getDeltaTime = function () {
  7168. return this.deltaTime;
  7169. };
  7170. Engine.prototype._measureFps = function () {
  7171. this.previousFramesDuration.push(BABYLON.Tools.Now);
  7172. var length = this.previousFramesDuration.length;
  7173. if (length >= 2) {
  7174. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  7175. }
  7176. if (length >= this.fpsRange) {
  7177. if (length > this.fpsRange) {
  7178. this.previousFramesDuration.splice(0, 1);
  7179. length = this.previousFramesDuration.length;
  7180. }
  7181. var sum = 0;
  7182. for (var id = 0; id < length - 1; id++) {
  7183. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  7184. }
  7185. this.fps = 1000.0 / (sum / (length - 1));
  7186. }
  7187. };
  7188. // Statics
  7189. Engine.isSupported = function () {
  7190. try {
  7191. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  7192. if (navigator.isCocoonJS) {
  7193. return true;
  7194. }
  7195. var tempcanvas = document.createElement("canvas");
  7196. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  7197. return gl != null && !!window.WebGLRenderingContext;
  7198. }
  7199. catch (e) {
  7200. return false;
  7201. }
  7202. };
  7203. // Const statics
  7204. Engine._ALPHA_DISABLE = 0;
  7205. Engine._ALPHA_ADD = 1;
  7206. Engine._ALPHA_COMBINE = 2;
  7207. Engine._ALPHA_SUBTRACT = 3;
  7208. Engine._ALPHA_MULTIPLY = 4;
  7209. Engine._ALPHA_MAXIMIZED = 5;
  7210. Engine._ALPHA_ONEONE = 6;
  7211. Engine._DELAYLOADSTATE_NONE = 0;
  7212. Engine._DELAYLOADSTATE_LOADED = 1;
  7213. Engine._DELAYLOADSTATE_LOADING = 2;
  7214. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  7215. Engine._TEXTUREFORMAT_ALPHA = 0;
  7216. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  7217. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  7218. Engine._TEXTUREFORMAT_RGB = 4;
  7219. Engine._TEXTUREFORMAT_RGBA = 5;
  7220. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  7221. Engine._TEXTURETYPE_FLOAT = 1;
  7222. // Updatable statics so stick with vars here
  7223. Engine.CollisionsEpsilon = 0.001;
  7224. Engine.CodeRepository = "src/";
  7225. Engine.ShadersRepository = "src/Shaders/";
  7226. return Engine;
  7227. })();
  7228. BABYLON.Engine = Engine;
  7229. })(BABYLON || (BABYLON = {}));
  7230. var BABYLON;
  7231. (function (BABYLON) {
  7232. /**
  7233. * Node is the basic class for all scene objects (Mesh, Light Camera).
  7234. */
  7235. var Node = (function () {
  7236. /**
  7237. * @constructor
  7238. * @param {string} name - the name and id to be given to this node
  7239. * @param {BABYLON.Scene} the scene this node will be added to
  7240. */
  7241. function Node(name, scene) {
  7242. this.state = "";
  7243. this.animations = new Array();
  7244. this._ranges = {};
  7245. this._childrenFlag = -1;
  7246. this._isEnabled = true;
  7247. this._isReady = true;
  7248. this._currentRenderId = -1;
  7249. this._parentRenderId = -1;
  7250. this.name = name;
  7251. this.id = name;
  7252. this._scene = scene;
  7253. this._initCache();
  7254. }
  7255. Object.defineProperty(Node.prototype, "parent", {
  7256. get: function () {
  7257. return this._parentNode;
  7258. },
  7259. set: function (parent) {
  7260. if (this._parentNode === parent) {
  7261. return;
  7262. }
  7263. if (this._parentNode) {
  7264. var index = this._parentNode._children.indexOf(this);
  7265. if (index !== -1) {
  7266. this._parentNode._children.splice(index, 1);
  7267. }
  7268. }
  7269. this._parentNode = parent;
  7270. if (this._parentNode) {
  7271. if (!this._parentNode._children) {
  7272. this._parentNode._children = new Array();
  7273. }
  7274. this._parentNode._children.push(this);
  7275. }
  7276. },
  7277. enumerable: true,
  7278. configurable: true
  7279. });
  7280. Node.prototype.getScene = function () {
  7281. return this._scene;
  7282. };
  7283. Node.prototype.getEngine = function () {
  7284. return this._scene.getEngine();
  7285. };
  7286. // override it in derived class
  7287. Node.prototype.getWorldMatrix = function () {
  7288. return BABYLON.Matrix.Identity();
  7289. };
  7290. // override it in derived class if you add new variables to the cache
  7291. // and call the parent class method
  7292. Node.prototype._initCache = function () {
  7293. this._cache = {};
  7294. this._cache.parent = undefined;
  7295. };
  7296. Node.prototype.updateCache = function (force) {
  7297. if (!force && this.isSynchronized())
  7298. return;
  7299. this._cache.parent = this.parent;
  7300. this._updateCache();
  7301. };
  7302. // override it in derived class if you add new variables to the cache
  7303. // and call the parent class method if !ignoreParentClass
  7304. Node.prototype._updateCache = function (ignoreParentClass) {
  7305. };
  7306. // override it in derived class if you add new variables to the cache
  7307. Node.prototype._isSynchronized = function () {
  7308. return true;
  7309. };
  7310. Node.prototype._markSyncedWithParent = function () {
  7311. this._parentRenderId = this.parent._currentRenderId;
  7312. };
  7313. Node.prototype.isSynchronizedWithParent = function () {
  7314. if (!this.parent) {
  7315. return true;
  7316. }
  7317. if (this._parentRenderId !== this.parent._currentRenderId) {
  7318. return false;
  7319. }
  7320. return this.parent.isSynchronized();
  7321. };
  7322. Node.prototype.isSynchronized = function (updateCache) {
  7323. var check = this.hasNewParent();
  7324. check = check || !this.isSynchronizedWithParent();
  7325. check = check || !this._isSynchronized();
  7326. if (updateCache)
  7327. this.updateCache(true);
  7328. return !check;
  7329. };
  7330. Node.prototype.hasNewParent = function (update) {
  7331. if (this._cache.parent === this.parent)
  7332. return false;
  7333. if (update)
  7334. this._cache.parent = this.parent;
  7335. return true;
  7336. };
  7337. /**
  7338. * Is this node ready to be used/rendered
  7339. * @return {boolean} is it ready
  7340. */
  7341. Node.prototype.isReady = function () {
  7342. return this._isReady;
  7343. };
  7344. /**
  7345. * Is this node enabled.
  7346. * If the node has a parent and is enabled, the parent will be inspected as well.
  7347. * @return {boolean} whether this node (and its parent) is enabled.
  7348. * @see setEnabled
  7349. */
  7350. Node.prototype.isEnabled = function () {
  7351. if (!this._isEnabled) {
  7352. return false;
  7353. }
  7354. if (this.parent) {
  7355. return this.parent.isEnabled();
  7356. }
  7357. return true;
  7358. };
  7359. /**
  7360. * Set the enabled state of this node.
  7361. * @param {boolean} value - the new enabled state
  7362. * @see isEnabled
  7363. */
  7364. Node.prototype.setEnabled = function (value) {
  7365. this._isEnabled = value;
  7366. };
  7367. /**
  7368. * Is this node a descendant of the given node.
  7369. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7370. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7371. * @see parent
  7372. */
  7373. Node.prototype.isDescendantOf = function (ancestor) {
  7374. if (this.parent) {
  7375. if (this.parent === ancestor) {
  7376. return true;
  7377. }
  7378. return this.parent.isDescendantOf(ancestor);
  7379. }
  7380. return false;
  7381. };
  7382. /**
  7383. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  7384. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  7385. * @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.
  7386. * @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.
  7387. */
  7388. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  7389. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  7390. if (!this._children) {
  7391. return;
  7392. }
  7393. for (var index = 0; index < this._children.length; index++) {
  7394. var item = this._children[index];
  7395. if (!predicate || predicate(item)) {
  7396. results.push(item);
  7397. }
  7398. if (!directDescendantsOnly) {
  7399. item._getDescendants(results, false, predicate);
  7400. }
  7401. }
  7402. };
  7403. /**
  7404. * Will return all nodes that have this node as ascendant.
  7405. * @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.
  7406. * @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.
  7407. * @return {BABYLON.Node[]} all children nodes of all types.
  7408. */
  7409. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  7410. var results = [];
  7411. this._getDescendants(results, directDescendantsOnly, predicate);
  7412. return results;
  7413. };
  7414. /**
  7415. * @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.
  7416. * @Deprecated, legacy support.
  7417. * use getDecendants instead.
  7418. */
  7419. Node.prototype.getChildren = function (predicate) {
  7420. return this.getDescendants(true, predicate);
  7421. };
  7422. /**
  7423. * Get all child-meshes of this node.
  7424. */
  7425. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  7426. var results = [];
  7427. this._getDescendants(results, directDecendantsOnly, function (node) {
  7428. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  7429. });
  7430. return results;
  7431. };
  7432. Node.prototype._setReady = function (state) {
  7433. if (state === this._isReady) {
  7434. return;
  7435. }
  7436. if (!state) {
  7437. this._isReady = false;
  7438. return;
  7439. }
  7440. this._isReady = true;
  7441. if (this.onReady) {
  7442. this.onReady(this);
  7443. }
  7444. };
  7445. Node.prototype.getAnimationByName = function (name) {
  7446. for (var i = 0; i < this.animations.length; i++) {
  7447. var animation = this.animations[i];
  7448. if (animation.name === name) {
  7449. return animation;
  7450. }
  7451. }
  7452. return null;
  7453. };
  7454. Node.prototype.createAnimationRange = function (name, from, to) {
  7455. // check name not already in use
  7456. if (!this._ranges[name]) {
  7457. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  7458. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7459. if (this.animations[i]) {
  7460. this.animations[i].createRange(name, from, to);
  7461. }
  7462. }
  7463. }
  7464. };
  7465. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  7466. if (deleteFrames === void 0) { deleteFrames = true; }
  7467. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  7468. if (this.animations[i]) {
  7469. this.animations[i].deleteRange(name, deleteFrames);
  7470. }
  7471. }
  7472. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  7473. };
  7474. Node.prototype.getAnimationRange = function (name) {
  7475. return this._ranges[name];
  7476. };
  7477. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  7478. var range = this.getAnimationRange(name);
  7479. if (!range) {
  7480. return null;
  7481. }
  7482. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  7483. };
  7484. Node.prototype.serializeAnimationRanges = function () {
  7485. var serializationRanges = [];
  7486. for (var name in this._ranges) {
  7487. var range = {};
  7488. range.name = name;
  7489. range.from = this._ranges[name].from;
  7490. range.to = this._ranges[name].to;
  7491. serializationRanges.push(range);
  7492. }
  7493. return serializationRanges;
  7494. };
  7495. Node.prototype.dispose = function () {
  7496. this.parent = null;
  7497. };
  7498. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  7499. if (parsedNode.ranges) {
  7500. for (var index = 0; index < parsedNode.ranges.length; index++) {
  7501. var data = parsedNode.ranges[index];
  7502. node.createAnimationRange(data.name, data.from, data.to);
  7503. }
  7504. }
  7505. };
  7506. __decorate([
  7507. BABYLON.serialize()
  7508. ], Node.prototype, "name", void 0);
  7509. __decorate([
  7510. BABYLON.serialize()
  7511. ], Node.prototype, "id", void 0);
  7512. __decorate([
  7513. BABYLON.serialize()
  7514. ], Node.prototype, "uniqueId", void 0);
  7515. __decorate([
  7516. BABYLON.serialize()
  7517. ], Node.prototype, "state", void 0);
  7518. return Node;
  7519. })();
  7520. BABYLON.Node = Node;
  7521. })(BABYLON || (BABYLON = {}));
  7522. var BABYLON;
  7523. (function (BABYLON) {
  7524. var FilesInput = (function () {
  7525. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7526. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7527. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7528. this._engine = p_engine;
  7529. this._canvas = p_canvas;
  7530. this._currentScene = p_scene;
  7531. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7532. this._progressCallback = p_progressCallback;
  7533. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7534. this._textureLoadingCallback = p_textureLoadingCallback;
  7535. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7536. }
  7537. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7538. var _this = this;
  7539. if (p_elementToMonitor) {
  7540. this._elementToMonitor = p_elementToMonitor;
  7541. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7542. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7543. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7544. }
  7545. };
  7546. FilesInput.prototype.renderFunction = function () {
  7547. if (this._additionnalRenderLoopLogicCallback) {
  7548. this._additionnalRenderLoopLogicCallback();
  7549. }
  7550. if (this._currentScene) {
  7551. if (this._textureLoadingCallback) {
  7552. var remaining = this._currentScene.getWaitingItemsCount();
  7553. if (remaining > 0) {
  7554. this._textureLoadingCallback(remaining);
  7555. }
  7556. }
  7557. this._currentScene.render();
  7558. }
  7559. };
  7560. FilesInput.prototype.drag = function (e) {
  7561. e.stopPropagation();
  7562. e.preventDefault();
  7563. };
  7564. FilesInput.prototype.drop = function (eventDrop) {
  7565. eventDrop.stopPropagation();
  7566. eventDrop.preventDefault();
  7567. this.loadFiles(eventDrop);
  7568. };
  7569. FilesInput.prototype.loadFiles = function (event) {
  7570. if (this._startingProcessingFilesCallback)
  7571. this._startingProcessingFilesCallback();
  7572. // Handling data transfer via drag'n'drop
  7573. if (event && event.dataTransfer && event.dataTransfer.files) {
  7574. this._filesToLoad = event.dataTransfer.files;
  7575. }
  7576. // Handling files from input files
  7577. if (event && event.target && event.target.files) {
  7578. this._filesToLoad = event.target.files;
  7579. }
  7580. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7581. for (var i = 0; i < this._filesToLoad.length; i++) {
  7582. switch (this._filesToLoad[i].type) {
  7583. case "image/jpeg":
  7584. case "image/png":
  7585. case "image/bmp":
  7586. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7587. break;
  7588. case "image/targa":
  7589. case "image/vnd.ms-dds":
  7590. case "audio/wav":
  7591. case "audio/x-wav":
  7592. case "audio/mp3":
  7593. case "audio/mpeg":
  7594. case "audio/mpeg3":
  7595. case "audio/x-mpeg-3":
  7596. case "audio/ogg":
  7597. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7598. break;
  7599. default:
  7600. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  7601. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  7602. }
  7603. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  7604. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  7605. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  7606. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7607. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7608. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  7609. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  7610. this._sceneFileToLoad = this._filesToLoad[i];
  7611. }
  7612. break;
  7613. }
  7614. }
  7615. this.reload();
  7616. }
  7617. };
  7618. FilesInput.prototype.reload = function () {
  7619. var _this = this;
  7620. var that = this;
  7621. // If a ".babylon" file has been provided
  7622. if (this._sceneFileToLoad) {
  7623. if (this._currentScene) {
  7624. if (BABYLON.Tools.errorsCount > 0) {
  7625. BABYLON.Tools.ClearLogCache();
  7626. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  7627. }
  7628. this._engine.stopRenderLoop();
  7629. this._currentScene.dispose();
  7630. }
  7631. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7632. that._currentScene = newScene;
  7633. // Wait for textures and shaders to be ready
  7634. that._currentScene.executeWhenReady(function () {
  7635. // Attach camera to canvas inputs
  7636. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7637. that._currentScene.createDefaultCameraOrLight();
  7638. }
  7639. that._currentScene.activeCamera.attachControl(that._canvas);
  7640. if (that._sceneLoadedCallback) {
  7641. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7642. }
  7643. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7644. });
  7645. }, function (progress) {
  7646. if (_this._progressCallback) {
  7647. _this._progressCallback(progress);
  7648. }
  7649. });
  7650. }
  7651. else {
  7652. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7653. }
  7654. };
  7655. FilesInput.FilesTextures = new Array();
  7656. FilesInput.FilesToLoad = new Array();
  7657. return FilesInput;
  7658. })();
  7659. BABYLON.FilesInput = FilesInput;
  7660. })(BABYLON || (BABYLON = {}));
  7661. var BABYLON;
  7662. (function (BABYLON) {
  7663. var IntersectionInfo = (function () {
  7664. function IntersectionInfo(bu, bv, distance) {
  7665. this.bu = bu;
  7666. this.bv = bv;
  7667. this.distance = distance;
  7668. this.faceId = 0;
  7669. this.subMeshId = 0;
  7670. }
  7671. return IntersectionInfo;
  7672. })();
  7673. BABYLON.IntersectionInfo = IntersectionInfo;
  7674. var PickingInfo = (function () {
  7675. function PickingInfo() {
  7676. this.hit = false;
  7677. this.distance = 0;
  7678. this.pickedPoint = null;
  7679. this.pickedMesh = null;
  7680. this.bu = 0;
  7681. this.bv = 0;
  7682. this.faceId = -1;
  7683. this.subMeshId = 0;
  7684. this.pickedSprite = null;
  7685. }
  7686. // Methods
  7687. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  7688. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7689. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  7690. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7691. return null;
  7692. }
  7693. var indices = this.pickedMesh.getIndices();
  7694. var result;
  7695. if (useVerticesNormals) {
  7696. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7697. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7698. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7699. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7700. normal0 = normal0.scale(this.bu);
  7701. normal1 = normal1.scale(this.bv);
  7702. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7703. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7704. }
  7705. else {
  7706. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  7707. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  7708. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  7709. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  7710. var p1p2 = vertex1.subtract(vertex2);
  7711. var p3p2 = vertex3.subtract(vertex2);
  7712. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  7713. }
  7714. if (useWorldCoordinates) {
  7715. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7716. }
  7717. return BABYLON.Vector3.Normalize(result);
  7718. };
  7719. PickingInfo.prototype.getTextureCoordinates = function () {
  7720. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7721. return null;
  7722. }
  7723. var indices = this.pickedMesh.getIndices();
  7724. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7725. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7726. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7727. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7728. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  7729. uv1 = uv1.scale(this.bu);
  7730. uv2 = uv2.scale(this.bv);
  7731. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7732. };
  7733. return PickingInfo;
  7734. })();
  7735. BABYLON.PickingInfo = PickingInfo;
  7736. })(BABYLON || (BABYLON = {}));
  7737. var BABYLON;
  7738. (function (BABYLON) {
  7739. var BoundingSphere = (function () {
  7740. function BoundingSphere(minimum, maximum) {
  7741. this.minimum = minimum;
  7742. this.maximum = maximum;
  7743. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7744. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7745. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7746. this.radius = distance * 0.5;
  7747. this.centerWorld = BABYLON.Vector3.Zero();
  7748. this._update(BABYLON.Matrix.Identity());
  7749. }
  7750. // Methods
  7751. BoundingSphere.prototype._update = function (world) {
  7752. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7753. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7754. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7755. };
  7756. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7757. for (var i = 0; i < 6; i++) {
  7758. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7759. return false;
  7760. }
  7761. return true;
  7762. };
  7763. BoundingSphere.prototype.intersectsPoint = function (point) {
  7764. var x = this.centerWorld.x - point.x;
  7765. var y = this.centerWorld.y - point.y;
  7766. var z = this.centerWorld.z - point.z;
  7767. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7768. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  7769. return false;
  7770. return true;
  7771. };
  7772. // Statics
  7773. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7774. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7775. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7776. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7777. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7778. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7779. return false;
  7780. return true;
  7781. };
  7782. return BoundingSphere;
  7783. })();
  7784. BABYLON.BoundingSphere = BoundingSphere;
  7785. })(BABYLON || (BABYLON = {}));
  7786. var BABYLON;
  7787. (function (BABYLON) {
  7788. var BoundingBox = (function () {
  7789. function BoundingBox(minimum, maximum) {
  7790. this.minimum = minimum;
  7791. this.maximum = maximum;
  7792. this.vectors = new Array();
  7793. this.vectorsWorld = new Array();
  7794. // Bounding vectors
  7795. this.vectors.push(this.minimum.clone());
  7796. this.vectors.push(this.maximum.clone());
  7797. this.vectors.push(this.minimum.clone());
  7798. this.vectors[2].x = this.maximum.x;
  7799. this.vectors.push(this.minimum.clone());
  7800. this.vectors[3].y = this.maximum.y;
  7801. this.vectors.push(this.minimum.clone());
  7802. this.vectors[4].z = this.maximum.z;
  7803. this.vectors.push(this.maximum.clone());
  7804. this.vectors[5].z = this.minimum.z;
  7805. this.vectors.push(this.maximum.clone());
  7806. this.vectors[6].x = this.minimum.x;
  7807. this.vectors.push(this.maximum.clone());
  7808. this.vectors[7].y = this.minimum.y;
  7809. // OBB
  7810. this.center = this.maximum.add(this.minimum).scale(0.5);
  7811. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7812. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7813. // World
  7814. for (var index = 0; index < this.vectors.length; index++) {
  7815. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7816. }
  7817. this.minimumWorld = BABYLON.Vector3.Zero();
  7818. this.maximumWorld = BABYLON.Vector3.Zero();
  7819. this._update(BABYLON.Matrix.Identity());
  7820. }
  7821. // Methods
  7822. BoundingBox.prototype.getWorldMatrix = function () {
  7823. return this._worldMatrix;
  7824. };
  7825. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  7826. this._worldMatrix.copyFrom(matrix);
  7827. return this;
  7828. };
  7829. BoundingBox.prototype._update = function (world) {
  7830. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7831. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7832. for (var index = 0; index < this.vectors.length; index++) {
  7833. var v = this.vectorsWorld[index];
  7834. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7835. if (v.x < this.minimumWorld.x)
  7836. this.minimumWorld.x = v.x;
  7837. if (v.y < this.minimumWorld.y)
  7838. this.minimumWorld.y = v.y;
  7839. if (v.z < this.minimumWorld.z)
  7840. this.minimumWorld.z = v.z;
  7841. if (v.x > this.maximumWorld.x)
  7842. this.maximumWorld.x = v.x;
  7843. if (v.y > this.maximumWorld.y)
  7844. this.maximumWorld.y = v.y;
  7845. if (v.z > this.maximumWorld.z)
  7846. this.maximumWorld.z = v.z;
  7847. }
  7848. // OBB
  7849. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7850. this.center.scaleInPlace(0.5);
  7851. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7852. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7853. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7854. this._worldMatrix = world;
  7855. };
  7856. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7857. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7858. };
  7859. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7860. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7861. };
  7862. BoundingBox.prototype.intersectsPoint = function (point) {
  7863. var delta = -BABYLON.Epsilon;
  7864. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7865. return false;
  7866. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7867. return false;
  7868. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7869. return false;
  7870. return true;
  7871. };
  7872. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7873. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7874. };
  7875. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7876. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7877. return false;
  7878. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7879. return false;
  7880. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7881. return false;
  7882. return true;
  7883. };
  7884. // Statics
  7885. BoundingBox.Intersects = function (box0, box1) {
  7886. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7887. return false;
  7888. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7889. return false;
  7890. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7891. return false;
  7892. return true;
  7893. };
  7894. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7895. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7896. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7897. return (num <= (sphereRadius * sphereRadius));
  7898. };
  7899. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7900. for (var p = 0; p < 6; p++) {
  7901. for (var i = 0; i < 8; i++) {
  7902. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7903. return false;
  7904. }
  7905. }
  7906. }
  7907. return true;
  7908. };
  7909. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7910. for (var p = 0; p < 6; p++) {
  7911. var inCount = 8;
  7912. for (var i = 0; i < 8; i++) {
  7913. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7914. --inCount;
  7915. }
  7916. else {
  7917. break;
  7918. }
  7919. }
  7920. if (inCount === 0)
  7921. return false;
  7922. }
  7923. return true;
  7924. };
  7925. return BoundingBox;
  7926. })();
  7927. BABYLON.BoundingBox = BoundingBox;
  7928. })(BABYLON || (BABYLON = {}));
  7929. var BABYLON;
  7930. (function (BABYLON) {
  7931. var computeBoxExtents = function (axis, box) {
  7932. var p = BABYLON.Vector3.Dot(box.center, axis);
  7933. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7934. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7935. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7936. var r = r0 + r1 + r2;
  7937. return {
  7938. min: p - r,
  7939. max: p + r
  7940. };
  7941. };
  7942. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7943. var axisOverlap = function (axis, box0, box1) {
  7944. var result0 = computeBoxExtents(axis, box0);
  7945. var result1 = computeBoxExtents(axis, box1);
  7946. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7947. };
  7948. var BoundingInfo = (function () {
  7949. function BoundingInfo(minimum, maximum) {
  7950. this.minimum = minimum;
  7951. this.maximum = maximum;
  7952. this._isLocked = false;
  7953. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7954. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7955. }
  7956. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  7957. get: function () {
  7958. return this._isLocked;
  7959. },
  7960. set: function (value) {
  7961. this._isLocked = value;
  7962. },
  7963. enumerable: true,
  7964. configurable: true
  7965. });
  7966. // Methods
  7967. BoundingInfo.prototype.update = function (world) {
  7968. if (this._isLocked) {
  7969. return;
  7970. }
  7971. this.boundingBox._update(world);
  7972. this.boundingSphere._update(world);
  7973. };
  7974. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7975. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7976. return false;
  7977. return this.boundingBox.isInFrustum(frustumPlanes);
  7978. };
  7979. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7980. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7981. };
  7982. BoundingInfo.prototype._checkCollision = function (collider) {
  7983. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7984. };
  7985. BoundingInfo.prototype.intersectsPoint = function (point) {
  7986. if (!this.boundingSphere.centerWorld) {
  7987. return false;
  7988. }
  7989. if (!this.boundingSphere.intersectsPoint(point)) {
  7990. return false;
  7991. }
  7992. if (!this.boundingBox.intersectsPoint(point)) {
  7993. return false;
  7994. }
  7995. return true;
  7996. };
  7997. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7998. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7999. return false;
  8000. }
  8001. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  8002. return false;
  8003. }
  8004. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  8005. return false;
  8006. }
  8007. if (!precise) {
  8008. return true;
  8009. }
  8010. var box0 = this.boundingBox;
  8011. var box1 = boundingInfo.boundingBox;
  8012. if (!axisOverlap(box0.directions[0], box0, box1))
  8013. return false;
  8014. if (!axisOverlap(box0.directions[1], box0, box1))
  8015. return false;
  8016. if (!axisOverlap(box0.directions[2], box0, box1))
  8017. return false;
  8018. if (!axisOverlap(box1.directions[0], box0, box1))
  8019. return false;
  8020. if (!axisOverlap(box1.directions[1], box0, box1))
  8021. return false;
  8022. if (!axisOverlap(box1.directions[2], box0, box1))
  8023. return false;
  8024. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  8025. return false;
  8026. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  8027. return false;
  8028. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  8029. return false;
  8030. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  8031. return false;
  8032. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  8033. return false;
  8034. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  8035. return false;
  8036. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  8037. return false;
  8038. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  8039. return false;
  8040. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  8041. return false;
  8042. return true;
  8043. };
  8044. return BoundingInfo;
  8045. })();
  8046. BABYLON.BoundingInfo = BoundingInfo;
  8047. })(BABYLON || (BABYLON = {}));
  8048. var BABYLON;
  8049. (function (BABYLON) {
  8050. var Ray = (function () {
  8051. function Ray(origin, direction, length) {
  8052. if (length === void 0) { length = Number.MAX_VALUE; }
  8053. this.origin = origin;
  8054. this.direction = direction;
  8055. this.length = length;
  8056. }
  8057. // Methods
  8058. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  8059. var d = 0.0;
  8060. var maxValue = Number.MAX_VALUE;
  8061. var inv;
  8062. var min;
  8063. var max;
  8064. var temp;
  8065. if (Math.abs(this.direction.x) < 0.0000001) {
  8066. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  8067. return false;
  8068. }
  8069. }
  8070. else {
  8071. inv = 1.0 / this.direction.x;
  8072. min = (minimum.x - this.origin.x) * inv;
  8073. max = (maximum.x - this.origin.x) * inv;
  8074. if (max === -Infinity) {
  8075. max = Infinity;
  8076. }
  8077. if (min > max) {
  8078. temp = min;
  8079. min = max;
  8080. max = temp;
  8081. }
  8082. d = Math.max(min, d);
  8083. maxValue = Math.min(max, maxValue);
  8084. if (d > maxValue) {
  8085. return false;
  8086. }
  8087. }
  8088. if (Math.abs(this.direction.y) < 0.0000001) {
  8089. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  8090. return false;
  8091. }
  8092. }
  8093. else {
  8094. inv = 1.0 / this.direction.y;
  8095. min = (minimum.y - this.origin.y) * inv;
  8096. max = (maximum.y - this.origin.y) * inv;
  8097. if (max === -Infinity) {
  8098. max = Infinity;
  8099. }
  8100. if (min > max) {
  8101. temp = min;
  8102. min = max;
  8103. max = temp;
  8104. }
  8105. d = Math.max(min, d);
  8106. maxValue = Math.min(max, maxValue);
  8107. if (d > maxValue) {
  8108. return false;
  8109. }
  8110. }
  8111. if (Math.abs(this.direction.z) < 0.0000001) {
  8112. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  8113. return false;
  8114. }
  8115. }
  8116. else {
  8117. inv = 1.0 / this.direction.z;
  8118. min = (minimum.z - this.origin.z) * inv;
  8119. max = (maximum.z - this.origin.z) * inv;
  8120. if (max === -Infinity) {
  8121. max = Infinity;
  8122. }
  8123. if (min > max) {
  8124. temp = min;
  8125. min = max;
  8126. max = temp;
  8127. }
  8128. d = Math.max(min, d);
  8129. maxValue = Math.min(max, maxValue);
  8130. if (d > maxValue) {
  8131. return false;
  8132. }
  8133. }
  8134. return true;
  8135. };
  8136. Ray.prototype.intersectsBox = function (box) {
  8137. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  8138. };
  8139. Ray.prototype.intersectsSphere = function (sphere) {
  8140. var x = sphere.center.x - this.origin.x;
  8141. var y = sphere.center.y - this.origin.y;
  8142. var z = sphere.center.z - this.origin.z;
  8143. var pyth = (x * x) + (y * y) + (z * z);
  8144. var rr = sphere.radius * sphere.radius;
  8145. if (pyth <= rr) {
  8146. return true;
  8147. }
  8148. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  8149. if (dot < 0.0) {
  8150. return false;
  8151. }
  8152. var temp = pyth - (dot * dot);
  8153. return temp <= rr;
  8154. };
  8155. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  8156. if (!this._edge1) {
  8157. this._edge1 = BABYLON.Vector3.Zero();
  8158. this._edge2 = BABYLON.Vector3.Zero();
  8159. this._pvec = BABYLON.Vector3.Zero();
  8160. this._tvec = BABYLON.Vector3.Zero();
  8161. this._qvec = BABYLON.Vector3.Zero();
  8162. }
  8163. vertex1.subtractToRef(vertex0, this._edge1);
  8164. vertex2.subtractToRef(vertex0, this._edge2);
  8165. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  8166. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  8167. if (det === 0) {
  8168. return null;
  8169. }
  8170. var invdet = 1 / det;
  8171. this.origin.subtractToRef(vertex0, this._tvec);
  8172. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  8173. if (bu < 0 || bu > 1.0) {
  8174. return null;
  8175. }
  8176. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  8177. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  8178. if (bv < 0 || bu + bv > 1.0) {
  8179. return null;
  8180. }
  8181. //check if the distance is longer than the predefined length.
  8182. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  8183. if (distance > this.length) {
  8184. return null;
  8185. }
  8186. return new BABYLON.IntersectionInfo(bu, bv, distance);
  8187. };
  8188. Ray.prototype.intersectsPlane = function (plane) {
  8189. var distance;
  8190. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  8191. if (Math.abs(result1) < 9.99999997475243E-07) {
  8192. return null;
  8193. }
  8194. else {
  8195. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  8196. distance = (-plane.d - result2) / result1;
  8197. if (distance < 0.0) {
  8198. if (distance < -9.99999997475243E-07) {
  8199. return null;
  8200. }
  8201. else {
  8202. return 0;
  8203. }
  8204. }
  8205. return distance;
  8206. }
  8207. };
  8208. /**
  8209. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  8210. * @param sega the first point of the segment to test the intersection against
  8211. * @param segb the second point of the segment to test the intersection against
  8212. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  8213. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  8214. */
  8215. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  8216. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  8217. var u = segb.subtract(sega);
  8218. var v = rsegb.subtract(this.origin);
  8219. var w = sega.subtract(this.origin);
  8220. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  8221. var b = BABYLON.Vector3.Dot(u, v);
  8222. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  8223. var d = BABYLON.Vector3.Dot(u, w);
  8224. var e = BABYLON.Vector3.Dot(v, w);
  8225. var D = a * c - b * b; // always >= 0
  8226. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  8227. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  8228. // compute the line parameters of the two closest points
  8229. if (D < Ray.smallnum) {
  8230. sN = 0.0; // force using point P0 on segment S1
  8231. sD = 1.0; // to prevent possible division by 0.0 later
  8232. tN = e;
  8233. tD = c;
  8234. }
  8235. else {
  8236. sN = (b * e - c * d);
  8237. tN = (a * e - b * d);
  8238. if (sN < 0.0) {
  8239. sN = 0.0;
  8240. tN = e;
  8241. tD = c;
  8242. }
  8243. else if (sN > sD) {
  8244. sN = sD;
  8245. tN = e + b;
  8246. tD = c;
  8247. }
  8248. }
  8249. if (tN < 0.0) {
  8250. tN = 0.0;
  8251. // recompute sc for this edge
  8252. if (-d < 0.0) {
  8253. sN = 0.0;
  8254. }
  8255. else if (-d > a)
  8256. sN = sD;
  8257. else {
  8258. sN = -d;
  8259. sD = a;
  8260. }
  8261. }
  8262. else if (tN > tD) {
  8263. tN = tD;
  8264. // recompute sc for this edge
  8265. if ((-d + b) < 0.0) {
  8266. sN = 0;
  8267. }
  8268. else if ((-d + b) > a) {
  8269. sN = sD;
  8270. }
  8271. else {
  8272. sN = (-d + b);
  8273. sD = a;
  8274. }
  8275. }
  8276. // finally do the division to get sc and tc
  8277. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  8278. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  8279. // get the difference of the two closest points
  8280. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(v.multiplyByFloats(tc, tc, tc)); // = S1(sc) - S2(tc)
  8281. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  8282. if (isIntersected) {
  8283. return tc;
  8284. }
  8285. return -1;
  8286. };
  8287. // Statics
  8288. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  8289. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  8290. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  8291. var direction = end.subtract(start);
  8292. direction.normalize();
  8293. return new Ray(start, direction);
  8294. };
  8295. /**
  8296. * 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
  8297. * transformed to the given world matrix.
  8298. * @param origin The origin point
  8299. * @param end The end point
  8300. * @param world a matrix to transform the ray to. Default is the identity matrix.
  8301. */
  8302. Ray.CreateNewFromTo = function (origin, end, world) {
  8303. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  8304. var direction = end.subtract(origin);
  8305. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  8306. direction.normalize();
  8307. return Ray.Transform(new Ray(origin, direction, length), world);
  8308. };
  8309. Ray.Transform = function (ray, matrix) {
  8310. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  8311. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  8312. newDirection.normalize();
  8313. return new Ray(newOrigin, newDirection, ray.length);
  8314. };
  8315. Ray.smallnum = 0.00000001;
  8316. Ray.rayl = 10e8;
  8317. return Ray;
  8318. })();
  8319. BABYLON.Ray = Ray;
  8320. })(BABYLON || (BABYLON = {}));
  8321. var BABYLON;
  8322. (function (BABYLON) {
  8323. var AbstractMesh = (function (_super) {
  8324. __extends(AbstractMesh, _super);
  8325. // Constructor
  8326. function AbstractMesh(name, scene) {
  8327. var _this = this;
  8328. _super.call(this, name, scene);
  8329. // Events
  8330. /**
  8331. * An event triggered when this mesh collides with another one
  8332. * @type {BABYLON.Observable}
  8333. */
  8334. this.onCollideObservable = new BABYLON.Observable();
  8335. /**
  8336. * An event triggered when the collision's position changes
  8337. * @type {BABYLON.Observable}
  8338. */
  8339. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  8340. /**
  8341. * An event triggered after the world matrix is updated
  8342. * @type {BABYLON.Observable}
  8343. */
  8344. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  8345. // Properties
  8346. this.definedFacingForward = true; // orientation for POV movement & rotation
  8347. this.position = new BABYLON.Vector3(0, 0, 0);
  8348. this._rotation = new BABYLON.Vector3(0, 0, 0);
  8349. this._scaling = new BABYLON.Vector3(1, 1, 1);
  8350. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8351. this.visibility = 1.0;
  8352. this.alphaIndex = Number.MAX_VALUE;
  8353. this.infiniteDistance = false;
  8354. this.isVisible = true;
  8355. this.isPickable = true;
  8356. this.showBoundingBox = false;
  8357. this.showSubMeshesBoundingBox = false;
  8358. this.onDispose = null;
  8359. this.isBlocker = false;
  8360. this.renderingGroupId = 0;
  8361. this.receiveShadows = false;
  8362. this.renderOutline = false;
  8363. this.outlineColor = BABYLON.Color3.Red();
  8364. this.outlineWidth = 0.02;
  8365. this.renderOverlay = false;
  8366. this.overlayColor = BABYLON.Color3.Red();
  8367. this.overlayAlpha = 0.5;
  8368. this.hasVertexAlpha = false;
  8369. this.useVertexColors = true;
  8370. this.applyFog = true;
  8371. this.computeBonesUsingShaders = true;
  8372. this.scalingDeterminant = 1;
  8373. this.numBoneInfluencers = 4;
  8374. this.useOctreeForRenderingSelection = true;
  8375. this.useOctreeForPicking = true;
  8376. this.useOctreeForCollisions = true;
  8377. this.layerMask = 0x0FFFFFFF;
  8378. this.alwaysSelectAsActiveMesh = false;
  8379. // Collisions
  8380. this._checkCollisions = false;
  8381. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8382. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8383. this._collider = new BABYLON.Collider();
  8384. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8385. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8386. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8387. // Edges
  8388. this.edgesWidth = 1;
  8389. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  8390. // Cache
  8391. this._localWorld = BABYLON.Matrix.Zero();
  8392. this._worldMatrix = BABYLON.Matrix.Zero();
  8393. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8394. this._absolutePosition = BABYLON.Vector3.Zero();
  8395. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8396. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8397. this._isDirty = false;
  8398. this._pivotMatrix = BABYLON.Matrix.Identity();
  8399. this._isDisposed = false;
  8400. this._renderId = 0;
  8401. this._intersectionsInProgress = new Array();
  8402. this._isWorldMatrixFrozen = false;
  8403. this._unIndexed = false;
  8404. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  8405. if (collidedMesh === void 0) { collidedMesh = null; }
  8406. //TODO move this to the collision coordinator!
  8407. if (_this.getScene().workerCollisions)
  8408. newPosition.multiplyInPlace(_this._collider.radius);
  8409. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  8410. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8411. _this.position.addInPlace(_this._diffPositionForCollisions);
  8412. }
  8413. if (collidedMesh) {
  8414. _this.onCollideObservable.notifyObservers(collidedMesh);
  8415. }
  8416. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  8417. };
  8418. scene.addMesh(this);
  8419. }
  8420. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8421. get: function () {
  8422. return AbstractMesh._BILLBOARDMODE_NONE;
  8423. },
  8424. enumerable: true,
  8425. configurable: true
  8426. });
  8427. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8428. get: function () {
  8429. return AbstractMesh._BILLBOARDMODE_X;
  8430. },
  8431. enumerable: true,
  8432. configurable: true
  8433. });
  8434. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8435. get: function () {
  8436. return AbstractMesh._BILLBOARDMODE_Y;
  8437. },
  8438. enumerable: true,
  8439. configurable: true
  8440. });
  8441. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8442. get: function () {
  8443. return AbstractMesh._BILLBOARDMODE_Z;
  8444. },
  8445. enumerable: true,
  8446. configurable: true
  8447. });
  8448. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8449. get: function () {
  8450. return AbstractMesh._BILLBOARDMODE_ALL;
  8451. },
  8452. enumerable: true,
  8453. configurable: true
  8454. });
  8455. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  8456. set: function (callback) {
  8457. if (this._onCollideObserver) {
  8458. this.onCollideObservable.remove(this._onCollideObserver);
  8459. }
  8460. this._onCollideObserver = this.onCollideObservable.add(callback);
  8461. },
  8462. enumerable: true,
  8463. configurable: true
  8464. });
  8465. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  8466. set: function (callback) {
  8467. if (this._onCollisionPositionChangeObserver) {
  8468. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  8469. }
  8470. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  8471. },
  8472. enumerable: true,
  8473. configurable: true
  8474. });
  8475. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  8476. get: function () {
  8477. return this._skeleton;
  8478. },
  8479. set: function (value) {
  8480. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  8481. this._skeleton._unregisterMeshWithPoseMatrix(this);
  8482. }
  8483. if (value && value.needInitialSkinMatrix) {
  8484. value._registerMeshWithPoseMatrix(this);
  8485. }
  8486. this._skeleton = value;
  8487. if (!this._skeleton) {
  8488. this._bonesTransformMatrices = null;
  8489. }
  8490. },
  8491. enumerable: true,
  8492. configurable: true
  8493. });
  8494. /**
  8495. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  8496. */
  8497. AbstractMesh.prototype.toString = function (fullDetails) {
  8498. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  8499. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  8500. if (this._skeleton) {
  8501. ret += ", skeleton: " + this._skeleton.name;
  8502. }
  8503. if (fullDetails) {
  8504. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  8505. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  8506. }
  8507. return ret;
  8508. };
  8509. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  8510. /**
  8511. * Getting the rotation object.
  8512. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  8513. */
  8514. get: function () {
  8515. return this._rotation;
  8516. },
  8517. set: function (newRotation) {
  8518. this._rotation = newRotation;
  8519. },
  8520. enumerable: true,
  8521. configurable: true
  8522. });
  8523. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  8524. get: function () {
  8525. return this._scaling;
  8526. },
  8527. set: function (newScaling) {
  8528. this._scaling = newScaling;
  8529. if (this.physicsImpostor) {
  8530. this.physicsImpostor.forceUpdate();
  8531. }
  8532. },
  8533. enumerable: true,
  8534. configurable: true
  8535. });
  8536. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  8537. get: function () {
  8538. return this._rotationQuaternion;
  8539. },
  8540. set: function (quaternion) {
  8541. this._rotationQuaternion = quaternion;
  8542. //reset the rotation vector.
  8543. if (quaternion && this.rotation.length()) {
  8544. this.rotation.copyFromFloats(0, 0, 0);
  8545. }
  8546. },
  8547. enumerable: true,
  8548. configurable: true
  8549. });
  8550. // Methods
  8551. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  8552. this._poseMatrix.copyFrom(matrix);
  8553. };
  8554. AbstractMesh.prototype.getPoseMatrix = function () {
  8555. return this._poseMatrix;
  8556. };
  8557. AbstractMesh.prototype.disableEdgesRendering = function () {
  8558. if (this._edgesRenderer !== undefined) {
  8559. this._edgesRenderer.dispose();
  8560. this._edgesRenderer = undefined;
  8561. }
  8562. };
  8563. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  8564. if (epsilon === void 0) { epsilon = 0.95; }
  8565. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  8566. this.disableEdgesRendering();
  8567. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  8568. };
  8569. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8570. get: function () {
  8571. return false;
  8572. },
  8573. enumerable: true,
  8574. configurable: true
  8575. });
  8576. AbstractMesh.prototype.getLOD = function (camera) {
  8577. return this;
  8578. };
  8579. AbstractMesh.prototype.getTotalVertices = function () {
  8580. return 0;
  8581. };
  8582. AbstractMesh.prototype.getIndices = function () {
  8583. return null;
  8584. };
  8585. AbstractMesh.prototype.getVerticesData = function (kind) {
  8586. return null;
  8587. };
  8588. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8589. return false;
  8590. };
  8591. AbstractMesh.prototype.getBoundingInfo = function () {
  8592. if (this._masterMesh) {
  8593. return this._masterMesh.getBoundingInfo();
  8594. }
  8595. if (!this._boundingInfo) {
  8596. this._updateBoundingInfo();
  8597. }
  8598. return this._boundingInfo;
  8599. };
  8600. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  8601. get: function () {
  8602. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  8603. },
  8604. enumerable: true,
  8605. configurable: true
  8606. });
  8607. AbstractMesh.prototype._preActivate = function () {
  8608. };
  8609. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  8610. };
  8611. AbstractMesh.prototype._activate = function (renderId) {
  8612. this._renderId = renderId;
  8613. };
  8614. AbstractMesh.prototype.getWorldMatrix = function () {
  8615. if (this._masterMesh) {
  8616. return this._masterMesh.getWorldMatrix();
  8617. }
  8618. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8619. this.computeWorldMatrix();
  8620. }
  8621. return this._worldMatrix;
  8622. };
  8623. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8624. get: function () {
  8625. return this._worldMatrix;
  8626. },
  8627. enumerable: true,
  8628. configurable: true
  8629. });
  8630. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8631. get: function () {
  8632. return this._absolutePosition;
  8633. },
  8634. enumerable: true,
  8635. configurable: true
  8636. });
  8637. AbstractMesh.prototype.freezeWorldMatrix = function () {
  8638. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  8639. this.computeWorldMatrix(true);
  8640. this._isWorldMatrixFrozen = true;
  8641. };
  8642. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  8643. this._isWorldMatrixFrozen = false;
  8644. this.computeWorldMatrix(true);
  8645. };
  8646. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  8647. get: function () {
  8648. return this._isWorldMatrixFrozen;
  8649. },
  8650. enumerable: true,
  8651. configurable: true
  8652. });
  8653. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8654. axis.normalize();
  8655. if (!this.rotationQuaternion) {
  8656. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8657. this.rotation = BABYLON.Vector3.Zero();
  8658. }
  8659. var rotationQuaternion;
  8660. if (!space || space === BABYLON.Space.LOCAL) {
  8661. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8662. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8663. }
  8664. else {
  8665. if (this.parent) {
  8666. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8667. invertParentWorldMatrix.invert();
  8668. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8669. }
  8670. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8671. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8672. }
  8673. };
  8674. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8675. var displacementVector = axis.scale(distance);
  8676. if (!space || space === BABYLON.Space.LOCAL) {
  8677. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8678. this.setPositionWithLocalVector(tempV3);
  8679. }
  8680. else {
  8681. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8682. }
  8683. };
  8684. AbstractMesh.prototype.getAbsolutePosition = function () {
  8685. this.computeWorldMatrix();
  8686. return this._absolutePosition;
  8687. };
  8688. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8689. if (!absolutePosition) {
  8690. return;
  8691. }
  8692. var absolutePositionX;
  8693. var absolutePositionY;
  8694. var absolutePositionZ;
  8695. if (absolutePosition.x === undefined) {
  8696. if (arguments.length < 3) {
  8697. return;
  8698. }
  8699. absolutePositionX = arguments[0];
  8700. absolutePositionY = arguments[1];
  8701. absolutePositionZ = arguments[2];
  8702. }
  8703. else {
  8704. absolutePositionX = absolutePosition.x;
  8705. absolutePositionY = absolutePosition.y;
  8706. absolutePositionZ = absolutePosition.z;
  8707. }
  8708. if (this.parent) {
  8709. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8710. invertParentWorldMatrix.invert();
  8711. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8712. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8713. }
  8714. else {
  8715. this.position.x = absolutePositionX;
  8716. this.position.y = absolutePositionY;
  8717. this.position.z = absolutePositionZ;
  8718. }
  8719. };
  8720. // ================================== Point of View Movement =================================
  8721. /**
  8722. * Perform relative position change from the point of view of behind the front of the mesh.
  8723. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8724. * Supports definition of mesh facing forward or backward.
  8725. * @param {number} amountRight
  8726. * @param {number} amountUp
  8727. * @param {number} amountForward
  8728. */
  8729. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  8730. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  8731. };
  8732. /**
  8733. * Calculate relative position change from the point of view of behind the front of the mesh.
  8734. * This is performed taking into account the meshes current rotation, so you do not have to care.
  8735. * Supports definition of mesh facing forward or backward.
  8736. * @param {number} amountRight
  8737. * @param {number} amountUp
  8738. * @param {number} amountForward
  8739. */
  8740. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  8741. var rotMatrix = new BABYLON.Matrix();
  8742. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8743. rotQuaternion.toRotationMatrix(rotMatrix);
  8744. var translationDelta = BABYLON.Vector3.Zero();
  8745. var defForwardMult = this.definedFacingForward ? -1 : 1;
  8746. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  8747. return translationDelta;
  8748. };
  8749. // ================================== Point of View Rotation =================================
  8750. /**
  8751. * Perform relative rotation change from the point of view of behind the front of the mesh.
  8752. * Supports definition of mesh facing forward or backward.
  8753. * @param {number} flipBack
  8754. * @param {number} twirlClockwise
  8755. * @param {number} tiltRight
  8756. */
  8757. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8758. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  8759. };
  8760. /**
  8761. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  8762. * Supports definition of mesh facing forward or backward.
  8763. * @param {number} flipBack
  8764. * @param {number} twirlClockwise
  8765. * @param {number} tiltRight
  8766. */
  8767. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  8768. var defForwardMult = this.definedFacingForward ? 1 : -1;
  8769. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  8770. };
  8771. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8772. this._pivotMatrix = matrix;
  8773. this._cache.pivotMatrixUpdated = true;
  8774. };
  8775. AbstractMesh.prototype.getPivotMatrix = function () {
  8776. return this._pivotMatrix;
  8777. };
  8778. AbstractMesh.prototype._isSynchronized = function () {
  8779. if (this._isDirty) {
  8780. return false;
  8781. }
  8782. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8783. return false;
  8784. if (this._cache.pivotMatrixUpdated) {
  8785. return false;
  8786. }
  8787. if (this.infiniteDistance) {
  8788. return false;
  8789. }
  8790. if (!this._cache.position.equals(this.position))
  8791. return false;
  8792. if (this.rotationQuaternion) {
  8793. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8794. return false;
  8795. }
  8796. else {
  8797. if (!this._cache.rotation.equals(this.rotation))
  8798. return false;
  8799. }
  8800. if (!this._cache.scaling.equals(this.scaling))
  8801. return false;
  8802. return true;
  8803. };
  8804. AbstractMesh.prototype._initCache = function () {
  8805. _super.prototype._initCache.call(this);
  8806. this._cache.localMatrixUpdated = false;
  8807. this._cache.position = BABYLON.Vector3.Zero();
  8808. this._cache.scaling = BABYLON.Vector3.Zero();
  8809. this._cache.rotation = BABYLON.Vector3.Zero();
  8810. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8811. this._cache.billboardMode = -1;
  8812. };
  8813. AbstractMesh.prototype.markAsDirty = function (property) {
  8814. if (property === "rotation") {
  8815. this.rotationQuaternion = null;
  8816. }
  8817. this._currentRenderId = Number.MAX_VALUE;
  8818. this._isDirty = true;
  8819. };
  8820. AbstractMesh.prototype._updateBoundingInfo = function () {
  8821. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8822. this._boundingInfo.update(this.worldMatrixFromCache);
  8823. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8824. };
  8825. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8826. if (!this.subMeshes) {
  8827. return;
  8828. }
  8829. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8830. var subMesh = this.subMeshes[subIndex];
  8831. if (!subMesh.IsGlobal) {
  8832. subMesh.updateBoundingInfo(matrix);
  8833. }
  8834. }
  8835. };
  8836. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8837. if (this._isWorldMatrixFrozen) {
  8838. return this._worldMatrix;
  8839. }
  8840. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  8841. this._currentRenderId = this.getScene().getRenderId();
  8842. return this._worldMatrix;
  8843. }
  8844. this._cache.position.copyFrom(this.position);
  8845. this._cache.scaling.copyFrom(this.scaling);
  8846. this._cache.pivotMatrixUpdated = false;
  8847. this._cache.billboardMode = this.billboardMode;
  8848. this._currentRenderId = this.getScene().getRenderId();
  8849. this._isDirty = false;
  8850. // Scaling
  8851. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  8852. // Rotation
  8853. //rotate, if quaternion is set and rotation was used
  8854. if (this.rotationQuaternion) {
  8855. var len = this.rotation.length();
  8856. if (len) {
  8857. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  8858. this.rotation.copyFromFloats(0, 0, 0);
  8859. }
  8860. }
  8861. if (this.rotationQuaternion) {
  8862. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  8863. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8864. }
  8865. else {
  8866. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  8867. this._cache.rotation.copyFrom(this.rotation);
  8868. }
  8869. // Translation
  8870. if (this.infiniteDistance && !this.parent) {
  8871. var camera = this.getScene().activeCamera;
  8872. if (camera) {
  8873. var cameraWorldMatrix = camera.getWorldMatrix();
  8874. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8875. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  8876. }
  8877. }
  8878. else {
  8879. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  8880. }
  8881. // Composing transformations
  8882. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  8883. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  8884. // Billboarding
  8885. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8886. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  8887. var localPosition = BABYLON.Tmp.Vector3[0];
  8888. if (this.parent && this.parent.getWorldMatrix) {
  8889. this._markSyncedWithParent();
  8890. var parentMatrix;
  8891. if (this._meshToBoneReferal) {
  8892. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8893. parentMatrix = BABYLON.Tmp.Matrix[6];
  8894. }
  8895. else {
  8896. parentMatrix = this.parent.getWorldMatrix();
  8897. }
  8898. BABYLON.Vector3.TransformCoordinatesToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  8899. localPosition = BABYLON.Tmp.Vector3[1];
  8900. }
  8901. var zero = this.getScene().activeCamera.globalPosition.clone();
  8902. if (this.parent && this.parent.position) {
  8903. localPosition.addInPlace(this.parent.position);
  8904. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  8905. }
  8906. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  8907. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  8908. zero.x = localPosition.x + BABYLON.Epsilon;
  8909. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  8910. zero.y = localPosition.y + BABYLON.Epsilon;
  8911. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  8912. zero.z = localPosition.z + BABYLON.Epsilon;
  8913. }
  8914. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  8915. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  8916. BABYLON.Tmp.Matrix[3].invert();
  8917. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  8918. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  8919. }
  8920. // Local world
  8921. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  8922. // Parent
  8923. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  8924. this._markSyncedWithParent();
  8925. if (this._meshToBoneReferal) {
  8926. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  8927. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  8928. }
  8929. else {
  8930. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8931. }
  8932. }
  8933. else {
  8934. this._worldMatrix.copyFrom(this._localWorld);
  8935. }
  8936. // Bounding info
  8937. this._updateBoundingInfo();
  8938. // Absolute position
  8939. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8940. // Callbacks
  8941. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  8942. if (!this._poseMatrix) {
  8943. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  8944. }
  8945. return this._worldMatrix;
  8946. };
  8947. /**
  8948. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8949. * @param func: callback function to add
  8950. */
  8951. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8952. this.onAfterWorldMatrixUpdateObservable.add(func);
  8953. };
  8954. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8955. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  8956. };
  8957. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8958. this.computeWorldMatrix();
  8959. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8960. };
  8961. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8962. this.computeWorldMatrix();
  8963. var invLocalWorldMatrix = this._localWorld.clone();
  8964. invLocalWorldMatrix.invert();
  8965. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8966. };
  8967. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8968. this.computeWorldMatrix(true);
  8969. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8970. };
  8971. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8972. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8973. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8974. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8975. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8976. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8977. /// <returns>Mesh oriented towards targetMesh</returns>
  8978. yawCor = yawCor || 0; // default to zero if undefined
  8979. pitchCor = pitchCor || 0;
  8980. rollCor = rollCor || 0;
  8981. var dv = targetPoint.subtract(this.position);
  8982. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8983. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8984. var pitch = Math.atan2(dv.y, len);
  8985. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8986. };
  8987. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  8988. this._meshToBoneReferal = affectedMesh;
  8989. this.parent = bone;
  8990. if (bone.getWorldMatrix().determinant() < 0) {
  8991. this.scalingDeterminant *= -1;
  8992. }
  8993. };
  8994. AbstractMesh.prototype.detachFromBone = function () {
  8995. if (this.parent.getWorldMatrix().determinant() < 0) {
  8996. this.scalingDeterminant *= -1;
  8997. }
  8998. this._meshToBoneReferal = null;
  8999. this.parent = null;
  9000. };
  9001. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9002. return this._boundingInfo.isInFrustum(frustumPlanes);
  9003. };
  9004. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9005. if (!camera) {
  9006. camera = this.getScene().activeCamera;
  9007. }
  9008. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9009. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9010. return false;
  9011. }
  9012. return true;
  9013. };
  9014. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9015. if (!this._boundingInfo || !mesh._boundingInfo) {
  9016. return false;
  9017. }
  9018. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9019. };
  9020. AbstractMesh.prototype.intersectsPoint = function (point) {
  9021. if (!this._boundingInfo) {
  9022. return false;
  9023. }
  9024. return this._boundingInfo.intersectsPoint(point);
  9025. };
  9026. // Physics
  9027. /**
  9028. * @Deprecated. Use new PhysicsImpostor instead.
  9029. * */
  9030. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9031. //legacy support
  9032. if (impostor.impostor) {
  9033. options = impostor;
  9034. impostor = impostor.impostor;
  9035. }
  9036. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  9037. return this.physicsImpostor.physicsBody;
  9038. };
  9039. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9040. return this.physicsImpostor;
  9041. };
  9042. /**
  9043. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  9044. */
  9045. AbstractMesh.prototype.getPhysicsMass = function () {
  9046. return this.physicsImpostor.getParam("mass");
  9047. };
  9048. /**
  9049. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  9050. */
  9051. AbstractMesh.prototype.getPhysicsFriction = function () {
  9052. return this.physicsImpostor.getParam("friction");
  9053. };
  9054. /**
  9055. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  9056. */
  9057. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9058. return this.physicsImpostor.getParam("resitution");
  9059. };
  9060. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9061. if (!camera) {
  9062. camera = this.getScene().activeCamera;
  9063. }
  9064. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9065. };
  9066. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9067. if (!camera) {
  9068. camera = this.getScene().activeCamera;
  9069. }
  9070. return this.absolutePosition.subtract(camera.position).length();
  9071. };
  9072. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9073. if (!this.physicsImpostor) {
  9074. return;
  9075. }
  9076. this.physicsImpostor.applyImpulse(force, contactPoint);
  9077. };
  9078. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9079. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  9080. return;
  9081. }
  9082. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  9083. mainPivot: pivot1,
  9084. connectedPivot: pivot2,
  9085. nativeParams: options
  9086. });
  9087. };
  9088. /**
  9089. * @Deprecated
  9090. */
  9091. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9092. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  9093. this.updatePhysicsBody();
  9094. };
  9095. /**
  9096. * @Deprecated
  9097. * Calling this function is not needed anymore.
  9098. * The physics engine takes care of transofmration automatically.
  9099. */
  9100. AbstractMesh.prototype.updatePhysicsBody = function () {
  9101. //Unneeded
  9102. };
  9103. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  9104. // Collisions
  9105. get: function () {
  9106. return this._checkCollisions;
  9107. },
  9108. set: function (collisionEnabled) {
  9109. this._checkCollisions = collisionEnabled;
  9110. if (this.getScene().workerCollisions) {
  9111. this.getScene().collisionCoordinator.onMeshUpdated(this);
  9112. }
  9113. },
  9114. enumerable: true,
  9115. configurable: true
  9116. });
  9117. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9118. var globalPosition = this.getAbsolutePosition();
  9119. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9120. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9121. this._collider.radius = this.ellipsoid;
  9122. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  9123. };
  9124. // Submeshes octree
  9125. /**
  9126. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9127. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9128. */
  9129. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9130. if (maxCapacity === void 0) { maxCapacity = 64; }
  9131. if (maxDepth === void 0) { maxDepth = 2; }
  9132. if (!this._submeshesOctree) {
  9133. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9134. }
  9135. this.computeWorldMatrix(true);
  9136. // Update octree
  9137. var bbox = this.getBoundingInfo().boundingBox;
  9138. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9139. return this._submeshesOctree;
  9140. };
  9141. // Collisions
  9142. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9143. this._generatePointsArray();
  9144. // Transformation
  9145. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9146. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9147. subMesh._lastColliderWorldVertices = [];
  9148. subMesh._trianglePlanes = [];
  9149. var start = subMesh.verticesStart;
  9150. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9151. for (var i = start; i < end; i++) {
  9152. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9153. }
  9154. }
  9155. // Collide
  9156. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  9157. if (collider.collisionFound) {
  9158. collider.collidedMesh = this;
  9159. }
  9160. };
  9161. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9162. var subMeshes;
  9163. var len;
  9164. // Octrees
  9165. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9166. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9167. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9168. len = intersections.length;
  9169. subMeshes = intersections.data;
  9170. }
  9171. else {
  9172. subMeshes = this.subMeshes;
  9173. len = subMeshes.length;
  9174. }
  9175. for (var index = 0; index < len; index++) {
  9176. var subMesh = subMeshes[index];
  9177. // Bounding test
  9178. if (len > 1 && !subMesh._checkCollision(collider))
  9179. continue;
  9180. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9181. }
  9182. };
  9183. AbstractMesh.prototype._checkCollision = function (collider) {
  9184. // Bounding box test
  9185. if (!this._boundingInfo._checkCollision(collider))
  9186. return;
  9187. // Transformation matrix
  9188. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9189. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9190. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9191. };
  9192. // Picking
  9193. AbstractMesh.prototype._generatePointsArray = function () {
  9194. return false;
  9195. };
  9196. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9197. var pickingInfo = new BABYLON.PickingInfo();
  9198. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9199. return pickingInfo;
  9200. }
  9201. if (!this._generatePointsArray()) {
  9202. return pickingInfo;
  9203. }
  9204. var intersectInfo = null;
  9205. // Octrees
  9206. var subMeshes;
  9207. var len;
  9208. if (this._submeshesOctree && this.useOctreeForPicking) {
  9209. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9210. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9211. len = intersections.length;
  9212. subMeshes = intersections.data;
  9213. }
  9214. else {
  9215. subMeshes = this.subMeshes;
  9216. len = subMeshes.length;
  9217. }
  9218. for (var index = 0; index < len; index++) {
  9219. var subMesh = subMeshes[index];
  9220. // Bounding test
  9221. if (len > 1 && !subMesh.canIntersects(ray))
  9222. continue;
  9223. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9224. if (currentIntersectInfo) {
  9225. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9226. intersectInfo = currentIntersectInfo;
  9227. intersectInfo.subMeshId = index;
  9228. if (fastCheck) {
  9229. break;
  9230. }
  9231. }
  9232. }
  9233. }
  9234. if (intersectInfo) {
  9235. // Get picked point
  9236. var world = this.getWorldMatrix();
  9237. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9238. var direction = ray.direction.clone();
  9239. direction = direction.scale(intersectInfo.distance);
  9240. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9241. var pickedPoint = worldOrigin.add(worldDirection);
  9242. // Return result
  9243. pickingInfo.hit = true;
  9244. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9245. pickingInfo.pickedPoint = pickedPoint;
  9246. pickingInfo.pickedMesh = this;
  9247. pickingInfo.bu = intersectInfo.bu;
  9248. pickingInfo.bv = intersectInfo.bv;
  9249. pickingInfo.faceId = intersectInfo.faceId;
  9250. pickingInfo.subMeshId = intersectInfo.subMeshId;
  9251. return pickingInfo;
  9252. }
  9253. return pickingInfo;
  9254. };
  9255. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9256. return null;
  9257. };
  9258. AbstractMesh.prototype.releaseSubMeshes = function () {
  9259. if (this.subMeshes) {
  9260. while (this.subMeshes.length) {
  9261. this.subMeshes[0].dispose();
  9262. }
  9263. }
  9264. else {
  9265. this.subMeshes = new Array();
  9266. }
  9267. };
  9268. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9269. var _this = this;
  9270. var index;
  9271. // Action manager
  9272. if (this.actionManager) {
  9273. this.actionManager.dispose();
  9274. this.actionManager = null;
  9275. }
  9276. // Skeleton
  9277. this.skeleton = null;
  9278. // Animations
  9279. this.getScene().stopAnimation(this);
  9280. // Physics
  9281. if (this.physicsImpostor) {
  9282. this.physicsImpostor.dispose();
  9283. }
  9284. // Intersections in progress
  9285. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9286. var other = this._intersectionsInProgress[index];
  9287. var pos = other._intersectionsInProgress.indexOf(this);
  9288. other._intersectionsInProgress.splice(pos, 1);
  9289. }
  9290. this._intersectionsInProgress = [];
  9291. // Lights
  9292. var lights = this.getScene().lights;
  9293. lights.forEach(function (light) {
  9294. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  9295. if (meshIndex !== -1) {
  9296. light.includedOnlyMeshes.splice(meshIndex, 1);
  9297. }
  9298. meshIndex = light.excludedMeshes.indexOf(_this);
  9299. if (meshIndex !== -1) {
  9300. light.excludedMeshes.splice(meshIndex, 1);
  9301. }
  9302. });
  9303. // Edges
  9304. if (this._edgesRenderer) {
  9305. this._edgesRenderer.dispose();
  9306. this._edgesRenderer = null;
  9307. }
  9308. // SubMeshes
  9309. this.releaseSubMeshes();
  9310. // Remove from scene
  9311. this.getScene().removeMesh(this);
  9312. if (!doNotRecurse) {
  9313. // Particles
  9314. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9315. if (this.getScene().particleSystems[index].emitter === this) {
  9316. this.getScene().particleSystems[index].dispose();
  9317. index--;
  9318. }
  9319. }
  9320. // Children
  9321. var objects = this.getDescendants(true);
  9322. for (index = 0; index < objects.length; index++) {
  9323. objects[index].dispose();
  9324. }
  9325. }
  9326. else {
  9327. var childMeshes = this.getChildMeshes(true);
  9328. for (index = 0; index < childMeshes.length; index++) {
  9329. var child = childMeshes[index];
  9330. child.parent = null;
  9331. child.computeWorldMatrix(true);
  9332. }
  9333. }
  9334. _super.prototype.dispose.call(this);
  9335. this.onAfterWorldMatrixUpdateObservable.clear();
  9336. this._isDisposed = true;
  9337. // Callback
  9338. if (this.onDispose) {
  9339. this.onDispose();
  9340. }
  9341. };
  9342. // Statics
  9343. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9344. AbstractMesh._BILLBOARDMODE_X = 1;
  9345. AbstractMesh._BILLBOARDMODE_Y = 2;
  9346. AbstractMesh._BILLBOARDMODE_Z = 4;
  9347. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9348. return AbstractMesh;
  9349. })(BABYLON.Node);
  9350. BABYLON.AbstractMesh = AbstractMesh;
  9351. })(BABYLON || (BABYLON = {}));
  9352. var BABYLON;
  9353. (function (BABYLON) {
  9354. var Light = (function (_super) {
  9355. __extends(Light, _super);
  9356. function Light(name, scene) {
  9357. _super.call(this, name, scene);
  9358. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  9359. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  9360. this.intensity = 1.0;
  9361. this.range = Number.MAX_VALUE;
  9362. this.includeOnlyWithLayerMask = 0;
  9363. this.includedOnlyMeshes = new Array();
  9364. this.excludedMeshes = new Array();
  9365. this.excludeWithLayerMask = 0;
  9366. // PBR Properties.
  9367. this.radius = 0.00001;
  9368. this._excludedMeshesIds = new Array();
  9369. this._includedOnlyMeshesIds = new Array();
  9370. scene.addLight(this);
  9371. }
  9372. /**
  9373. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9374. */
  9375. Light.prototype.toString = function (fullDetails) {
  9376. var ret = "Name: " + this.name;
  9377. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  9378. if (this.animations) {
  9379. for (var i = 0; i < this.animations.length; i++) {
  9380. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  9381. }
  9382. }
  9383. if (fullDetails) {
  9384. }
  9385. return ret;
  9386. };
  9387. Light.prototype.getShadowGenerator = function () {
  9388. return this._shadowGenerator;
  9389. };
  9390. Light.prototype.getAbsolutePosition = function () {
  9391. return BABYLON.Vector3.Zero();
  9392. };
  9393. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  9394. };
  9395. Light.prototype._getWorldMatrix = function () {
  9396. return BABYLON.Matrix.Identity();
  9397. };
  9398. Light.prototype.canAffectMesh = function (mesh) {
  9399. if (!mesh) {
  9400. return true;
  9401. }
  9402. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  9403. return false;
  9404. }
  9405. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  9406. return false;
  9407. }
  9408. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  9409. return false;
  9410. }
  9411. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  9412. return false;
  9413. }
  9414. return true;
  9415. };
  9416. Light.prototype.getWorldMatrix = function () {
  9417. this._currentRenderId = this.getScene().getRenderId();
  9418. var worldMatrix = this._getWorldMatrix();
  9419. if (this.parent && this.parent.getWorldMatrix) {
  9420. if (!this._parentedWorldMatrix) {
  9421. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  9422. }
  9423. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  9424. this._markSyncedWithParent();
  9425. return this._parentedWorldMatrix;
  9426. }
  9427. return worldMatrix;
  9428. };
  9429. Light.prototype.dispose = function () {
  9430. if (this._shadowGenerator) {
  9431. this._shadowGenerator.dispose();
  9432. this._shadowGenerator = null;
  9433. }
  9434. // Animations
  9435. this.getScene().stopAnimation(this);
  9436. // Remove from scene
  9437. this.getScene().removeLight(this);
  9438. _super.prototype.dispose.call(this);
  9439. };
  9440. Light.prototype.getTypeID = function () {
  9441. return 0;
  9442. };
  9443. Light.prototype.clone = function (name) {
  9444. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  9445. };
  9446. Light.prototype.serialize = function () {
  9447. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  9448. // Type
  9449. serializationObject.type = this.getTypeID();
  9450. // Parent
  9451. if (this.parent) {
  9452. serializationObject.parentId = this.parent.id;
  9453. }
  9454. // Inclusion / exclusions
  9455. if (this.excludedMeshes.length > 0) {
  9456. serializationObject.excludedMeshesIds = [];
  9457. this.excludedMeshes.forEach(function (mesh) {
  9458. serializationObject.excludedMeshesIds.push(mesh.id);
  9459. });
  9460. }
  9461. if (this.includedOnlyMeshes.length > 0) {
  9462. serializationObject.includedOnlyMeshesIds = [];
  9463. this.includedOnlyMeshes.forEach(function (mesh) {
  9464. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  9465. });
  9466. }
  9467. // Animations
  9468. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  9469. serializationObject.ranges = this.serializeAnimationRanges();
  9470. return serializationObject;
  9471. };
  9472. Light.GetConstructorFromName = function (type, name, scene) {
  9473. switch (type) {
  9474. case 0:
  9475. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  9476. case 1:
  9477. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  9478. case 2:
  9479. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  9480. case 3:
  9481. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  9482. }
  9483. };
  9484. Light.Parse = function (parsedLight, scene) {
  9485. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  9486. // Inclusion / exclusions
  9487. if (parsedLight.excludedMeshesIds) {
  9488. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  9489. }
  9490. if (parsedLight.includedOnlyMeshesIds) {
  9491. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  9492. }
  9493. // Parent
  9494. if (parsedLight.parentId) {
  9495. light._waitingParentId = parsedLight.parentId;
  9496. }
  9497. // Animations
  9498. if (parsedLight.animations) {
  9499. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  9500. var parsedAnimation = parsedLight.animations[animationIndex];
  9501. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  9502. }
  9503. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  9504. }
  9505. if (parsedLight.autoAnimate) {
  9506. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  9507. }
  9508. return light;
  9509. };
  9510. __decorate([
  9511. BABYLON.serializeAsColor3()
  9512. ], Light.prototype, "diffuse", void 0);
  9513. __decorate([
  9514. BABYLON.serializeAsColor3()
  9515. ], Light.prototype, "specular", void 0);
  9516. __decorate([
  9517. BABYLON.serialize()
  9518. ], Light.prototype, "intensity", void 0);
  9519. __decorate([
  9520. BABYLON.serialize()
  9521. ], Light.prototype, "range", void 0);
  9522. __decorate([
  9523. BABYLON.serialize()
  9524. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  9525. __decorate([
  9526. BABYLON.serialize()
  9527. ], Light.prototype, "excludeWithLayerMask", void 0);
  9528. __decorate([
  9529. BABYLON.serialize()
  9530. ], Light.prototype, "radius", void 0);
  9531. return Light;
  9532. })(BABYLON.Node);
  9533. BABYLON.Light = Light;
  9534. })(BABYLON || (BABYLON = {}));
  9535. var BABYLON;
  9536. (function (BABYLON) {
  9537. var PointLight = (function (_super) {
  9538. __extends(PointLight, _super);
  9539. function PointLight(name, position, scene) {
  9540. _super.call(this, name, scene);
  9541. this.position = position;
  9542. }
  9543. PointLight.prototype.getAbsolutePosition = function () {
  9544. return this.transformedPosition ? this.transformedPosition : this.position;
  9545. };
  9546. PointLight.prototype.computeTransformedPosition = function () {
  9547. if (this.parent && this.parent.getWorldMatrix) {
  9548. if (!this.transformedPosition) {
  9549. this.transformedPosition = BABYLON.Vector3.Zero();
  9550. }
  9551. BABYLON.Vector3.TransformCoordinatesToRef(this.getAbsolutePosition(), this.parent.getWorldMatrix(), this.transformedPosition);
  9552. return true;
  9553. }
  9554. return false;
  9555. };
  9556. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  9557. if (this.parent && this.parent.getWorldMatrix) {
  9558. this.computeTransformedPosition();
  9559. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  9560. return;
  9561. }
  9562. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  9563. };
  9564. PointLight.prototype.needCube = function () {
  9565. return true;
  9566. };
  9567. PointLight.prototype.supportsVSM = function () {
  9568. return false;
  9569. };
  9570. PointLight.prototype.needRefreshPerFrame = function () {
  9571. return false;
  9572. };
  9573. PointLight.prototype.getShadowDirection = function (faceIndex) {
  9574. switch (faceIndex) {
  9575. case 0:
  9576. return new BABYLON.Vector3(1, 0, 0);
  9577. case 1:
  9578. return new BABYLON.Vector3(-1, 0, 0);
  9579. case 2:
  9580. return new BABYLON.Vector3(0, -1, 0);
  9581. case 3:
  9582. return new BABYLON.Vector3(0, 1, 0);
  9583. case 4:
  9584. return new BABYLON.Vector3(0, 0, 1);
  9585. case 5:
  9586. return new BABYLON.Vector3(0, 0, -1);
  9587. }
  9588. return BABYLON.Vector3.Zero();
  9589. };
  9590. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9591. var activeCamera = this.getScene().activeCamera;
  9592. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9593. };
  9594. PointLight.prototype._getWorldMatrix = function () {
  9595. if (!this._worldMatrix) {
  9596. this._worldMatrix = BABYLON.Matrix.Identity();
  9597. }
  9598. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9599. return this._worldMatrix;
  9600. };
  9601. PointLight.prototype.getTypeID = function () {
  9602. return 0;
  9603. };
  9604. __decorate([
  9605. BABYLON.serializeAsVector3()
  9606. ], PointLight.prototype, "position", void 0);
  9607. return PointLight;
  9608. })(BABYLON.Light);
  9609. BABYLON.PointLight = PointLight;
  9610. })(BABYLON || (BABYLON = {}));
  9611. var BABYLON;
  9612. (function (BABYLON) {
  9613. var SpotLight = (function (_super) {
  9614. __extends(SpotLight, _super);
  9615. function SpotLight(name, position, direction, angle, exponent, scene) {
  9616. _super.call(this, name, scene);
  9617. this.position = position;
  9618. this.direction = direction;
  9619. this.angle = angle;
  9620. this.exponent = exponent;
  9621. }
  9622. SpotLight.prototype.getAbsolutePosition = function () {
  9623. return this.transformedPosition ? this.transformedPosition : this.position;
  9624. };
  9625. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9626. var activeCamera = this.getScene().activeCamera;
  9627. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  9628. };
  9629. SpotLight.prototype.needCube = function () {
  9630. return false;
  9631. };
  9632. SpotLight.prototype.supportsVSM = function () {
  9633. return true;
  9634. };
  9635. SpotLight.prototype.needRefreshPerFrame = function () {
  9636. return false;
  9637. };
  9638. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  9639. return this.direction;
  9640. };
  9641. SpotLight.prototype.setDirectionToTarget = function (target) {
  9642. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9643. return this.direction;
  9644. };
  9645. SpotLight.prototype.computeTransformedPosition = function () {
  9646. if (this.parent && this.parent.getWorldMatrix) {
  9647. if (!this.transformedPosition) {
  9648. this.transformedPosition = BABYLON.Vector3.Zero();
  9649. }
  9650. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9651. return true;
  9652. }
  9653. return false;
  9654. };
  9655. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  9656. var normalizeDirection;
  9657. if (this.parent && this.parent.getWorldMatrix) {
  9658. if (!this._transformedDirection) {
  9659. this._transformedDirection = BABYLON.Vector3.Zero();
  9660. }
  9661. this.computeTransformedPosition();
  9662. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9663. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  9664. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  9665. }
  9666. else {
  9667. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  9668. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9669. }
  9670. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  9671. };
  9672. SpotLight.prototype._getWorldMatrix = function () {
  9673. if (!this._worldMatrix) {
  9674. this._worldMatrix = BABYLON.Matrix.Identity();
  9675. }
  9676. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9677. return this._worldMatrix;
  9678. };
  9679. SpotLight.prototype.getTypeID = function () {
  9680. return 2;
  9681. };
  9682. __decorate([
  9683. BABYLON.serializeAsVector3()
  9684. ], SpotLight.prototype, "position", void 0);
  9685. __decorate([
  9686. BABYLON.serializeAsVector3()
  9687. ], SpotLight.prototype, "direction", void 0);
  9688. __decorate([
  9689. BABYLON.serialize()
  9690. ], SpotLight.prototype, "angle", void 0);
  9691. __decorate([
  9692. BABYLON.serialize()
  9693. ], SpotLight.prototype, "exponent", void 0);
  9694. return SpotLight;
  9695. })(BABYLON.Light);
  9696. BABYLON.SpotLight = SpotLight;
  9697. })(BABYLON || (BABYLON = {}));
  9698. var BABYLON;
  9699. (function (BABYLON) {
  9700. var HemisphericLight = (function (_super) {
  9701. __extends(HemisphericLight, _super);
  9702. function HemisphericLight(name, direction, scene) {
  9703. _super.call(this, name, scene);
  9704. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  9705. this.direction = direction;
  9706. }
  9707. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  9708. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  9709. return this.direction;
  9710. };
  9711. HemisphericLight.prototype.getShadowGenerator = function () {
  9712. return null;
  9713. };
  9714. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  9715. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  9716. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  9717. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  9718. };
  9719. HemisphericLight.prototype._getWorldMatrix = function () {
  9720. if (!this._worldMatrix) {
  9721. this._worldMatrix = BABYLON.Matrix.Identity();
  9722. }
  9723. return this._worldMatrix;
  9724. };
  9725. HemisphericLight.prototype.getTypeID = function () {
  9726. return 3;
  9727. };
  9728. __decorate([
  9729. BABYLON.serializeAsColor3()
  9730. ], HemisphericLight.prototype, "groundColor", void 0);
  9731. __decorate([
  9732. BABYLON.serializeAsVector3()
  9733. ], HemisphericLight.prototype, "direction", void 0);
  9734. return HemisphericLight;
  9735. })(BABYLON.Light);
  9736. BABYLON.HemisphericLight = HemisphericLight;
  9737. })(BABYLON || (BABYLON = {}));
  9738. var BABYLON;
  9739. (function (BABYLON) {
  9740. var DirectionalLight = (function (_super) {
  9741. __extends(DirectionalLight, _super);
  9742. function DirectionalLight(name, direction, scene) {
  9743. _super.call(this, name, scene);
  9744. this.shadowOrthoScale = 0.5;
  9745. this.autoUpdateExtends = true;
  9746. // Cache
  9747. this._orthoLeft = Number.MAX_VALUE;
  9748. this._orthoRight = Number.MIN_VALUE;
  9749. this._orthoTop = Number.MIN_VALUE;
  9750. this._orthoBottom = Number.MAX_VALUE;
  9751. this.position = direction.scale(-1);
  9752. this.direction = direction;
  9753. }
  9754. DirectionalLight.prototype.getAbsolutePosition = function () {
  9755. return this.transformedPosition ? this.transformedPosition : this.position;
  9756. };
  9757. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  9758. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  9759. return this.direction;
  9760. };
  9761. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  9762. var activeCamera = this.getScene().activeCamera;
  9763. // Check extends
  9764. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  9765. var tempVector3 = BABYLON.Vector3.Zero();
  9766. this._orthoLeft = Number.MAX_VALUE;
  9767. this._orthoRight = Number.MIN_VALUE;
  9768. this._orthoTop = Number.MIN_VALUE;
  9769. this._orthoBottom = Number.MAX_VALUE;
  9770. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  9771. var mesh = renderList[meshIndex];
  9772. if (!mesh) {
  9773. continue;
  9774. }
  9775. var boundingInfo = mesh.getBoundingInfo();
  9776. if (!boundingInfo) {
  9777. continue;
  9778. }
  9779. var boundingBox = boundingInfo.boundingBox;
  9780. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  9781. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  9782. if (tempVector3.x < this._orthoLeft)
  9783. this._orthoLeft = tempVector3.x;
  9784. if (tempVector3.y < this._orthoBottom)
  9785. this._orthoBottom = tempVector3.y;
  9786. if (tempVector3.x > this._orthoRight)
  9787. this._orthoRight = tempVector3.x;
  9788. if (tempVector3.y > this._orthoTop)
  9789. this._orthoTop = tempVector3.y;
  9790. }
  9791. }
  9792. }
  9793. var xOffset = this._orthoRight - this._orthoLeft;
  9794. var yOffset = this._orthoTop - this._orthoBottom;
  9795. 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);
  9796. };
  9797. DirectionalLight.prototype.supportsVSM = function () {
  9798. return true;
  9799. };
  9800. DirectionalLight.prototype.needRefreshPerFrame = function () {
  9801. return true;
  9802. };
  9803. DirectionalLight.prototype.needCube = function () {
  9804. return false;
  9805. };
  9806. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  9807. return this.direction;
  9808. };
  9809. DirectionalLight.prototype.computeTransformedPosition = function () {
  9810. if (this.parent && this.parent.getWorldMatrix) {
  9811. if (!this.transformedPosition) {
  9812. this.transformedPosition = BABYLON.Vector3.Zero();
  9813. }
  9814. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  9815. return true;
  9816. }
  9817. return false;
  9818. };
  9819. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  9820. if (this.parent && this.parent.getWorldMatrix) {
  9821. if (!this._transformedDirection) {
  9822. this._transformedDirection = BABYLON.Vector3.Zero();
  9823. }
  9824. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  9825. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  9826. return;
  9827. }
  9828. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  9829. };
  9830. DirectionalLight.prototype._getWorldMatrix = function () {
  9831. if (!this._worldMatrix) {
  9832. this._worldMatrix = BABYLON.Matrix.Identity();
  9833. }
  9834. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  9835. return this._worldMatrix;
  9836. };
  9837. DirectionalLight.prototype.getTypeID = function () {
  9838. return 1;
  9839. };
  9840. __decorate([
  9841. BABYLON.serializeAsVector3()
  9842. ], DirectionalLight.prototype, "position", void 0);
  9843. __decorate([
  9844. BABYLON.serializeAsVector3()
  9845. ], DirectionalLight.prototype, "direction", void 0);
  9846. __decorate([
  9847. BABYLON.serialize()
  9848. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  9849. __decorate([
  9850. BABYLON.serialize()
  9851. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  9852. return DirectionalLight;
  9853. })(BABYLON.Light);
  9854. BABYLON.DirectionalLight = DirectionalLight;
  9855. })(BABYLON || (BABYLON = {}));
  9856. var BABYLON;
  9857. (function (BABYLON) {
  9858. var ShadowGenerator = (function () {
  9859. function ShadowGenerator(mapSize, light) {
  9860. var _this = this;
  9861. // Members
  9862. this._filter = ShadowGenerator.FILTER_NONE;
  9863. this.blurScale = 2;
  9864. this._blurBoxOffset = 0;
  9865. this._bias = 0.00005;
  9866. this._lightDirection = BABYLON.Vector3.Zero();
  9867. this.forceBackFacesOnly = false;
  9868. this._darkness = 0;
  9869. this._transparencyShadow = false;
  9870. this._viewMatrix = BABYLON.Matrix.Zero();
  9871. this._projectionMatrix = BABYLON.Matrix.Zero();
  9872. this._transformMatrix = BABYLON.Matrix.Zero();
  9873. this._worldViewProjection = BABYLON.Matrix.Zero();
  9874. this._currentFaceIndex = 0;
  9875. this._currentFaceIndexCache = 0;
  9876. this._light = light;
  9877. this._scene = light.getScene();
  9878. this._mapSize = mapSize;
  9879. light._shadowGenerator = this;
  9880. // Render target
  9881. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, light.needCube());
  9882. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9883. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9884. this._shadowMap.anisotropicFilteringLevel = 1;
  9885. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9886. this._shadowMap.renderParticles = false;
  9887. this._shadowMap.onBeforeRender = function (faceIndex) {
  9888. _this._currentFaceIndex = faceIndex;
  9889. };
  9890. this._shadowMap.onAfterUnbind = function () {
  9891. if (!_this.useBlurVarianceShadowMap) {
  9892. return;
  9893. }
  9894. if (!_this._shadowMap2) {
  9895. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  9896. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9897. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9898. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  9899. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  9900. _this._downSamplePostprocess.onApply = function (effect) {
  9901. effect.setTexture("textureSampler", _this._shadowMap);
  9902. };
  9903. _this.blurBoxOffset = 1;
  9904. }
  9905. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  9906. };
  9907. // Custom render function
  9908. var renderSubMesh = function (subMesh) {
  9909. var mesh = subMesh.getRenderingMesh();
  9910. var scene = _this._scene;
  9911. var engine = scene.getEngine();
  9912. // Culling
  9913. engine.setState(subMesh.getMaterial().backFaceCulling);
  9914. // Managing instances
  9915. var batch = mesh._getInstancesRenderList(subMesh._id);
  9916. if (batch.mustReturn) {
  9917. return;
  9918. }
  9919. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9920. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  9921. engine.enableEffect(_this._effect);
  9922. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  9923. var material = subMesh.getMaterial();
  9924. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  9925. _this._effect.setVector3("lightPosition", _this.getLight().position);
  9926. if (_this.getLight().needCube()) {
  9927. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  9928. }
  9929. // Alpha test
  9930. if (material && material.needAlphaTesting()) {
  9931. var alphaTexture = material.getAlphaTestTexture();
  9932. _this._effect.setTexture("diffuseSampler", alphaTexture);
  9933. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  9934. }
  9935. // Bones
  9936. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  9937. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  9938. }
  9939. if (_this.forceBackFacesOnly) {
  9940. engine.setState(true, 0, false, true);
  9941. }
  9942. // Draw
  9943. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  9944. if (_this.forceBackFacesOnly) {
  9945. engine.setState(true, 0, false, false);
  9946. }
  9947. }
  9948. else {
  9949. // Need to reset refresh rate of the shadowMap
  9950. _this._shadowMap.resetRefreshCounter();
  9951. }
  9952. };
  9953. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  9954. var index;
  9955. for (index = 0; index < opaqueSubMeshes.length; index++) {
  9956. renderSubMesh(opaqueSubMeshes.data[index]);
  9957. }
  9958. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  9959. renderSubMesh(alphaTestSubMeshes.data[index]);
  9960. }
  9961. if (_this._transparencyShadow) {
  9962. for (index = 0; index < transparentSubMeshes.length; index++) {
  9963. renderSubMesh(transparentSubMeshes.data[index]);
  9964. }
  9965. }
  9966. };
  9967. this._shadowMap.onClear = function (engine) {
  9968. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  9969. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  9970. }
  9971. else {
  9972. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  9973. }
  9974. };
  9975. }
  9976. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  9977. // Static
  9978. get: function () {
  9979. return ShadowGenerator._FILTER_NONE;
  9980. },
  9981. enumerable: true,
  9982. configurable: true
  9983. });
  9984. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  9985. get: function () {
  9986. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  9987. },
  9988. enumerable: true,
  9989. configurable: true
  9990. });
  9991. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  9992. get: function () {
  9993. return ShadowGenerator._FILTER_POISSONSAMPLING;
  9994. },
  9995. enumerable: true,
  9996. configurable: true
  9997. });
  9998. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  9999. get: function () {
  10000. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  10001. },
  10002. enumerable: true,
  10003. configurable: true
  10004. });
  10005. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  10006. get: function () {
  10007. return this._bias;
  10008. },
  10009. set: function (bias) {
  10010. this._bias = bias;
  10011. },
  10012. enumerable: true,
  10013. configurable: true
  10014. });
  10015. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  10016. get: function () {
  10017. return this._blurBoxOffset;
  10018. },
  10019. set: function (value) {
  10020. var _this = this;
  10021. if (this._blurBoxOffset === value) {
  10022. return;
  10023. }
  10024. this._blurBoxOffset = value;
  10025. if (this._boxBlurPostprocess) {
  10026. this._boxBlurPostprocess.dispose();
  10027. }
  10028. 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);
  10029. this._boxBlurPostprocess.onApply = function (effect) {
  10030. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  10031. };
  10032. },
  10033. enumerable: true,
  10034. configurable: true
  10035. });
  10036. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  10037. get: function () {
  10038. return this._filter;
  10039. },
  10040. set: function (value) {
  10041. if (this._filter === value) {
  10042. return;
  10043. }
  10044. this._filter = value;
  10045. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  10046. this._shadowMap.anisotropicFilteringLevel = 16;
  10047. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  10048. }
  10049. else {
  10050. this._shadowMap.anisotropicFilteringLevel = 1;
  10051. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10052. }
  10053. },
  10054. enumerable: true,
  10055. configurable: true
  10056. });
  10057. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  10058. get: function () {
  10059. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  10060. },
  10061. set: function (value) {
  10062. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10063. },
  10064. enumerable: true,
  10065. configurable: true
  10066. });
  10067. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  10068. get: function () {
  10069. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  10070. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  10071. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  10072. },
  10073. set: function (value) {
  10074. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  10075. },
  10076. enumerable: true,
  10077. configurable: true
  10078. });
  10079. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  10080. get: function () {
  10081. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  10082. },
  10083. set: function (value) {
  10084. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  10085. },
  10086. enumerable: true,
  10087. configurable: true
  10088. });
  10089. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  10090. var defines = [];
  10091. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  10092. defines.push("#define VSM");
  10093. }
  10094. if (this.getLight().needCube()) {
  10095. defines.push("#define CUBEMAP");
  10096. }
  10097. var attribs = [BABYLON.VertexBuffer.PositionKind];
  10098. var mesh = subMesh.getMesh();
  10099. var material = subMesh.getMaterial();
  10100. // Alpha test
  10101. if (material && material.needAlphaTesting()) {
  10102. defines.push("#define ALPHATEST");
  10103. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10104. attribs.push(BABYLON.VertexBuffer.UVKind);
  10105. defines.push("#define UV1");
  10106. }
  10107. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  10108. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  10109. defines.push("#define UV2");
  10110. }
  10111. }
  10112. // Bones
  10113. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  10114. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  10115. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  10116. if (mesh.numBoneInfluencers > 4) {
  10117. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  10118. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  10119. }
  10120. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  10121. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  10122. }
  10123. else {
  10124. defines.push("#define NUM_BONE_INFLUENCERS 0");
  10125. }
  10126. // Instances
  10127. if (useInstances) {
  10128. defines.push("#define INSTANCES");
  10129. attribs.push("world0");
  10130. attribs.push("world1");
  10131. attribs.push("world2");
  10132. attribs.push("world3");
  10133. }
  10134. // Get correct effect
  10135. var join = defines.join("\n");
  10136. if (this._cachedDefines !== join) {
  10137. this._cachedDefines = join;
  10138. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  10139. }
  10140. return this._effect.isReady();
  10141. };
  10142. ShadowGenerator.prototype.getShadowMap = function () {
  10143. return this._shadowMap;
  10144. };
  10145. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  10146. if (this._shadowMap2) {
  10147. return this._shadowMap2;
  10148. }
  10149. return this._shadowMap;
  10150. };
  10151. ShadowGenerator.prototype.getLight = function () {
  10152. return this._light;
  10153. };
  10154. // Methods
  10155. ShadowGenerator.prototype.getTransformMatrix = function () {
  10156. var scene = this._scene;
  10157. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  10158. return this._transformMatrix;
  10159. }
  10160. this._currentRenderID = scene.getRenderId();
  10161. this._currentFaceIndexCache = this._currentFaceIndex;
  10162. var lightPosition = this._light.position;
  10163. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  10164. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  10165. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  10166. }
  10167. if (this._light.computeTransformedPosition()) {
  10168. lightPosition = this._light.transformedPosition;
  10169. }
  10170. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  10171. this._cachedPosition = lightPosition.clone();
  10172. this._cachedDirection = this._lightDirection.clone();
  10173. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  10174. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  10175. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  10176. }
  10177. return this._transformMatrix;
  10178. };
  10179. ShadowGenerator.prototype.getDarkness = function () {
  10180. return this._darkness;
  10181. };
  10182. ShadowGenerator.prototype.setDarkness = function (darkness) {
  10183. if (darkness >= 1.0)
  10184. this._darkness = 1.0;
  10185. else if (darkness <= 0.0)
  10186. this._darkness = 0.0;
  10187. else
  10188. this._darkness = darkness;
  10189. };
  10190. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  10191. this._transparencyShadow = hasShadow;
  10192. };
  10193. ShadowGenerator.prototype._packHalf = function (depth) {
  10194. var scale = depth * 255.0;
  10195. var fract = scale - Math.floor(scale);
  10196. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  10197. };
  10198. ShadowGenerator.prototype.dispose = function () {
  10199. this._shadowMap.dispose();
  10200. if (this._shadowMap2) {
  10201. this._shadowMap2.dispose();
  10202. }
  10203. if (this._downSamplePostprocess) {
  10204. this._downSamplePostprocess.dispose();
  10205. }
  10206. if (this._boxBlurPostprocess) {
  10207. this._boxBlurPostprocess.dispose();
  10208. }
  10209. };
  10210. ShadowGenerator.prototype.serialize = function () {
  10211. var serializationObject = {};
  10212. serializationObject.lightId = this._light.id;
  10213. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  10214. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  10215. serializationObject.usePoissonSampling = this.usePoissonSampling;
  10216. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  10217. serializationObject.renderList = [];
  10218. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  10219. var mesh = this.getShadowMap().renderList[meshIndex];
  10220. serializationObject.renderList.push(mesh.id);
  10221. }
  10222. return serializationObject;
  10223. };
  10224. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  10225. //casting to point light, as light is missing the position attr and typescript complains.
  10226. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  10227. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  10228. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  10229. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  10230. shadowGenerator.getShadowMap().renderList.push(mesh);
  10231. }
  10232. if (parsedShadowGenerator.usePoissonSampling) {
  10233. shadowGenerator.usePoissonSampling = true;
  10234. }
  10235. else if (parsedShadowGenerator.useVarianceShadowMap) {
  10236. shadowGenerator.useVarianceShadowMap = true;
  10237. }
  10238. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  10239. shadowGenerator.useBlurVarianceShadowMap = true;
  10240. if (parsedShadowGenerator.blurScale) {
  10241. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  10242. }
  10243. if (parsedShadowGenerator.blurBoxOffset) {
  10244. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  10245. }
  10246. }
  10247. if (parsedShadowGenerator.bias !== undefined) {
  10248. shadowGenerator.bias = parsedShadowGenerator.bias;
  10249. }
  10250. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  10251. return shadowGenerator;
  10252. };
  10253. ShadowGenerator._FILTER_NONE = 0;
  10254. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  10255. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  10256. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  10257. return ShadowGenerator;
  10258. })();
  10259. BABYLON.ShadowGenerator = ShadowGenerator;
  10260. })(BABYLON || (BABYLON = {}));
  10261. var BABYLON;
  10262. (function (BABYLON) {
  10263. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  10264. if (boxMin.x > sphereCenter.x + sphereRadius)
  10265. return false;
  10266. if (sphereCenter.x - sphereRadius > boxMax.x)
  10267. return false;
  10268. if (boxMin.y > sphereCenter.y + sphereRadius)
  10269. return false;
  10270. if (sphereCenter.y - sphereRadius > boxMax.y)
  10271. return false;
  10272. if (boxMin.z > sphereCenter.z + sphereRadius)
  10273. return false;
  10274. if (sphereCenter.z - sphereRadius > boxMax.z)
  10275. return false;
  10276. return true;
  10277. };
  10278. var getLowestRoot = function (a, b, c, maxR) {
  10279. var determinant = b * b - 4.0 * a * c;
  10280. var result = { root: 0, found: false };
  10281. if (determinant < 0)
  10282. return result;
  10283. var sqrtD = Math.sqrt(determinant);
  10284. var r1 = (-b - sqrtD) / (2.0 * a);
  10285. var r2 = (-b + sqrtD) / (2.0 * a);
  10286. if (r1 > r2) {
  10287. var temp = r2;
  10288. r2 = r1;
  10289. r1 = temp;
  10290. }
  10291. if (r1 > 0 && r1 < maxR) {
  10292. result.root = r1;
  10293. result.found = true;
  10294. return result;
  10295. }
  10296. if (r2 > 0 && r2 < maxR) {
  10297. result.root = r2;
  10298. result.found = true;
  10299. return result;
  10300. }
  10301. return result;
  10302. };
  10303. var Collider = (function () {
  10304. function Collider() {
  10305. this.radius = new BABYLON.Vector3(1, 1, 1);
  10306. this.retry = 0;
  10307. this.basePointWorld = BABYLON.Vector3.Zero();
  10308. this.velocityWorld = BABYLON.Vector3.Zero();
  10309. this.normalizedVelocity = BABYLON.Vector3.Zero();
  10310. this._collisionPoint = BABYLON.Vector3.Zero();
  10311. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  10312. this._tempVector = BABYLON.Vector3.Zero();
  10313. this._tempVector2 = BABYLON.Vector3.Zero();
  10314. this._tempVector3 = BABYLON.Vector3.Zero();
  10315. this._tempVector4 = BABYLON.Vector3.Zero();
  10316. this._edge = BABYLON.Vector3.Zero();
  10317. this._baseToVertex = BABYLON.Vector3.Zero();
  10318. this._destinationPoint = BABYLON.Vector3.Zero();
  10319. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  10320. this._displacementVector = BABYLON.Vector3.Zero();
  10321. }
  10322. // Methods
  10323. Collider.prototype._initialize = function (source, dir, e) {
  10324. this.velocity = dir;
  10325. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  10326. this.basePoint = source;
  10327. source.multiplyToRef(this.radius, this.basePointWorld);
  10328. dir.multiplyToRef(this.radius, this.velocityWorld);
  10329. this.velocityWorldLength = this.velocityWorld.length();
  10330. this.epsilon = e;
  10331. this.collisionFound = false;
  10332. };
  10333. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  10334. pa.subtractToRef(point, this._tempVector);
  10335. pb.subtractToRef(point, this._tempVector2);
  10336. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  10337. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10338. if (d < 0)
  10339. return false;
  10340. pc.subtractToRef(point, this._tempVector3);
  10341. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  10342. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10343. if (d < 0)
  10344. return false;
  10345. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  10346. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  10347. return d >= 0;
  10348. };
  10349. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  10350. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  10351. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  10352. if (distance > this.velocityWorldLength + max + sphereRadius) {
  10353. return false;
  10354. }
  10355. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  10356. return false;
  10357. return true;
  10358. };
  10359. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  10360. var t0;
  10361. var embeddedInPlane = false;
  10362. //defensive programming, actually not needed.
  10363. if (!trianglePlaneArray) {
  10364. trianglePlaneArray = [];
  10365. }
  10366. if (!trianglePlaneArray[faceIndex]) {
  10367. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  10368. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  10369. }
  10370. var trianglePlane = trianglePlaneArray[faceIndex];
  10371. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  10372. return;
  10373. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  10374. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  10375. if (normalDotVelocity == 0) {
  10376. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  10377. return;
  10378. embeddedInPlane = true;
  10379. t0 = 0;
  10380. }
  10381. else {
  10382. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10383. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  10384. if (t0 > t1) {
  10385. var temp = t1;
  10386. t1 = t0;
  10387. t0 = temp;
  10388. }
  10389. if (t0 > 1.0 || t1 < 0.0)
  10390. return;
  10391. if (t0 < 0)
  10392. t0 = 0;
  10393. if (t0 > 1.0)
  10394. t0 = 1.0;
  10395. }
  10396. this._collisionPoint.copyFromFloats(0, 0, 0);
  10397. var found = false;
  10398. var t = 1.0;
  10399. if (!embeddedInPlane) {
  10400. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  10401. this.velocity.scaleToRef(t0, this._tempVector);
  10402. this._planeIntersectionPoint.addInPlace(this._tempVector);
  10403. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  10404. found = true;
  10405. t = t0;
  10406. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  10407. }
  10408. }
  10409. if (!found) {
  10410. var velocitySquaredLength = this.velocity.lengthSquared();
  10411. var a = velocitySquaredLength;
  10412. this.basePoint.subtractToRef(p1, this._tempVector);
  10413. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10414. var c = this._tempVector.lengthSquared() - 1.0;
  10415. var lowestRoot = getLowestRoot(a, b, c, t);
  10416. if (lowestRoot.found) {
  10417. t = lowestRoot.root;
  10418. found = true;
  10419. this._collisionPoint.copyFrom(p1);
  10420. }
  10421. this.basePoint.subtractToRef(p2, this._tempVector);
  10422. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10423. c = this._tempVector.lengthSquared() - 1.0;
  10424. lowestRoot = getLowestRoot(a, b, c, t);
  10425. if (lowestRoot.found) {
  10426. t = lowestRoot.root;
  10427. found = true;
  10428. this._collisionPoint.copyFrom(p2);
  10429. }
  10430. this.basePoint.subtractToRef(p3, this._tempVector);
  10431. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  10432. c = this._tempVector.lengthSquared() - 1.0;
  10433. lowestRoot = getLowestRoot(a, b, c, t);
  10434. if (lowestRoot.found) {
  10435. t = lowestRoot.root;
  10436. found = true;
  10437. this._collisionPoint.copyFrom(p3);
  10438. }
  10439. p2.subtractToRef(p1, this._edge);
  10440. p1.subtractToRef(this.basePoint, this._baseToVertex);
  10441. var edgeSquaredLength = this._edge.lengthSquared();
  10442. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10443. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10444. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10445. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10446. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10447. lowestRoot = getLowestRoot(a, b, c, t);
  10448. if (lowestRoot.found) {
  10449. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10450. if (f >= 0.0 && f <= 1.0) {
  10451. t = lowestRoot.root;
  10452. found = true;
  10453. this._edge.scaleInPlace(f);
  10454. p1.addToRef(this._edge, this._collisionPoint);
  10455. }
  10456. }
  10457. p3.subtractToRef(p2, this._edge);
  10458. p2.subtractToRef(this.basePoint, this._baseToVertex);
  10459. edgeSquaredLength = this._edge.lengthSquared();
  10460. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10461. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10462. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10463. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10464. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10465. lowestRoot = getLowestRoot(a, b, c, t);
  10466. if (lowestRoot.found) {
  10467. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10468. if (f >= 0.0 && f <= 1.0) {
  10469. t = lowestRoot.root;
  10470. found = true;
  10471. this._edge.scaleInPlace(f);
  10472. p2.addToRef(this._edge, this._collisionPoint);
  10473. }
  10474. }
  10475. p1.subtractToRef(p3, this._edge);
  10476. p3.subtractToRef(this.basePoint, this._baseToVertex);
  10477. edgeSquaredLength = this._edge.lengthSquared();
  10478. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  10479. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  10480. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  10481. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  10482. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  10483. lowestRoot = getLowestRoot(a, b, c, t);
  10484. if (lowestRoot.found) {
  10485. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  10486. if (f >= 0.0 && f <= 1.0) {
  10487. t = lowestRoot.root;
  10488. found = true;
  10489. this._edge.scaleInPlace(f);
  10490. p3.addToRef(this._edge, this._collisionPoint);
  10491. }
  10492. }
  10493. }
  10494. if (found) {
  10495. var distToCollision = t * this.velocity.length();
  10496. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  10497. if (!this.intersectionPoint) {
  10498. this.intersectionPoint = this._collisionPoint.clone();
  10499. }
  10500. else {
  10501. this.intersectionPoint.copyFrom(this._collisionPoint);
  10502. }
  10503. this.nearestDistance = distToCollision;
  10504. this.collisionFound = true;
  10505. }
  10506. }
  10507. };
  10508. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  10509. for (var i = indexStart; i < indexEnd; i += 3) {
  10510. var p1 = pts[indices[i] - decal];
  10511. var p2 = pts[indices[i + 1] - decal];
  10512. var p3 = pts[indices[i + 2] - decal];
  10513. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  10514. }
  10515. };
  10516. Collider.prototype._getResponse = function (pos, vel) {
  10517. pos.addToRef(vel, this._destinationPoint);
  10518. vel.scaleInPlace((this.nearestDistance / vel.length()));
  10519. this.basePoint.addToRef(vel, pos);
  10520. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  10521. this._slidePlaneNormal.normalize();
  10522. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  10523. pos.addInPlace(this._displacementVector);
  10524. this.intersectionPoint.addInPlace(this._displacementVector);
  10525. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  10526. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  10527. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  10528. };
  10529. return Collider;
  10530. })();
  10531. BABYLON.Collider = Collider;
  10532. })(BABYLON || (BABYLON = {}));
  10533. var BABYLON;
  10534. (function (BABYLON) {
  10535. //WebWorker code will be inserted to this variable.
  10536. BABYLON.CollisionWorker = "";
  10537. (function (WorkerTaskType) {
  10538. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  10539. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  10540. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  10541. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  10542. var WorkerTaskType = BABYLON.WorkerTaskType;
  10543. (function (WorkerReplyType) {
  10544. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  10545. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  10546. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  10547. var WorkerReplyType = BABYLON.WorkerReplyType;
  10548. var CollisionCoordinatorWorker = (function () {
  10549. function CollisionCoordinatorWorker() {
  10550. var _this = this;
  10551. this._scaledPosition = BABYLON.Vector3.Zero();
  10552. this._scaledVelocity = BABYLON.Vector3.Zero();
  10553. this.onMeshUpdated = function (mesh) {
  10554. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  10555. };
  10556. this.onGeometryUpdated = function (geometry) {
  10557. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  10558. };
  10559. this._afterRender = function () {
  10560. if (!_this._init)
  10561. return;
  10562. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  10563. return;
  10564. }
  10565. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  10566. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  10567. if (_this._runningUpdated > 4) {
  10568. return;
  10569. }
  10570. ++_this._runningUpdated;
  10571. var payload = {
  10572. updatedMeshes: _this._addUpdateMeshesList,
  10573. updatedGeometries: _this._addUpdateGeometriesList,
  10574. removedGeometries: _this._toRemoveGeometryArray,
  10575. removedMeshes: _this._toRemoveMeshesArray
  10576. };
  10577. var message = {
  10578. payload: payload,
  10579. taskType: WorkerTaskType.UPDATE
  10580. };
  10581. var serializable = [];
  10582. for (var id in payload.updatedGeometries) {
  10583. if (payload.updatedGeometries.hasOwnProperty(id)) {
  10584. //prepare transferables
  10585. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  10586. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  10587. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  10588. }
  10589. }
  10590. _this._worker.postMessage(message, serializable);
  10591. _this._addUpdateMeshesList = {};
  10592. _this._addUpdateGeometriesList = {};
  10593. _this._toRemoveGeometryArray = [];
  10594. _this._toRemoveMeshesArray = [];
  10595. };
  10596. this._onMessageFromWorker = function (e) {
  10597. var returnData = e.data;
  10598. if (returnData.error != WorkerReplyType.SUCCESS) {
  10599. //TODO what errors can be returned from the worker?
  10600. BABYLON.Tools.Warn("error returned from worker!");
  10601. return;
  10602. }
  10603. switch (returnData.taskType) {
  10604. case WorkerTaskType.INIT:
  10605. _this._init = true;
  10606. //Update the worked with ALL of the scene's current state
  10607. _this._scene.meshes.forEach(function (mesh) {
  10608. _this.onMeshAdded(mesh);
  10609. });
  10610. _this._scene.getGeometries().forEach(function (geometry) {
  10611. _this.onGeometryAdded(geometry);
  10612. });
  10613. break;
  10614. case WorkerTaskType.UPDATE:
  10615. _this._runningUpdated--;
  10616. break;
  10617. case WorkerTaskType.COLLIDE:
  10618. _this._runningCollisionTask = false;
  10619. var returnPayload = returnData.payload;
  10620. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  10621. return;
  10622. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  10623. //cleanup
  10624. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  10625. break;
  10626. }
  10627. };
  10628. this._collisionsCallbackArray = [];
  10629. this._init = false;
  10630. this._runningUpdated = 0;
  10631. this._runningCollisionTask = false;
  10632. this._addUpdateMeshesList = {};
  10633. this._addUpdateGeometriesList = {};
  10634. this._toRemoveGeometryArray = [];
  10635. this._toRemoveMeshesArray = [];
  10636. }
  10637. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10638. if (!this._init)
  10639. return;
  10640. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  10641. return;
  10642. position.divideToRef(collider.radius, this._scaledPosition);
  10643. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10644. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  10645. var payload = {
  10646. collider: {
  10647. position: this._scaledPosition.asArray(),
  10648. velocity: this._scaledVelocity.asArray(),
  10649. radius: collider.radius.asArray()
  10650. },
  10651. collisionId: collisionIndex,
  10652. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  10653. maximumRetry: maximumRetry
  10654. };
  10655. var message = {
  10656. payload: payload,
  10657. taskType: WorkerTaskType.COLLIDE
  10658. };
  10659. this._worker.postMessage(message);
  10660. };
  10661. CollisionCoordinatorWorker.prototype.init = function (scene) {
  10662. this._scene = scene;
  10663. this._scene.registerAfterRender(this._afterRender);
  10664. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  10665. this._worker = new Worker(workerUrl);
  10666. this._worker.onmessage = this._onMessageFromWorker;
  10667. var message = {
  10668. payload: {},
  10669. taskType: WorkerTaskType.INIT
  10670. };
  10671. this._worker.postMessage(message);
  10672. };
  10673. CollisionCoordinatorWorker.prototype.destroy = function () {
  10674. this._scene.unregisterAfterRender(this._afterRender);
  10675. this._worker.terminate();
  10676. };
  10677. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  10678. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  10679. this.onMeshUpdated(mesh);
  10680. };
  10681. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  10682. this._toRemoveMeshesArray.push(mesh.uniqueId);
  10683. };
  10684. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  10685. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  10686. geometry.onGeometryUpdated = this.onGeometryUpdated;
  10687. this.onGeometryUpdated(geometry);
  10688. };
  10689. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  10690. this._toRemoveGeometryArray.push(geometry.id);
  10691. };
  10692. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  10693. var submeshes = [];
  10694. if (mesh.subMeshes) {
  10695. submeshes = mesh.subMeshes.map(function (sm, idx) {
  10696. return {
  10697. position: idx,
  10698. verticesStart: sm.verticesStart,
  10699. verticesCount: sm.verticesCount,
  10700. indexStart: sm.indexStart,
  10701. indexCount: sm.indexCount,
  10702. hasMaterial: !!sm.getMaterial(),
  10703. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10704. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  10705. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10706. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  10707. };
  10708. });
  10709. }
  10710. var geometryId = null;
  10711. if (mesh instanceof BABYLON.Mesh) {
  10712. geometryId = mesh.geometry ? mesh.geometry.id : null;
  10713. }
  10714. else if (mesh instanceof BABYLON.InstancedMesh) {
  10715. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  10716. }
  10717. return {
  10718. uniqueId: mesh.uniqueId,
  10719. id: mesh.id,
  10720. name: mesh.name,
  10721. geometryId: geometryId,
  10722. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  10723. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  10724. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  10725. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  10726. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  10727. subMeshes: submeshes,
  10728. checkCollisions: mesh.checkCollisions
  10729. };
  10730. };
  10731. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  10732. return {
  10733. id: geometry.id,
  10734. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  10735. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  10736. indices: new Int32Array(geometry.getIndices() || []),
  10737. };
  10738. };
  10739. return CollisionCoordinatorWorker;
  10740. })();
  10741. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  10742. var CollisionCoordinatorLegacy = (function () {
  10743. function CollisionCoordinatorLegacy() {
  10744. this._scaledPosition = BABYLON.Vector3.Zero();
  10745. this._scaledVelocity = BABYLON.Vector3.Zero();
  10746. this._finalPosition = BABYLON.Vector3.Zero();
  10747. }
  10748. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  10749. position.divideToRef(collider.radius, this._scaledPosition);
  10750. velocity.divideToRef(collider.radius, this._scaledVelocity);
  10751. collider.collidedMesh = null;
  10752. collider.retry = 0;
  10753. collider.initialVelocity = this._scaledVelocity;
  10754. collider.initialPosition = this._scaledPosition;
  10755. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  10756. this._finalPosition.multiplyInPlace(collider.radius);
  10757. //run the callback
  10758. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  10759. };
  10760. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  10761. this._scene = scene;
  10762. };
  10763. CollisionCoordinatorLegacy.prototype.destroy = function () {
  10764. //Legacy need no destruction method.
  10765. };
  10766. //No update in legacy mode
  10767. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  10768. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  10769. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  10770. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  10771. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  10772. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  10773. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  10774. if (excludedMesh === void 0) { excludedMesh = null; }
  10775. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  10776. if (collider.retry >= maximumRetry) {
  10777. finalPosition.copyFrom(position);
  10778. return;
  10779. }
  10780. collider._initialize(position, velocity, closeDistance);
  10781. // Check all meshes
  10782. for (var index = 0; index < this._scene.meshes.length; index++) {
  10783. var mesh = this._scene.meshes[index];
  10784. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  10785. mesh._checkCollision(collider);
  10786. }
  10787. }
  10788. if (!collider.collisionFound) {
  10789. position.addToRef(velocity, finalPosition);
  10790. return;
  10791. }
  10792. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  10793. collider._getResponse(position, velocity);
  10794. }
  10795. if (velocity.length() <= closeDistance) {
  10796. finalPosition.copyFrom(position);
  10797. return;
  10798. }
  10799. collider.retry++;
  10800. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  10801. };
  10802. return CollisionCoordinatorLegacy;
  10803. })();
  10804. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  10805. })(BABYLON || (BABYLON = {}));
  10806. var BABYLON;
  10807. (function (BABYLON) {
  10808. var Camera = (function (_super) {
  10809. __extends(Camera, _super);
  10810. function Camera(name, position, scene) {
  10811. _super.call(this, name, scene);
  10812. this.upVector = BABYLON.Vector3.Up();
  10813. this.orthoLeft = null;
  10814. this.orthoRight = null;
  10815. this.orthoBottom = null;
  10816. this.orthoTop = null;
  10817. this.fov = 0.8;
  10818. this.minZ = 1.0;
  10819. this.maxZ = 10000.0;
  10820. this.inertia = 0.9;
  10821. this.mode = Camera.PERSPECTIVE_CAMERA;
  10822. this.isIntermediate = false;
  10823. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  10824. this.layerMask = 0x0FFFFFFF;
  10825. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  10826. // Camera rig members
  10827. this.cameraRigMode = Camera.RIG_MODE_NONE;
  10828. this._rigCameras = new Array();
  10829. // Cache
  10830. this._computedViewMatrix = BABYLON.Matrix.Identity();
  10831. this._projectionMatrix = new BABYLON.Matrix();
  10832. this._postProcesses = new Array();
  10833. this._postProcessesTakenIndices = [];
  10834. this._activeMeshes = new BABYLON.SmartArray(256);
  10835. this._globalPosition = BABYLON.Vector3.Zero();
  10836. scene.addCamera(this);
  10837. if (!scene.activeCamera) {
  10838. scene.activeCamera = this;
  10839. }
  10840. this.position = position;
  10841. }
  10842. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  10843. get: function () {
  10844. return Camera._PERSPECTIVE_CAMERA;
  10845. },
  10846. enumerable: true,
  10847. configurable: true
  10848. });
  10849. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  10850. get: function () {
  10851. return Camera._ORTHOGRAPHIC_CAMERA;
  10852. },
  10853. enumerable: true,
  10854. configurable: true
  10855. });
  10856. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  10857. get: function () {
  10858. return Camera._FOVMODE_VERTICAL_FIXED;
  10859. },
  10860. enumerable: true,
  10861. configurable: true
  10862. });
  10863. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  10864. get: function () {
  10865. return Camera._FOVMODE_HORIZONTAL_FIXED;
  10866. },
  10867. enumerable: true,
  10868. configurable: true
  10869. });
  10870. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  10871. get: function () {
  10872. return Camera._RIG_MODE_NONE;
  10873. },
  10874. enumerable: true,
  10875. configurable: true
  10876. });
  10877. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  10878. get: function () {
  10879. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  10880. },
  10881. enumerable: true,
  10882. configurable: true
  10883. });
  10884. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  10885. get: function () {
  10886. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  10887. },
  10888. enumerable: true,
  10889. configurable: true
  10890. });
  10891. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  10892. get: function () {
  10893. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  10894. },
  10895. enumerable: true,
  10896. configurable: true
  10897. });
  10898. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  10899. get: function () {
  10900. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  10901. },
  10902. enumerable: true,
  10903. configurable: true
  10904. });
  10905. Object.defineProperty(Camera, "RIG_MODE_VR", {
  10906. get: function () {
  10907. return Camera._RIG_MODE_VR;
  10908. },
  10909. enumerable: true,
  10910. configurable: true
  10911. });
  10912. /**
  10913. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10914. */
  10915. Camera.prototype.toString = function (fullDetails) {
  10916. var ret = "Name: " + this.name;
  10917. ret += ", type: " + this.getTypeName();
  10918. if (this.animations) {
  10919. for (var i = 0; i < this.animations.length; i++) {
  10920. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  10921. }
  10922. }
  10923. if (fullDetails) {
  10924. }
  10925. return ret;
  10926. };
  10927. Object.defineProperty(Camera.prototype, "globalPosition", {
  10928. get: function () {
  10929. return this._globalPosition;
  10930. },
  10931. enumerable: true,
  10932. configurable: true
  10933. });
  10934. Camera.prototype.getActiveMeshes = function () {
  10935. return this._activeMeshes;
  10936. };
  10937. Camera.prototype.isActiveMesh = function (mesh) {
  10938. return (this._activeMeshes.indexOf(mesh) !== -1);
  10939. };
  10940. //Cache
  10941. Camera.prototype._initCache = function () {
  10942. _super.prototype._initCache.call(this);
  10943. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10944. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10945. this._cache.mode = undefined;
  10946. this._cache.minZ = undefined;
  10947. this._cache.maxZ = undefined;
  10948. this._cache.fov = undefined;
  10949. this._cache.aspectRatio = undefined;
  10950. this._cache.orthoLeft = undefined;
  10951. this._cache.orthoRight = undefined;
  10952. this._cache.orthoBottom = undefined;
  10953. this._cache.orthoTop = undefined;
  10954. this._cache.renderWidth = undefined;
  10955. this._cache.renderHeight = undefined;
  10956. };
  10957. Camera.prototype._updateCache = function (ignoreParentClass) {
  10958. if (!ignoreParentClass) {
  10959. _super.prototype._updateCache.call(this);
  10960. }
  10961. var engine = this.getEngine();
  10962. this._cache.position.copyFrom(this.position);
  10963. this._cache.upVector.copyFrom(this.upVector);
  10964. this._cache.mode = this.mode;
  10965. this._cache.minZ = this.minZ;
  10966. this._cache.maxZ = this.maxZ;
  10967. this._cache.fov = this.fov;
  10968. this._cache.aspectRatio = engine.getAspectRatio(this);
  10969. this._cache.orthoLeft = this.orthoLeft;
  10970. this._cache.orthoRight = this.orthoRight;
  10971. this._cache.orthoBottom = this.orthoBottom;
  10972. this._cache.orthoTop = this.orthoTop;
  10973. this._cache.renderWidth = engine.getRenderWidth();
  10974. this._cache.renderHeight = engine.getRenderHeight();
  10975. };
  10976. Camera.prototype._updateFromScene = function () {
  10977. this.updateCache();
  10978. this._update();
  10979. };
  10980. // Synchronized
  10981. Camera.prototype._isSynchronized = function () {
  10982. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  10983. };
  10984. Camera.prototype._isSynchronizedViewMatrix = function () {
  10985. if (!_super.prototype._isSynchronized.call(this))
  10986. return false;
  10987. return this._cache.position.equals(this.position)
  10988. && this._cache.upVector.equals(this.upVector)
  10989. && this.isSynchronizedWithParent();
  10990. };
  10991. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  10992. var check = this._cache.mode === this.mode
  10993. && this._cache.minZ === this.minZ
  10994. && this._cache.maxZ === this.maxZ;
  10995. if (!check) {
  10996. return false;
  10997. }
  10998. var engine = this.getEngine();
  10999. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11000. check = this._cache.fov === this.fov
  11001. && this._cache.aspectRatio === engine.getAspectRatio(this);
  11002. }
  11003. else {
  11004. check = this._cache.orthoLeft === this.orthoLeft
  11005. && this._cache.orthoRight === this.orthoRight
  11006. && this._cache.orthoBottom === this.orthoBottom
  11007. && this._cache.orthoTop === this.orthoTop
  11008. && this._cache.renderWidth === engine.getRenderWidth()
  11009. && this._cache.renderHeight === engine.getRenderHeight();
  11010. }
  11011. return check;
  11012. };
  11013. // Controls
  11014. Camera.prototype.attachControl = function (element, noPreventDefault) {
  11015. };
  11016. Camera.prototype.detachControl = function (element) {
  11017. };
  11018. Camera.prototype._update = function () {
  11019. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  11020. this._updateRigCameras();
  11021. }
  11022. this._checkInputs();
  11023. };
  11024. Camera.prototype._checkInputs = function () {
  11025. };
  11026. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  11027. if (insertAt === void 0) { insertAt = null; }
  11028. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  11029. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  11030. return 0;
  11031. }
  11032. if (insertAt == null || insertAt < 0) {
  11033. this._postProcesses.push(postProcess);
  11034. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  11035. return this._postProcesses.length - 1;
  11036. }
  11037. var add = 0;
  11038. var i;
  11039. var start;
  11040. if (this._postProcesses[insertAt]) {
  11041. start = this._postProcesses.length - 1;
  11042. for (i = start; i >= insertAt + 1; --i) {
  11043. this._postProcesses[i + 1] = this._postProcesses[i];
  11044. }
  11045. add = 1;
  11046. }
  11047. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  11048. if (this._postProcessesTakenIndices[i] < insertAt) {
  11049. continue;
  11050. }
  11051. start = this._postProcessesTakenIndices.length - 1;
  11052. for (var j = start; j >= i; --j) {
  11053. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  11054. }
  11055. this._postProcessesTakenIndices[i] = insertAt;
  11056. break;
  11057. }
  11058. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) === -1) {
  11059. this._postProcessesTakenIndices.push(insertAt);
  11060. }
  11061. var result = insertAt + add;
  11062. this._postProcesses[result] = postProcess;
  11063. return result;
  11064. };
  11065. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  11066. if (atIndices === void 0) { atIndices = null; }
  11067. var result = [];
  11068. var i;
  11069. var index;
  11070. if (!atIndices) {
  11071. var length = this._postProcesses.length;
  11072. for (i = 0; i < length; i++) {
  11073. if (this._postProcesses[i] !== postProcess) {
  11074. continue;
  11075. }
  11076. delete this._postProcesses[i];
  11077. index = this._postProcessesTakenIndices.indexOf(i);
  11078. this._postProcessesTakenIndices.splice(index, 1);
  11079. }
  11080. }
  11081. else {
  11082. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  11083. for (i = 0; i < atIndices.length; i++) {
  11084. var foundPostProcess = this._postProcesses[atIndices[i]];
  11085. if (foundPostProcess !== postProcess) {
  11086. result.push(i);
  11087. continue;
  11088. }
  11089. delete this._postProcesses[atIndices[i]];
  11090. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  11091. this._postProcessesTakenIndices.splice(index, 1);
  11092. }
  11093. }
  11094. return result;
  11095. };
  11096. Camera.prototype.getWorldMatrix = function () {
  11097. if (!this._worldMatrix) {
  11098. this._worldMatrix = BABYLON.Matrix.Identity();
  11099. }
  11100. var viewMatrix = this.getViewMatrix();
  11101. viewMatrix.invertToRef(this._worldMatrix);
  11102. return this._worldMatrix;
  11103. };
  11104. Camera.prototype._getViewMatrix = function () {
  11105. return BABYLON.Matrix.Identity();
  11106. };
  11107. Camera.prototype.getViewMatrix = function (force) {
  11108. this._computedViewMatrix = this._computeViewMatrix(force);
  11109. if (!force && this._isSynchronizedViewMatrix()) {
  11110. return this._computedViewMatrix;
  11111. }
  11112. if (!this.parent || !this.parent.getWorldMatrix) {
  11113. this._globalPosition.copyFrom(this.position);
  11114. }
  11115. else {
  11116. if (!this._worldMatrix) {
  11117. this._worldMatrix = BABYLON.Matrix.Identity();
  11118. }
  11119. this._computedViewMatrix.invertToRef(this._worldMatrix);
  11120. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  11121. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  11122. this._computedViewMatrix.invert();
  11123. this._markSyncedWithParent();
  11124. }
  11125. this._currentRenderId = this.getScene().getRenderId();
  11126. return this._computedViewMatrix;
  11127. };
  11128. Camera.prototype._computeViewMatrix = function (force) {
  11129. if (!force && this._isSynchronizedViewMatrix()) {
  11130. return this._computedViewMatrix;
  11131. }
  11132. this._computedViewMatrix = this._getViewMatrix();
  11133. this._currentRenderId = this.getScene().getRenderId();
  11134. return this._computedViewMatrix;
  11135. };
  11136. Camera.prototype.getProjectionMatrix = function (force) {
  11137. if (!force && this._isSynchronizedProjectionMatrix()) {
  11138. return this._projectionMatrix;
  11139. }
  11140. var engine = this.getEngine();
  11141. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  11142. if (this.minZ <= 0) {
  11143. this.minZ = 0.1;
  11144. }
  11145. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  11146. return this._projectionMatrix;
  11147. }
  11148. var halfWidth = engine.getRenderWidth() / 2.0;
  11149. var halfHeight = engine.getRenderHeight() / 2.0;
  11150. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  11151. return this._projectionMatrix;
  11152. };
  11153. Camera.prototype.dispose = function () {
  11154. // Animations
  11155. this.getScene().stopAnimation(this);
  11156. // Remove from scene
  11157. this.getScene().removeCamera(this);
  11158. while (this._rigCameras.length > 0) {
  11159. this._rigCameras.pop().dispose();
  11160. }
  11161. // Postprocesses
  11162. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  11163. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  11164. }
  11165. _super.prototype.dispose.call(this);
  11166. };
  11167. // ---- Camera rigs section ----
  11168. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  11169. while (this._rigCameras.length > 0) {
  11170. this._rigCameras.pop().dispose();
  11171. }
  11172. this.cameraRigMode = mode;
  11173. this._cameraRigParams = {};
  11174. switch (this.cameraRigMode) {
  11175. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11176. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11177. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11178. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11179. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  11180. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  11181. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  11182. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  11183. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  11184. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  11185. break;
  11186. }
  11187. var postProcesses = new Array();
  11188. switch (this.cameraRigMode) {
  11189. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11190. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  11191. this._rigCameras[0].isIntermediate = true;
  11192. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  11193. postProcesses[1].onApply = function (effect) {
  11194. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  11195. };
  11196. break;
  11197. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11198. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11199. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11200. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  11201. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  11202. var secondCamIndex = 1 - firstCamIndex;
  11203. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  11204. this._rigCameras[firstCamIndex].isIntermediate = true;
  11205. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  11206. break;
  11207. case Camera.RIG_MODE_VR:
  11208. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  11209. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  11210. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  11211. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  11212. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  11213. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  11214. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  11215. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11216. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  11217. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  11218. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  11219. if (metrics.compensateDistortion) {
  11220. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  11221. }
  11222. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  11223. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  11224. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  11225. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  11226. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  11227. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  11228. if (metrics.compensateDistortion) {
  11229. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  11230. }
  11231. break;
  11232. }
  11233. this._update();
  11234. };
  11235. Camera.prototype._getVRProjectionMatrix = function () {
  11236. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  11237. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  11238. return this._projectionMatrix;
  11239. };
  11240. Camera.prototype.setCameraRigParameter = function (name, value) {
  11241. this._cameraRigParams[name] = value;
  11242. //provisionnally:
  11243. if (name === "interaxialDistance") {
  11244. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  11245. }
  11246. };
  11247. /**
  11248. * May needs to be overridden by children so sub has required properties to be copied
  11249. */
  11250. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  11251. return null;
  11252. };
  11253. /**
  11254. * May needs to be overridden by children
  11255. */
  11256. Camera.prototype._updateRigCameras = function () {
  11257. for (var i = 0; i < this._rigCameras.length; i++) {
  11258. this._rigCameras[i].minZ = this.minZ;
  11259. this._rigCameras[i].maxZ = this.maxZ;
  11260. this._rigCameras[i].fov = this.fov;
  11261. }
  11262. // only update viewport when ANAGLYPH
  11263. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  11264. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  11265. }
  11266. };
  11267. Camera.prototype.serialize = function () {
  11268. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11269. // Type
  11270. serializationObject.type = this.getTypeName();
  11271. // Parent
  11272. if (this.parent) {
  11273. serializationObject.parentId = this.parent.id;
  11274. }
  11275. if (this.inputs) {
  11276. this.inputs.serialize(serializationObject);
  11277. }
  11278. // Animations
  11279. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11280. serializationObject.ranges = this.serializeAnimationRanges();
  11281. return serializationObject;
  11282. };
  11283. Camera.prototype.getTypeName = function () {
  11284. return "Camera";
  11285. };
  11286. Camera.prototype.clone = function (name) {
  11287. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  11288. };
  11289. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  11290. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  11291. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  11292. switch (type) {
  11293. case "ArcRotateCamera":
  11294. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  11295. case "DeviceOrientationCamera":
  11296. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  11297. case "FollowCamera":
  11298. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  11299. case "ArcFollowCamera":
  11300. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  11301. case "GamepadCamera":
  11302. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  11303. case "TouchCamera":
  11304. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  11305. case "VirtualJoysticksCamera":
  11306. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  11307. case "WebVRFreeCamera":
  11308. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11309. case "VRDeviceOrientationFreeCamera":
  11310. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  11311. case "AnaglyphArcRotateCamera":
  11312. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11313. case "AnaglyphFreeCamera":
  11314. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11315. case "AnaglyphGamepadCamera":
  11316. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11317. case "AnaglyphUniversalCamera":
  11318. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  11319. case "StereoscopicArcRotateCamera":
  11320. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11321. case "StereoscopicFreeCamera":
  11322. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11323. case "StereoscopicGamepadCamera":
  11324. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11325. case "StereoscopicUniversalCamera":
  11326. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  11327. case "FreeCamera":
  11328. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11329. default:
  11330. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  11331. }
  11332. };
  11333. Camera.Parse = function (parsedCamera, scene) {
  11334. var type = parsedCamera.type;
  11335. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  11336. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  11337. // Parent
  11338. if (parsedCamera.parentId) {
  11339. camera._waitingParentId = parsedCamera.parentId;
  11340. }
  11341. //If camera has an input manager, let it parse inputs settings
  11342. if (camera.inputs) {
  11343. camera.inputs.parse(parsedCamera);
  11344. }
  11345. // Target
  11346. if (parsedCamera.target) {
  11347. if (camera.setTarget) {
  11348. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  11349. }
  11350. }
  11351. // Apply 3d rig, when found
  11352. if (parsedCamera.cameraRigMode) {
  11353. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  11354. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  11355. }
  11356. // Animations
  11357. if (parsedCamera.animations) {
  11358. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  11359. var parsedAnimation = parsedCamera.animations[animationIndex];
  11360. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11361. }
  11362. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  11363. }
  11364. if (parsedCamera.autoAnimate) {
  11365. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  11366. }
  11367. return camera;
  11368. };
  11369. // Statics
  11370. Camera._PERSPECTIVE_CAMERA = 0;
  11371. Camera._ORTHOGRAPHIC_CAMERA = 1;
  11372. Camera._FOVMODE_VERTICAL_FIXED = 0;
  11373. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  11374. Camera._RIG_MODE_NONE = 0;
  11375. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  11376. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  11377. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  11378. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  11379. Camera._RIG_MODE_VR = 20;
  11380. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  11381. __decorate([
  11382. BABYLON.serializeAsVector3()
  11383. ], Camera.prototype, "position", void 0);
  11384. __decorate([
  11385. BABYLON.serializeAsVector3()
  11386. ], Camera.prototype, "upVector", void 0);
  11387. __decorate([
  11388. BABYLON.serialize()
  11389. ], Camera.prototype, "orthoLeft", void 0);
  11390. __decorate([
  11391. BABYLON.serialize()
  11392. ], Camera.prototype, "orthoRight", void 0);
  11393. __decorate([
  11394. BABYLON.serialize()
  11395. ], Camera.prototype, "orthoBottom", void 0);
  11396. __decorate([
  11397. BABYLON.serialize()
  11398. ], Camera.prototype, "orthoTop", void 0);
  11399. __decorate([
  11400. BABYLON.serialize()
  11401. ], Camera.prototype, "fov", void 0);
  11402. __decorate([
  11403. BABYLON.serialize()
  11404. ], Camera.prototype, "minZ", void 0);
  11405. __decorate([
  11406. BABYLON.serialize()
  11407. ], Camera.prototype, "maxZ", void 0);
  11408. __decorate([
  11409. BABYLON.serialize()
  11410. ], Camera.prototype, "inertia", void 0);
  11411. __decorate([
  11412. BABYLON.serialize()
  11413. ], Camera.prototype, "mode", void 0);
  11414. __decorate([
  11415. BABYLON.serialize()
  11416. ], Camera.prototype, "layerMask", void 0);
  11417. __decorate([
  11418. BABYLON.serialize()
  11419. ], Camera.prototype, "fovMode", void 0);
  11420. __decorate([
  11421. BABYLON.serialize()
  11422. ], Camera.prototype, "cameraRigMode", void 0);
  11423. __decorate([
  11424. BABYLON.serialize()
  11425. ], Camera.prototype, "interaxialDistance", void 0);
  11426. __decorate([
  11427. BABYLON.serialize()
  11428. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  11429. return Camera;
  11430. })(BABYLON.Node);
  11431. BABYLON.Camera = Camera;
  11432. })(BABYLON || (BABYLON = {}));
  11433. var BABYLON;
  11434. (function (BABYLON) {
  11435. BABYLON.CameraInputTypes = {};
  11436. var CameraInputsManager = (function () {
  11437. function CameraInputsManager(camera) {
  11438. this.attached = {};
  11439. this.camera = camera;
  11440. this.checkInputs = function () { };
  11441. }
  11442. CameraInputsManager.prototype.add = function (input) {
  11443. var type = input.getSimpleName();
  11444. if (this.attached[type]) {
  11445. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  11446. return;
  11447. }
  11448. this.attached[type] = input;
  11449. input.camera = this.camera;
  11450. //for checkInputs, we are dynamically creating a function
  11451. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  11452. if (input.checkInputs) {
  11453. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11454. }
  11455. if (this.attachedElement) {
  11456. input.attachControl(this.attachedElement);
  11457. }
  11458. };
  11459. CameraInputsManager.prototype.remove = function (inputToRemove) {
  11460. for (var cam in this.attached) {
  11461. var input = this.attached[cam];
  11462. if (input === inputToRemove) {
  11463. input.detachControl(this.attachedElement);
  11464. delete this.attached[cam];
  11465. this.rebuildInputCheck();
  11466. }
  11467. }
  11468. };
  11469. CameraInputsManager.prototype.removeByType = function (inputType) {
  11470. for (var cam in this.attached) {
  11471. var input = this.attached[cam];
  11472. if (input.getTypeName() === inputType) {
  11473. input.detachControl(this.attachedElement);
  11474. delete this.attached[cam];
  11475. this.rebuildInputCheck();
  11476. }
  11477. }
  11478. };
  11479. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  11480. var current = this.checkInputs;
  11481. return function () {
  11482. current();
  11483. fn();
  11484. };
  11485. };
  11486. CameraInputsManager.prototype.attachInput = function (input) {
  11487. input.attachControl(this.attachedElement, this.noPreventDefault);
  11488. };
  11489. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  11490. if (this.attachedElement) {
  11491. return;
  11492. }
  11493. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  11494. this.attachedElement = element;
  11495. this.noPreventDefault = noPreventDefault;
  11496. for (var cam in this.attached) {
  11497. var input = this.attached[cam];
  11498. this.attached[cam].attachControl(element, noPreventDefault);
  11499. }
  11500. };
  11501. CameraInputsManager.prototype.detachElement = function (element) {
  11502. if (this.attachedElement !== element) {
  11503. return;
  11504. }
  11505. for (var cam in this.attached) {
  11506. var input = this.attached[cam];
  11507. this.attached[cam].detachControl(element);
  11508. }
  11509. this.attachedElement = null;
  11510. };
  11511. CameraInputsManager.prototype.rebuildInputCheck = function () {
  11512. this.checkInputs = function () { };
  11513. for (var cam in this.attached) {
  11514. var input = this.attached[cam];
  11515. if (input.checkInputs) {
  11516. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  11517. }
  11518. }
  11519. };
  11520. CameraInputsManager.prototype.clear = function () {
  11521. if (this.attachedElement) {
  11522. this.detachElement(this.attachedElement);
  11523. }
  11524. this.attached = {};
  11525. this.attachedElement = null;
  11526. this.checkInputs = function () { };
  11527. };
  11528. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  11529. var inputs = {};
  11530. for (var cam in this.attached) {
  11531. var input = this.attached[cam];
  11532. var res = BABYLON.SerializationHelper.Serialize(input);
  11533. inputs[input.getTypeName()] = res;
  11534. }
  11535. serializedCamera.inputsmgr = inputs;
  11536. };
  11537. CameraInputsManager.prototype.parse = function (parsedCamera) {
  11538. var parsedInputs = parsedCamera.inputsmgr;
  11539. if (parsedInputs) {
  11540. this.clear();
  11541. for (var n in parsedInputs) {
  11542. var construct = BABYLON.CameraInputTypes[n];
  11543. if (construct) {
  11544. var parsedinput = parsedInputs[n];
  11545. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  11546. this.add(input);
  11547. }
  11548. }
  11549. }
  11550. else {
  11551. //2016-03-08 this part is for managing backward compatibility
  11552. for (var n in this.attached) {
  11553. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  11554. if (construct) {
  11555. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  11556. this.remove(this.attached[n]);
  11557. this.add(input);
  11558. }
  11559. }
  11560. }
  11561. };
  11562. return CameraInputsManager;
  11563. })();
  11564. BABYLON.CameraInputsManager = CameraInputsManager;
  11565. })(BABYLON || (BABYLON = {}));
  11566. var BABYLON;
  11567. (function (BABYLON) {
  11568. var FreeCameraMouseInput = (function () {
  11569. function FreeCameraMouseInput() {
  11570. this.angularSensibility = 2000.0;
  11571. }
  11572. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  11573. var _this = this;
  11574. if (!this._pointerInput) {
  11575. var camera = this.camera;
  11576. var engine = this.camera.getEngine();
  11577. this._pointerInput = function (p, s) {
  11578. var evt = p.event;
  11579. if (evt.pointerType === "touch") {
  11580. return;
  11581. }
  11582. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  11583. try {
  11584. evt.srcElement.setPointerCapture(evt.pointerId);
  11585. }
  11586. catch (e) {
  11587. }
  11588. _this.previousPosition = {
  11589. x: evt.clientX,
  11590. y: evt.clientY
  11591. };
  11592. if (!noPreventDefault) {
  11593. evt.preventDefault();
  11594. }
  11595. }
  11596. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  11597. try {
  11598. evt.srcElement.releasePointerCapture(evt.pointerId);
  11599. }
  11600. catch (e) {
  11601. }
  11602. _this.previousPosition = null;
  11603. if (!noPreventDefault) {
  11604. evt.preventDefault();
  11605. }
  11606. }
  11607. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  11608. if (!_this.previousPosition && !engine.isPointerLock) {
  11609. return;
  11610. }
  11611. var offsetX;
  11612. var offsetY;
  11613. if (!engine.isPointerLock) {
  11614. offsetX = evt.clientX - _this.previousPosition.x;
  11615. offsetY = evt.clientY - _this.previousPosition.y;
  11616. }
  11617. else {
  11618. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  11619. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  11620. }
  11621. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  11622. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  11623. _this.previousPosition = {
  11624. x: evt.clientX,
  11625. y: evt.clientY
  11626. };
  11627. if (!noPreventDefault) {
  11628. evt.preventDefault();
  11629. }
  11630. }
  11631. };
  11632. }
  11633. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  11634. };
  11635. FreeCameraMouseInput.prototype.detachControl = function (element) {
  11636. if (this._observer && element) {
  11637. this.camera.getScene().onPointerObservable.remove(this._observer);
  11638. this._observer = null;
  11639. this.previousPosition = null;
  11640. }
  11641. };
  11642. FreeCameraMouseInput.prototype.getTypeName = function () {
  11643. return "FreeCameraMouseInput";
  11644. };
  11645. FreeCameraMouseInput.prototype.getSimpleName = function () {
  11646. return "mouse";
  11647. };
  11648. __decorate([
  11649. BABYLON.serialize()
  11650. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  11651. return FreeCameraMouseInput;
  11652. })();
  11653. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  11654. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  11655. })(BABYLON || (BABYLON = {}));
  11656. var BABYLON;
  11657. (function (BABYLON) {
  11658. var FreeCameraKeyboardMoveInput = (function () {
  11659. function FreeCameraKeyboardMoveInput() {
  11660. this._keys = [];
  11661. this.keysUp = [38];
  11662. this.keysDown = [40];
  11663. this.keysLeft = [37];
  11664. this.keysRight = [39];
  11665. }
  11666. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  11667. var _this = this;
  11668. if (!this._onKeyDown) {
  11669. this._onKeyDown = function (evt) {
  11670. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11671. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11672. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11673. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11674. var index = _this._keys.indexOf(evt.keyCode);
  11675. if (index === -1) {
  11676. _this._keys.push(evt.keyCode);
  11677. }
  11678. if (!noPreventDefault) {
  11679. evt.preventDefault();
  11680. }
  11681. }
  11682. };
  11683. this._onKeyUp = function (evt) {
  11684. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  11685. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  11686. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  11687. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  11688. var index = _this._keys.indexOf(evt.keyCode);
  11689. if (index >= 0) {
  11690. _this._keys.splice(index, 1);
  11691. }
  11692. if (!noPreventDefault) {
  11693. evt.preventDefault();
  11694. }
  11695. }
  11696. };
  11697. BABYLON.Tools.RegisterTopRootEvents([
  11698. { name: "keydown", handler: this._onKeyDown },
  11699. { name: "keyup", handler: this._onKeyUp },
  11700. { name: "blur", handler: this._onLostFocus }
  11701. ]);
  11702. }
  11703. };
  11704. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  11705. if (this._onKeyDown) {
  11706. BABYLON.Tools.UnregisterTopRootEvents([
  11707. { name: "keydown", handler: this._onKeyDown },
  11708. { name: "keyup", handler: this._onKeyUp },
  11709. { name: "blur", handler: this._onLostFocus }
  11710. ]);
  11711. this._keys = [];
  11712. this._onKeyDown = null;
  11713. this._onKeyUp = null;
  11714. }
  11715. };
  11716. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  11717. if (this._onKeyDown) {
  11718. var camera = this.camera;
  11719. // Keyboard
  11720. for (var index = 0; index < this._keys.length; index++) {
  11721. var keyCode = this._keys[index];
  11722. var speed = camera._computeLocalCameraSpeed();
  11723. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11724. camera._localDirection.copyFromFloats(-speed, 0, 0);
  11725. }
  11726. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11727. camera._localDirection.copyFromFloats(0, 0, speed);
  11728. }
  11729. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11730. camera._localDirection.copyFromFloats(speed, 0, 0);
  11731. }
  11732. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11733. camera._localDirection.copyFromFloats(0, 0, -speed);
  11734. }
  11735. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  11736. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  11737. camera.cameraDirection.addInPlace(camera._transformedDirection);
  11738. }
  11739. }
  11740. };
  11741. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  11742. return "FreeCameraKeyboardMoveInput";
  11743. };
  11744. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  11745. this._keys = [];
  11746. };
  11747. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  11748. return "keyboard";
  11749. };
  11750. __decorate([
  11751. BABYLON.serialize()
  11752. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  11753. __decorate([
  11754. BABYLON.serialize()
  11755. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  11756. __decorate([
  11757. BABYLON.serialize()
  11758. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  11759. __decorate([
  11760. BABYLON.serialize()
  11761. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  11762. return FreeCameraKeyboardMoveInput;
  11763. })();
  11764. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  11765. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  11766. })(BABYLON || (BABYLON = {}));
  11767. var BABYLON;
  11768. (function (BABYLON) {
  11769. var FreeCameraTouchInput = (function () {
  11770. function FreeCameraTouchInput() {
  11771. this._offsetX = null;
  11772. this._offsetY = null;
  11773. this._pointerCount = 0;
  11774. this._pointerPressed = [];
  11775. this.touchAngularSensibility = 200000.0;
  11776. this.touchMoveSensibility = 250.0;
  11777. }
  11778. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  11779. var _this = this;
  11780. var previousPosition;
  11781. if (this._pointerInput === undefined) {
  11782. this._onLostFocus = function (evt) {
  11783. _this._offsetX = null;
  11784. _this._offsetY = null;
  11785. };
  11786. this._pointerInput = function (p, s) {
  11787. var evt = p.event;
  11788. if (evt.pointerType === "mouse") {
  11789. return;
  11790. }
  11791. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  11792. if (!noPreventDefault) {
  11793. evt.preventDefault();
  11794. }
  11795. _this._pointerPressed.push(evt.pointerId);
  11796. if (_this._pointerPressed.length !== 1) {
  11797. return;
  11798. }
  11799. previousPosition = {
  11800. x: evt.clientX,
  11801. y: evt.clientY
  11802. };
  11803. }
  11804. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  11805. if (!noPreventDefault) {
  11806. evt.preventDefault();
  11807. }
  11808. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11809. if (index === -1) {
  11810. return;
  11811. }
  11812. _this._pointerPressed.splice(index, 1);
  11813. if (index != 0) {
  11814. return;
  11815. }
  11816. previousPosition = null;
  11817. _this._offsetX = null;
  11818. _this._offsetY = null;
  11819. }
  11820. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  11821. if (!noPreventDefault) {
  11822. evt.preventDefault();
  11823. }
  11824. if (!previousPosition) {
  11825. return;
  11826. }
  11827. var index = _this._pointerPressed.indexOf(evt.pointerId);
  11828. if (index != 0) {
  11829. return;
  11830. }
  11831. _this._offsetX = evt.clientX - previousPosition.x;
  11832. _this._offsetY = -(evt.clientY - previousPosition.y);
  11833. }
  11834. };
  11835. }
  11836. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  11837. element.addEventListener("blur", this._onLostFocus);
  11838. };
  11839. FreeCameraTouchInput.prototype.detachControl = function (element) {
  11840. if (this._pointerInput && element) {
  11841. this.camera.getScene().onPointerObservable.remove(this._observer);
  11842. this._observer = null;
  11843. element.removeEventListener("blur", this._onLostFocus);
  11844. this._onLostFocus = null;
  11845. this._pointerPressed = [];
  11846. this._offsetX = null;
  11847. this._offsetY = null;
  11848. this._pointerCount = 0;
  11849. }
  11850. };
  11851. FreeCameraTouchInput.prototype.checkInputs = function () {
  11852. if (this._offsetX) {
  11853. var camera = this.camera;
  11854. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  11855. if (this._pointerPressed.length > 1) {
  11856. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  11857. }
  11858. else {
  11859. var speed = camera._computeLocalCameraSpeed();
  11860. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  11861. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  11862. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  11863. }
  11864. }
  11865. };
  11866. FreeCameraTouchInput.prototype.getTypeName = function () {
  11867. return "FreeCameraTouchInput";
  11868. };
  11869. FreeCameraTouchInput.prototype.getSimpleName = function () {
  11870. return "touch";
  11871. };
  11872. __decorate([
  11873. BABYLON.serialize()
  11874. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  11875. __decorate([
  11876. BABYLON.serialize()
  11877. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  11878. return FreeCameraTouchInput;
  11879. })();
  11880. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  11881. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  11882. })(BABYLON || (BABYLON = {}));
  11883. var BABYLON;
  11884. (function (BABYLON) {
  11885. var FreeCameraDeviceOrientationInput = (function () {
  11886. function FreeCameraDeviceOrientationInput() {
  11887. this._offsetX = null;
  11888. this._offsetY = null;
  11889. this._orientationGamma = 0;
  11890. this._orientationBeta = 0;
  11891. this._initialOrientationGamma = 0;
  11892. this._initialOrientationBeta = 0;
  11893. this.angularSensibility = 10000.0;
  11894. this.moveSensibility = 50.0;
  11895. this._resetOrientationGamma = this.resetOrientationGamma.bind(this);
  11896. this._orientationChanged = this.orientationChanged.bind(this);
  11897. }
  11898. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  11899. window.addEventListener("resize", this._resetOrientationGamma, false);
  11900. window.addEventListener("deviceorientation", this._orientationChanged);
  11901. };
  11902. FreeCameraDeviceOrientationInput.prototype.resetOrientationGamma = function () {
  11903. this._initialOrientationGamma = null;
  11904. };
  11905. FreeCameraDeviceOrientationInput.prototype.orientationChanged = function (evt) {
  11906. if (!this._initialOrientationGamma) {
  11907. this._initialOrientationGamma = evt.gamma;
  11908. this._initialOrientationBeta = evt.beta;
  11909. }
  11910. this._orientationGamma = evt.gamma;
  11911. this._orientationBeta = evt.beta;
  11912. this._offsetY = (this._initialOrientationBeta - this._orientationBeta);
  11913. this._offsetX = (this._initialOrientationGamma - this._orientationGamma);
  11914. };
  11915. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  11916. window.removeEventListener("resize", this._resetOrientationGamma);
  11917. window.removeEventListener("deviceorientation", this._orientationChanged);
  11918. this._orientationGamma = 0;
  11919. this._orientationBeta = 0;
  11920. this._initialOrientationGamma = 0;
  11921. this._initialOrientationBeta = 0;
  11922. this._offsetX = null;
  11923. this._offsetY = null;
  11924. };
  11925. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  11926. if (!this._offsetX) {
  11927. return;
  11928. }
  11929. var camera = this.camera;
  11930. camera.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11931. var speed = camera._computeLocalCameraSpeed();
  11932. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11933. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  11934. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  11935. };
  11936. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  11937. return "FreeCameraDeviceOrientationInput";
  11938. };
  11939. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  11940. return "deviceOrientation";
  11941. };
  11942. __decorate([
  11943. BABYLON.serialize()
  11944. ], FreeCameraDeviceOrientationInput.prototype, "angularSensibility", void 0);
  11945. __decorate([
  11946. BABYLON.serialize()
  11947. ], FreeCameraDeviceOrientationInput.prototype, "moveSensibility", void 0);
  11948. return FreeCameraDeviceOrientationInput;
  11949. })();
  11950. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  11951. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  11952. })(BABYLON || (BABYLON = {}));
  11953. var BABYLON;
  11954. (function (BABYLON) {
  11955. var FreeCameraVRDeviceOrientationInput = (function () {
  11956. function FreeCameraVRDeviceOrientationInput() {
  11957. this.alphaCorrection = 1;
  11958. this.betaCorrection = 1;
  11959. this.gammaCorrection = 1;
  11960. this._alpha = 0;
  11961. this._beta = 0;
  11962. this._gamma = 0;
  11963. this._dirty = false;
  11964. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  11965. }
  11966. FreeCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  11967. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  11968. };
  11969. FreeCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  11970. var camera = this.camera;
  11971. this._alpha = +evt.alpha | 0;
  11972. this._beta = +evt.beta | 0;
  11973. this._gamma = +evt.gamma | 0;
  11974. this._dirty = true;
  11975. };
  11976. FreeCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  11977. if (this._dirty) {
  11978. this._dirty = false;
  11979. var rotationX = this._gamma;
  11980. if (rotationX < 0) {
  11981. rotationX = 90 + rotationX;
  11982. }
  11983. else {
  11984. // Incline it in the correct angle.
  11985. rotationX = 270 - rotationX;
  11986. }
  11987. this.camera.rotation.x = this.gammaCorrection * rotationX / 180.0 * Math.PI;
  11988. this.camera.rotation.y = this.alphaCorrection * -this._alpha / 180.0 * Math.PI;
  11989. this.camera.rotation.z = this.betaCorrection * this._beta / 180.0 * Math.PI;
  11990. }
  11991. };
  11992. FreeCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  11993. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  11994. };
  11995. FreeCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  11996. return "FreeCameraVRDeviceOrientationInput";
  11997. };
  11998. FreeCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  11999. return "VRDeviceOrientation";
  12000. };
  12001. return FreeCameraVRDeviceOrientationInput;
  12002. })();
  12003. BABYLON.FreeCameraVRDeviceOrientationInput = FreeCameraVRDeviceOrientationInput;
  12004. BABYLON.CameraInputTypes["FreeCameraVRDeviceOrientationInput"] = FreeCameraVRDeviceOrientationInput;
  12005. })(BABYLON || (BABYLON = {}));
  12006. var BABYLON;
  12007. (function (BABYLON) {
  12008. var FreeCameraGamepadInput = (function () {
  12009. function FreeCameraGamepadInput() {
  12010. this.gamepadAngularSensibility = 200;
  12011. this.gamepadMoveSensibility = 40;
  12012. }
  12013. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12014. var _this = this;
  12015. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12016. };
  12017. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  12018. if (this._gamepads) {
  12019. this._gamepads.dispose();
  12020. }
  12021. this.gamepad = null;
  12022. };
  12023. FreeCameraGamepadInput.prototype.checkInputs = function () {
  12024. if (this.gamepad) {
  12025. var camera = this.camera;
  12026. var LSValues = this.gamepad.leftStick;
  12027. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  12028. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12029. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  12030. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  12031. var RSValues = this.gamepad.rightStick;
  12032. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  12033. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  12034. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  12035. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  12036. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  12037. var speed = camera._computeLocalCameraSpeed() * 50.0;
  12038. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  12039. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  12040. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  12041. }
  12042. };
  12043. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12044. // Only the first gamepad can control the camera
  12045. if (gamepad.index === 0) {
  12046. this.gamepad = gamepad;
  12047. }
  12048. };
  12049. FreeCameraGamepadInput.prototype.getTypeName = function () {
  12050. return "FreeCameraGamepadInput";
  12051. };
  12052. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  12053. return "gamepad";
  12054. };
  12055. __decorate([
  12056. BABYLON.serialize()
  12057. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  12058. __decorate([
  12059. BABYLON.serialize()
  12060. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12061. return FreeCameraGamepadInput;
  12062. })();
  12063. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  12064. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  12065. })(BABYLON || (BABYLON = {}));
  12066. var BABYLON;
  12067. (function (BABYLON) {
  12068. var FreeCameraVirtualJoystickInput = (function () {
  12069. function FreeCameraVirtualJoystickInput() {
  12070. }
  12071. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  12072. return this._leftjoystick;
  12073. };
  12074. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  12075. return this._rightjoystick;
  12076. };
  12077. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  12078. if (this._leftjoystick) {
  12079. var camera = this.camera;
  12080. var speed = camera._computeLocalCameraSpeed() * 50;
  12081. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  12082. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  12083. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  12084. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  12085. if (!this._leftjoystick.pressed) {
  12086. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  12087. }
  12088. if (!this._rightjoystick.pressed) {
  12089. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  12090. }
  12091. }
  12092. };
  12093. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  12094. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  12095. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  12096. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  12097. this._leftjoystick.setJoystickSensibility(0.15);
  12098. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  12099. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  12100. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  12101. this._rightjoystick.reverseUpDown = true;
  12102. this._rightjoystick.setJoystickSensibility(0.05);
  12103. this._rightjoystick.setJoystickColor("yellow");
  12104. };
  12105. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  12106. this._leftjoystick.releaseCanvas();
  12107. this._rightjoystick.releaseCanvas();
  12108. };
  12109. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  12110. return "FreeCameraVirtualJoystickInput";
  12111. };
  12112. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  12113. return "virtualJoystick";
  12114. };
  12115. return FreeCameraVirtualJoystickInput;
  12116. })();
  12117. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  12118. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  12119. })(BABYLON || (BABYLON = {}));
  12120. var BABYLON;
  12121. (function (BABYLON) {
  12122. var ArcRotateCameraKeyboardMoveInput = (function () {
  12123. function ArcRotateCameraKeyboardMoveInput() {
  12124. this._keys = [];
  12125. this.keysUp = [38];
  12126. this.keysDown = [40];
  12127. this.keysLeft = [37];
  12128. this.keysRight = [39];
  12129. }
  12130. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  12131. var _this = this;
  12132. this._onKeyDown = function (evt) {
  12133. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12134. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12135. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12136. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12137. var index = _this._keys.indexOf(evt.keyCode);
  12138. if (index === -1) {
  12139. _this._keys.push(evt.keyCode);
  12140. }
  12141. if (evt.preventDefault) {
  12142. if (!noPreventDefault) {
  12143. evt.preventDefault();
  12144. }
  12145. }
  12146. }
  12147. };
  12148. this._onKeyUp = function (evt) {
  12149. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  12150. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  12151. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  12152. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  12153. var index = _this._keys.indexOf(evt.keyCode);
  12154. if (index >= 0) {
  12155. _this._keys.splice(index, 1);
  12156. }
  12157. if (evt.preventDefault) {
  12158. if (!noPreventDefault) {
  12159. evt.preventDefault();
  12160. }
  12161. }
  12162. }
  12163. };
  12164. this._onLostFocus = function () {
  12165. _this._keys = [];
  12166. };
  12167. BABYLON.Tools.RegisterTopRootEvents([
  12168. { name: "keydown", handler: this._onKeyDown },
  12169. { name: "keyup", handler: this._onKeyUp },
  12170. { name: "blur", handler: this._onLostFocus }
  12171. ]);
  12172. };
  12173. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  12174. BABYLON.Tools.UnregisterTopRootEvents([
  12175. { name: "keydown", handler: this._onKeyDown },
  12176. { name: "keyup", handler: this._onKeyUp },
  12177. { name: "blur", handler: this._onLostFocus }
  12178. ]);
  12179. this._keys = [];
  12180. this._onKeyDown = null;
  12181. this._onKeyUp = null;
  12182. this._onLostFocus = null;
  12183. };
  12184. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  12185. if (this._onKeyDown) {
  12186. var camera = this.camera;
  12187. for (var index = 0; index < this._keys.length; index++) {
  12188. var keyCode = this._keys[index];
  12189. if (this.keysLeft.indexOf(keyCode) !== -1) {
  12190. camera.inertialAlphaOffset -= 0.01;
  12191. }
  12192. else if (this.keysUp.indexOf(keyCode) !== -1) {
  12193. camera.inertialBetaOffset -= 0.01;
  12194. }
  12195. else if (this.keysRight.indexOf(keyCode) !== -1) {
  12196. camera.inertialAlphaOffset += 0.01;
  12197. }
  12198. else if (this.keysDown.indexOf(keyCode) !== -1) {
  12199. camera.inertialBetaOffset += 0.01;
  12200. }
  12201. }
  12202. }
  12203. };
  12204. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  12205. return "ArcRotateCameraKeyboardMoveInput";
  12206. };
  12207. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  12208. return "keyboard";
  12209. };
  12210. __decorate([
  12211. BABYLON.serialize()
  12212. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  12213. __decorate([
  12214. BABYLON.serialize()
  12215. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  12216. __decorate([
  12217. BABYLON.serialize()
  12218. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  12219. __decorate([
  12220. BABYLON.serialize()
  12221. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  12222. return ArcRotateCameraKeyboardMoveInput;
  12223. })();
  12224. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  12225. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  12226. })(BABYLON || (BABYLON = {}));
  12227. var BABYLON;
  12228. (function (BABYLON) {
  12229. var ArcRotateCameraMouseWheelInput = (function () {
  12230. function ArcRotateCameraMouseWheelInput() {
  12231. this.wheelPrecision = 3.0;
  12232. }
  12233. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  12234. var _this = this;
  12235. this._wheel = function (p, s) {
  12236. //sanity check - this should be a PointerWheel event.
  12237. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  12238. return;
  12239. var event = p.event;
  12240. var delta = 0;
  12241. if (event.wheelDelta) {
  12242. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  12243. }
  12244. else if (event.detail) {
  12245. delta = -event.detail / _this.wheelPrecision;
  12246. }
  12247. if (delta)
  12248. _this.camera.inertialRadiusOffset += delta;
  12249. if (event.preventDefault) {
  12250. if (!noPreventDefault) {
  12251. event.preventDefault();
  12252. }
  12253. }
  12254. };
  12255. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  12256. };
  12257. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  12258. if (this._observer && element) {
  12259. this.camera.getScene().onPointerObservable.remove(this._observer);
  12260. this._observer = null;
  12261. this._wheel = null;
  12262. }
  12263. };
  12264. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  12265. return "ArcRotateCameraMouseWheelInput";
  12266. };
  12267. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  12268. return "mousewheel";
  12269. };
  12270. __decorate([
  12271. BABYLON.serialize()
  12272. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  12273. return ArcRotateCameraMouseWheelInput;
  12274. })();
  12275. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  12276. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  12277. })(BABYLON || (BABYLON = {}));
  12278. var BABYLON;
  12279. (function (BABYLON) {
  12280. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12281. var ArcRotateCameraPointersInput = (function () {
  12282. function ArcRotateCameraPointersInput() {
  12283. this.angularSensibilityX = 1000.0;
  12284. this.angularSensibilityY = 1000.0;
  12285. this.pinchPrecision = 6.0;
  12286. this.panningSensibility = 50.0;
  12287. this._isRightClick = false;
  12288. this._isCtrlPushed = false;
  12289. this.pinchInwards = true;
  12290. }
  12291. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  12292. var _this = this;
  12293. var engine = this.camera.getEngine();
  12294. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  12295. var pointers = new BABYLON.SmartCollection();
  12296. var previousPinchDistance = 0;
  12297. this._pointerInput = function (p, s) {
  12298. var evt = p.event;
  12299. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  12300. try {
  12301. evt.srcElement.setPointerCapture(evt.pointerId);
  12302. }
  12303. catch (e) {
  12304. }
  12305. // Manage panning with right click
  12306. _this._isRightClick = evt.button === 2;
  12307. // manage pointers
  12308. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  12309. cacheSoloPointer = pointers.item(evt.pointerId);
  12310. if (!noPreventDefault) {
  12311. evt.preventDefault();
  12312. }
  12313. }
  12314. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  12315. try {
  12316. evt.srcElement.releasePointerCapture(evt.pointerId);
  12317. }
  12318. catch (e) {
  12319. }
  12320. cacheSoloPointer = null;
  12321. previousPinchDistance = 0;
  12322. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  12323. //but emptying completly pointers collection is required to fix a bug on iPhone :
  12324. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  12325. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  12326. pointers.empty();
  12327. if (!noPreventDefault) {
  12328. evt.preventDefault();
  12329. }
  12330. }
  12331. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  12332. if (!noPreventDefault) {
  12333. evt.preventDefault();
  12334. }
  12335. switch (pointers.count) {
  12336. case 1:
  12337. if (_this.panningSensibility !== 0 && ((_this._isCtrlPushed && _this.camera._useCtrlForPanning) || (!_this.camera._useCtrlForPanning && _this._isRightClick))) {
  12338. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  12339. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  12340. }
  12341. else {
  12342. var offsetX = evt.clientX - cacheSoloPointer.x;
  12343. var offsetY = evt.clientY - cacheSoloPointer.y;
  12344. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12345. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12346. }
  12347. cacheSoloPointer.x = evt.clientX;
  12348. cacheSoloPointer.y = evt.clientY;
  12349. break;
  12350. case 2:
  12351. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  12352. pointers.item(evt.pointerId).x = evt.clientX;
  12353. pointers.item(evt.pointerId).y = evt.clientY;
  12354. var direction = _this.pinchInwards ? 1 : -1;
  12355. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  12356. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  12357. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  12358. if (previousPinchDistance === 0) {
  12359. previousPinchDistance = pinchSquaredDistance;
  12360. return;
  12361. }
  12362. if (pinchSquaredDistance !== previousPinchDistance) {
  12363. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) * direction);
  12364. previousPinchDistance = pinchSquaredDistance;
  12365. }
  12366. break;
  12367. default:
  12368. if (pointers.item(evt.pointerId)) {
  12369. pointers.item(evt.pointerId).x = evt.clientX;
  12370. pointers.item(evt.pointerId).y = evt.clientY;
  12371. }
  12372. }
  12373. }
  12374. };
  12375. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  12376. this._onContextMenu = function (evt) {
  12377. evt.preventDefault();
  12378. };
  12379. if (!this.camera._useCtrlForPanning) {
  12380. element.addEventListener("contextmenu", this._onContextMenu, false);
  12381. }
  12382. this._onLostFocus = function () {
  12383. //this._keys = [];
  12384. pointers.empty();
  12385. previousPinchDistance = 0;
  12386. cacheSoloPointer = null;
  12387. };
  12388. this._onKeyDown = function (evt) {
  12389. _this._isCtrlPushed = evt.ctrlKey;
  12390. };
  12391. this._onKeyUp = function (evt) {
  12392. _this._isCtrlPushed = evt.ctrlKey;
  12393. };
  12394. this._onMouseMove = function (evt) {
  12395. if (!engine.isPointerLock) {
  12396. return;
  12397. }
  12398. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  12399. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  12400. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  12401. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  12402. if (!noPreventDefault) {
  12403. evt.preventDefault();
  12404. }
  12405. };
  12406. this._onGestureStart = function (e) {
  12407. if (window.MSGesture === undefined) {
  12408. return;
  12409. }
  12410. if (!_this._MSGestureHandler) {
  12411. _this._MSGestureHandler = new MSGesture();
  12412. _this._MSGestureHandler.target = element;
  12413. }
  12414. _this._MSGestureHandler.addPointer(e.pointerId);
  12415. };
  12416. this._onGesture = function (e) {
  12417. _this.camera.radius *= e.scale;
  12418. if (e.preventDefault) {
  12419. if (!noPreventDefault) {
  12420. e.stopPropagation();
  12421. e.preventDefault();
  12422. }
  12423. }
  12424. };
  12425. element.addEventListener("mousemove", this._onMouseMove, false);
  12426. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  12427. element.addEventListener("MSGestureChange", this._onGesture, false);
  12428. BABYLON.Tools.RegisterTopRootEvents([
  12429. { name: "keydown", handler: this._onKeyDown },
  12430. { name: "keyup", handler: this._onKeyUp },
  12431. { name: "blur", handler: this._onLostFocus }
  12432. ]);
  12433. };
  12434. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  12435. if (element && this._observer) {
  12436. this.camera.getScene().onPointerObservable.remove(this._observer);
  12437. this._observer = null;
  12438. element.removeEventListener("contextmenu", this._onContextMenu);
  12439. element.removeEventListener("mousemove", this._onMouseMove);
  12440. element.removeEventListener("MSPointerDown", this._onGestureStart);
  12441. element.removeEventListener("MSGestureChange", this._onGesture);
  12442. this._isRightClick = false;
  12443. this._isCtrlPushed = false;
  12444. this.pinchInwards = true;
  12445. this._onKeyDown = null;
  12446. this._onKeyUp = null;
  12447. this._onMouseMove = null;
  12448. this._onGestureStart = null;
  12449. this._onGesture = null;
  12450. this._MSGestureHandler = null;
  12451. this._onLostFocus = null;
  12452. this._onContextMenu = null;
  12453. }
  12454. BABYLON.Tools.UnregisterTopRootEvents([
  12455. { name: "keydown", handler: this._onKeyDown },
  12456. { name: "keyup", handler: this._onKeyUp },
  12457. { name: "blur", handler: this._onLostFocus }
  12458. ]);
  12459. };
  12460. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  12461. return "ArcRotateCameraPointersInput";
  12462. };
  12463. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  12464. return "pointers";
  12465. };
  12466. __decorate([
  12467. BABYLON.serialize()
  12468. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  12469. __decorate([
  12470. BABYLON.serialize()
  12471. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  12472. __decorate([
  12473. BABYLON.serialize()
  12474. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  12475. __decorate([
  12476. BABYLON.serialize()
  12477. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  12478. return ArcRotateCameraPointersInput;
  12479. })();
  12480. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  12481. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  12482. })(BABYLON || (BABYLON = {}));
  12483. var BABYLON;
  12484. (function (BABYLON) {
  12485. var ArcRotateCameraGamepadInput = (function () {
  12486. function ArcRotateCameraGamepadInput() {
  12487. this.gamepadRotationSensibility = 80;
  12488. this.gamepadMoveSensibility = 40;
  12489. }
  12490. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  12491. var _this = this;
  12492. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  12493. };
  12494. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  12495. if (this._gamepads) {
  12496. this._gamepads.dispose();
  12497. }
  12498. this.gamepad = null;
  12499. };
  12500. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  12501. if (this.gamepad) {
  12502. var camera = this.camera;
  12503. var RSValues = this.gamepad.rightStick;
  12504. if (RSValues.x != 0) {
  12505. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  12506. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  12507. camera.inertialAlphaOffset += normalizedRX;
  12508. }
  12509. }
  12510. if (RSValues.y != 0) {
  12511. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  12512. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  12513. camera.inertialBetaOffset += normalizedRY;
  12514. }
  12515. }
  12516. var LSValues = this.gamepad.leftStick;
  12517. if (LSValues.y != 0) {
  12518. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  12519. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  12520. this.camera.inertialRadiusOffset -= normalizedLY;
  12521. }
  12522. }
  12523. }
  12524. };
  12525. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  12526. // Only the first gamepad can control the camera
  12527. if (gamepad.index === 0) {
  12528. this.gamepad = gamepad;
  12529. }
  12530. };
  12531. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  12532. return "ArcRotateCameraGamepadInput";
  12533. };
  12534. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  12535. return "gamepad";
  12536. };
  12537. __decorate([
  12538. BABYLON.serialize()
  12539. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  12540. __decorate([
  12541. BABYLON.serialize()
  12542. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  12543. return ArcRotateCameraGamepadInput;
  12544. })();
  12545. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  12546. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  12547. })(BABYLON || (BABYLON = {}));
  12548. var BABYLON;
  12549. (function (BABYLON) {
  12550. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  12551. function ArcRotateCameraVRDeviceOrientationInput() {
  12552. this.alphaCorrection = 1;
  12553. this.betaCorrection = 1;
  12554. this.gammaCorrection = 1;
  12555. this._alpha = 0;
  12556. this._beta = 0;
  12557. this._gamma = 0;
  12558. this._dirty = false;
  12559. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  12560. }
  12561. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  12562. this.camera.attachControl(element, noPreventDefault);
  12563. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  12564. };
  12565. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  12566. var camera = this.camera;
  12567. this._alpha = +evt.alpha | 0;
  12568. this._beta = +evt.beta | 0;
  12569. this._gamma = +evt.gamma | 0;
  12570. this._dirty = true;
  12571. };
  12572. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  12573. if (this._dirty) {
  12574. this._dirty = false;
  12575. if (this._gamma < 0) {
  12576. this._gamma = 180 + this._gamma;
  12577. }
  12578. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  12579. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  12580. }
  12581. };
  12582. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  12583. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  12584. };
  12585. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  12586. return "ArcRotateCameraVRDeviceOrientationInput";
  12587. };
  12588. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  12589. return "VRDeviceOrientation";
  12590. };
  12591. return ArcRotateCameraVRDeviceOrientationInput;
  12592. })();
  12593. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  12594. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  12595. })(BABYLON || (BABYLON = {}));
  12596. var BABYLON;
  12597. (function (BABYLON) {
  12598. var TargetCamera = (function (_super) {
  12599. __extends(TargetCamera, _super);
  12600. function TargetCamera(name, position, scene) {
  12601. _super.call(this, name, position, scene);
  12602. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  12603. this.cameraRotation = new BABYLON.Vector2(0, 0);
  12604. this.rotation = new BABYLON.Vector3(0, 0, 0);
  12605. this.speed = 2.0;
  12606. this.noRotationConstraint = false;
  12607. this.lockedTarget = null;
  12608. this._currentTarget = BABYLON.Vector3.Zero();
  12609. this._viewMatrix = BABYLON.Matrix.Zero();
  12610. this._camMatrix = BABYLON.Matrix.Zero();
  12611. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  12612. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  12613. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  12614. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  12615. this._lookAtTemp = BABYLON.Matrix.Zero();
  12616. this._tempMatrix = BABYLON.Matrix.Zero();
  12617. }
  12618. TargetCamera.prototype.getFrontPosition = function (distance) {
  12619. var direction = this.getTarget().subtract(this.position);
  12620. direction.normalize();
  12621. direction.scaleInPlace(distance);
  12622. return this.globalPosition.add(direction);
  12623. };
  12624. TargetCamera.prototype._getLockedTargetPosition = function () {
  12625. if (!this.lockedTarget) {
  12626. return null;
  12627. }
  12628. return this.lockedTarget.position || this.lockedTarget;
  12629. };
  12630. // Cache
  12631. TargetCamera.prototype._initCache = function () {
  12632. _super.prototype._initCache.call(this);
  12633. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12634. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12635. };
  12636. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  12637. if (!ignoreParentClass) {
  12638. _super.prototype._updateCache.call(this);
  12639. }
  12640. var lockedTargetPosition = this._getLockedTargetPosition();
  12641. if (!lockedTargetPosition) {
  12642. this._cache.lockedTarget = null;
  12643. }
  12644. else {
  12645. if (!this._cache.lockedTarget) {
  12646. this._cache.lockedTarget = lockedTargetPosition.clone();
  12647. }
  12648. else {
  12649. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  12650. }
  12651. }
  12652. this._cache.rotation.copyFrom(this.rotation);
  12653. };
  12654. // Synchronized
  12655. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  12656. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  12657. return false;
  12658. }
  12659. var lockedTargetPosition = this._getLockedTargetPosition();
  12660. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  12661. && this._cache.rotation.equals(this.rotation);
  12662. };
  12663. // Methods
  12664. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  12665. var engine = this.getEngine();
  12666. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  12667. };
  12668. // Target
  12669. TargetCamera.prototype.setTarget = function (target) {
  12670. this.upVector.normalize();
  12671. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  12672. this._camMatrix.invert();
  12673. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  12674. var vDir = target.subtract(this.position);
  12675. if (vDir.x >= 0.0) {
  12676. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  12677. }
  12678. else {
  12679. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  12680. }
  12681. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  12682. if (isNaN(this.rotation.x)) {
  12683. this.rotation.x = 0;
  12684. }
  12685. if (isNaN(this.rotation.y)) {
  12686. this.rotation.y = 0;
  12687. }
  12688. if (isNaN(this.rotation.z)) {
  12689. this.rotation.z = 0;
  12690. }
  12691. };
  12692. TargetCamera.prototype.getTarget = function () {
  12693. return this._currentTarget;
  12694. };
  12695. TargetCamera.prototype._decideIfNeedsToMove = function () {
  12696. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  12697. };
  12698. TargetCamera.prototype._updatePosition = function () {
  12699. this.position.addInPlace(this.cameraDirection);
  12700. };
  12701. TargetCamera.prototype._checkInputs = function () {
  12702. var needToMove = this._decideIfNeedsToMove();
  12703. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  12704. // Move
  12705. if (needToMove) {
  12706. this._updatePosition();
  12707. }
  12708. // Rotate
  12709. if (needToRotate) {
  12710. this.rotation.x += this.cameraRotation.x;
  12711. this.rotation.y += this.cameraRotation.y;
  12712. if (!this.noRotationConstraint) {
  12713. var limit = (Math.PI / 2) * 0.95;
  12714. if (this.rotation.x > limit)
  12715. this.rotation.x = limit;
  12716. if (this.rotation.x < -limit)
  12717. this.rotation.x = -limit;
  12718. }
  12719. }
  12720. // Inertia
  12721. if (needToMove) {
  12722. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  12723. this.cameraDirection.x = 0;
  12724. }
  12725. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  12726. this.cameraDirection.y = 0;
  12727. }
  12728. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  12729. this.cameraDirection.z = 0;
  12730. }
  12731. this.cameraDirection.scaleInPlace(this.inertia);
  12732. }
  12733. if (needToRotate) {
  12734. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  12735. this.cameraRotation.x = 0;
  12736. }
  12737. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  12738. this.cameraRotation.y = 0;
  12739. }
  12740. this.cameraRotation.scaleInPlace(this.inertia);
  12741. }
  12742. _super.prototype._checkInputs.call(this);
  12743. };
  12744. TargetCamera.prototype._getViewMatrix = function () {
  12745. if (!this.lockedTarget) {
  12746. // Compute
  12747. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  12748. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  12749. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12750. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  12751. this._lookAtTemp.invert();
  12752. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  12753. }
  12754. else {
  12755. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12756. }
  12757. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12758. // Computing target and final matrix
  12759. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12760. }
  12761. else {
  12762. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  12763. }
  12764. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  12765. return this._viewMatrix;
  12766. };
  12767. TargetCamera.prototype._getVRViewMatrix = function () {
  12768. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  12769. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  12770. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  12771. // Computing target and final matrix
  12772. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  12773. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  12774. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  12775. return this._viewMatrix;
  12776. };
  12777. /**
  12778. * @override
  12779. * Override Camera.createRigCamera
  12780. */
  12781. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  12782. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  12783. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  12784. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  12785. rigCamera._cameraRigParams = {};
  12786. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  12787. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  12788. }
  12789. return rigCamera;
  12790. }
  12791. return null;
  12792. };
  12793. /**
  12794. * @override
  12795. * Override Camera._updateRigCameras
  12796. */
  12797. TargetCamera.prototype._updateRigCameras = function () {
  12798. switch (this.cameraRigMode) {
  12799. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12800. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12801. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12802. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12803. case BABYLON.Camera.RIG_MODE_VR:
  12804. var camLeft = this._rigCameras[0];
  12805. var camRight = this._rigCameras[1];
  12806. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  12807. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  12808. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  12809. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  12810. camLeft.position.copyFrom(this.position);
  12811. camRight.position.copyFrom(this.position);
  12812. }
  12813. else {
  12814. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  12815. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  12816. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  12817. camLeft.setTarget(this.getTarget());
  12818. camRight.setTarget(this.getTarget());
  12819. }
  12820. break;
  12821. }
  12822. _super.prototype._updateRigCameras.call(this);
  12823. };
  12824. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  12825. if (!this._rigCamTransformMatrix) {
  12826. this._rigCamTransformMatrix = new BABYLON.Matrix();
  12827. }
  12828. var target = this.getTarget();
  12829. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  12830. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  12831. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  12832. };
  12833. TargetCamera.prototype.getTypeName = function () {
  12834. return "TargetCamera";
  12835. };
  12836. __decorate([
  12837. BABYLON.serializeAsVector3()
  12838. ], TargetCamera.prototype, "rotation", void 0);
  12839. __decorate([
  12840. BABYLON.serialize()
  12841. ], TargetCamera.prototype, "speed", void 0);
  12842. __decorate([
  12843. BABYLON.serializeAsMeshReference("lockedTargetId")
  12844. ], TargetCamera.prototype, "lockedTarget", void 0);
  12845. return TargetCamera;
  12846. })(BABYLON.Camera);
  12847. BABYLON.TargetCamera = TargetCamera;
  12848. })(BABYLON || (BABYLON = {}));
  12849. var BABYLON;
  12850. (function (BABYLON) {
  12851. var FreeCamera = (function (_super) {
  12852. __extends(FreeCamera, _super);
  12853. function FreeCamera(name, position, scene) {
  12854. var _this = this;
  12855. _super.call(this, name, position, scene);
  12856. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12857. this.checkCollisions = false;
  12858. this.applyGravity = false;
  12859. this._collider = new BABYLON.Collider();
  12860. this._needMoveForGravity = false;
  12861. this._oldPosition = BABYLON.Vector3.Zero();
  12862. this._diffPosition = BABYLON.Vector3.Zero();
  12863. this._newPosition = BABYLON.Vector3.Zero();
  12864. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  12865. if (collidedMesh === void 0) { collidedMesh = null; }
  12866. //TODO move this to the collision coordinator!
  12867. if (_this.getScene().workerCollisions)
  12868. newPosition.multiplyInPlace(_this._collider.radius);
  12869. var updatePosition = function (newPos) {
  12870. _this._newPosition.copyFrom(newPos);
  12871. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  12872. var oldPosition = _this.position.clone();
  12873. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  12874. _this.position.addInPlace(_this._diffPosition);
  12875. if (_this.onCollide && collidedMesh) {
  12876. _this.onCollide(collidedMesh);
  12877. }
  12878. }
  12879. };
  12880. updatePosition(newPosition);
  12881. };
  12882. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  12883. this.inputs.addKeyboard().addMouse();
  12884. }
  12885. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  12886. //-- begin properties for backward compatibility for inputs
  12887. get: function () {
  12888. var mouse = this.inputs.attached["mouse"];
  12889. if (mouse)
  12890. return mouse.angularSensibility;
  12891. },
  12892. set: function (value) {
  12893. var mouse = this.inputs.attached["mouse"];
  12894. if (mouse)
  12895. mouse.angularSensibility = value;
  12896. },
  12897. enumerable: true,
  12898. configurable: true
  12899. });
  12900. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  12901. get: function () {
  12902. var keyboard = this.inputs.attached["keyboard"];
  12903. if (keyboard)
  12904. return keyboard.keysUp;
  12905. },
  12906. set: function (value) {
  12907. var keyboard = this.inputs.attached["keyboard"];
  12908. if (keyboard)
  12909. keyboard.keysUp = value;
  12910. },
  12911. enumerable: true,
  12912. configurable: true
  12913. });
  12914. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  12915. get: function () {
  12916. var keyboard = this.inputs.attached["keyboard"];
  12917. if (keyboard)
  12918. return keyboard.keysDown;
  12919. },
  12920. set: function (value) {
  12921. var keyboard = this.inputs.attached["keyboard"];
  12922. if (keyboard)
  12923. keyboard.keysDown = value;
  12924. },
  12925. enumerable: true,
  12926. configurable: true
  12927. });
  12928. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  12929. get: function () {
  12930. var keyboard = this.inputs.attached["keyboard"];
  12931. if (keyboard)
  12932. return keyboard.keysLeft;
  12933. },
  12934. set: function (value) {
  12935. var keyboard = this.inputs.attached["keyboard"];
  12936. if (keyboard)
  12937. keyboard.keysLeft = value;
  12938. },
  12939. enumerable: true,
  12940. configurable: true
  12941. });
  12942. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  12943. get: function () {
  12944. var keyboard = this.inputs.attached["keyboard"];
  12945. if (keyboard)
  12946. return keyboard.keysRight;
  12947. },
  12948. set: function (value) {
  12949. var keyboard = this.inputs.attached["keyboard"];
  12950. if (keyboard)
  12951. keyboard.keysRight = value;
  12952. },
  12953. enumerable: true,
  12954. configurable: true
  12955. });
  12956. // Controls
  12957. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  12958. this.inputs.attachElement(element, noPreventDefault);
  12959. };
  12960. FreeCamera.prototype.detachControl = function (element) {
  12961. this.inputs.detachElement(element);
  12962. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  12963. this.cameraRotation = new BABYLON.Vector2(0, 0);
  12964. };
  12965. FreeCamera.prototype._collideWithWorld = function (velocity) {
  12966. var globalPosition;
  12967. if (this.parent) {
  12968. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  12969. }
  12970. else {
  12971. globalPosition = this.position;
  12972. }
  12973. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  12974. this._collider.radius = this.ellipsoid;
  12975. //no need for clone, as long as gravity is not on.
  12976. var actualVelocity = velocity;
  12977. //add gravity to the velocity to prevent the dual-collision checking
  12978. if (this.applyGravity) {
  12979. //this prevents mending with cameraDirection, a global variable of the free camera class.
  12980. actualVelocity = velocity.add(this.getScene().gravity);
  12981. }
  12982. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  12983. };
  12984. FreeCamera.prototype._checkInputs = function () {
  12985. if (!this._localDirection) {
  12986. this._localDirection = BABYLON.Vector3.Zero();
  12987. this._transformedDirection = BABYLON.Vector3.Zero();
  12988. }
  12989. this.inputs.checkInputs();
  12990. _super.prototype._checkInputs.call(this);
  12991. };
  12992. FreeCamera.prototype._decideIfNeedsToMove = function () {
  12993. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  12994. };
  12995. FreeCamera.prototype._updatePosition = function () {
  12996. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  12997. this._collideWithWorld(this.cameraDirection);
  12998. }
  12999. else {
  13000. this.position.addInPlace(this.cameraDirection);
  13001. }
  13002. };
  13003. FreeCamera.prototype.dispose = function () {
  13004. this.inputs.clear();
  13005. _super.prototype.dispose.call(this);
  13006. };
  13007. FreeCamera.prototype.getTypeName = function () {
  13008. return "FreeCamera";
  13009. };
  13010. __decorate([
  13011. BABYLON.serializeAsVector3()
  13012. ], FreeCamera.prototype, "ellipsoid", void 0);
  13013. __decorate([
  13014. BABYLON.serialize()
  13015. ], FreeCamera.prototype, "checkCollisions", void 0);
  13016. __decorate([
  13017. BABYLON.serialize()
  13018. ], FreeCamera.prototype, "applyGravity", void 0);
  13019. return FreeCamera;
  13020. })(BABYLON.TargetCamera);
  13021. BABYLON.FreeCamera = FreeCamera;
  13022. })(BABYLON || (BABYLON = {}));
  13023. var BABYLON;
  13024. (function (BABYLON) {
  13025. var FreeCameraInputsManager = (function (_super) {
  13026. __extends(FreeCameraInputsManager, _super);
  13027. function FreeCameraInputsManager(camera) {
  13028. _super.call(this, camera);
  13029. }
  13030. FreeCameraInputsManager.prototype.addKeyboard = function () {
  13031. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  13032. return this;
  13033. };
  13034. FreeCameraInputsManager.prototype.addMouse = function () {
  13035. this.add(new BABYLON.FreeCameraMouseInput());
  13036. return this;
  13037. };
  13038. FreeCameraInputsManager.prototype.addGamepad = function () {
  13039. this.add(new BABYLON.FreeCameraGamepadInput());
  13040. return this;
  13041. };
  13042. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  13043. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  13044. return this;
  13045. };
  13046. FreeCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  13047. this.add(new BABYLON.FreeCameraVRDeviceOrientationInput());
  13048. return this;
  13049. };
  13050. FreeCameraInputsManager.prototype.addTouch = function () {
  13051. this.add(new BABYLON.FreeCameraTouchInput());
  13052. return this;
  13053. };
  13054. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  13055. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  13056. return this;
  13057. };
  13058. return FreeCameraInputsManager;
  13059. })(BABYLON.CameraInputsManager);
  13060. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  13061. })(BABYLON || (BABYLON = {}));
  13062. var BABYLON;
  13063. (function (BABYLON) {
  13064. var FollowCamera = (function (_super) {
  13065. __extends(FollowCamera, _super);
  13066. function FollowCamera(name, position, scene, target) {
  13067. _super.call(this, name, position, scene);
  13068. this.radius = 12;
  13069. this.rotationOffset = 0;
  13070. this.heightOffset = 4;
  13071. this.cameraAcceleration = 0.05;
  13072. this.maxCameraSpeed = 20;
  13073. this.target = target;
  13074. }
  13075. FollowCamera.prototype.getRadians = function (degrees) {
  13076. return degrees * Math.PI / 180;
  13077. };
  13078. FollowCamera.prototype.follow = function (cameraTarget) {
  13079. if (!cameraTarget)
  13080. return;
  13081. var yRotation;
  13082. if (cameraTarget.rotationQuaternion) {
  13083. var rotMatrix = new BABYLON.Matrix();
  13084. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  13085. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  13086. }
  13087. else {
  13088. yRotation = cameraTarget.rotation.y;
  13089. }
  13090. var radians = this.getRadians(this.rotationOffset) + yRotation;
  13091. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  13092. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  13093. var dx = targetX - this.position.x;
  13094. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  13095. var dz = (targetZ) - this.position.z;
  13096. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  13097. var vy = dy * this.cameraAcceleration;
  13098. var vz = dz * this.cameraAcceleration * 2;
  13099. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  13100. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13101. }
  13102. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  13103. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13104. }
  13105. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  13106. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  13107. }
  13108. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  13109. this.setTarget(cameraTarget.position);
  13110. };
  13111. FollowCamera.prototype._checkInputs = function () {
  13112. _super.prototype._checkInputs.call(this);
  13113. this.follow(this.target);
  13114. };
  13115. FollowCamera.prototype.getTypeName = function () {
  13116. return "FollowCamera";
  13117. };
  13118. __decorate([
  13119. BABYLON.serialize()
  13120. ], FollowCamera.prototype, "radius", void 0);
  13121. __decorate([
  13122. BABYLON.serialize()
  13123. ], FollowCamera.prototype, "rotationOffset", void 0);
  13124. __decorate([
  13125. BABYLON.serialize()
  13126. ], FollowCamera.prototype, "heightOffset", void 0);
  13127. __decorate([
  13128. BABYLON.serialize()
  13129. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  13130. __decorate([
  13131. BABYLON.serialize()
  13132. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  13133. __decorate([
  13134. BABYLON.serializeAsMeshReference("lockedTargetId")
  13135. ], FollowCamera.prototype, "target", void 0);
  13136. return FollowCamera;
  13137. })(BABYLON.TargetCamera);
  13138. BABYLON.FollowCamera = FollowCamera;
  13139. var ArcFollowCamera = (function (_super) {
  13140. __extends(ArcFollowCamera, _super);
  13141. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  13142. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13143. this.alpha = alpha;
  13144. this.beta = beta;
  13145. this.radius = radius;
  13146. this.target = target;
  13147. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  13148. this.follow();
  13149. }
  13150. ArcFollowCamera.prototype.follow = function () {
  13151. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  13152. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  13153. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  13154. this.position = this.target.position.add(this._cartesianCoordinates);
  13155. this.setTarget(this.target.position);
  13156. };
  13157. ArcFollowCamera.prototype._checkInputs = function () {
  13158. _super.prototype._checkInputs.call(this);
  13159. this.follow();
  13160. };
  13161. ArcFollowCamera.prototype.getTypeName = function () {
  13162. return "ArcFollowCamera";
  13163. };
  13164. return ArcFollowCamera;
  13165. })(BABYLON.TargetCamera);
  13166. BABYLON.ArcFollowCamera = ArcFollowCamera;
  13167. })(BABYLON || (BABYLON = {}));
  13168. var BABYLON;
  13169. (function (BABYLON) {
  13170. // We're mainly based on the logic defined into the FreeCamera code
  13171. var TouchCamera = (function (_super) {
  13172. __extends(TouchCamera, _super);
  13173. //-- end properties for backward compatibility for inputs
  13174. function TouchCamera(name, position, scene) {
  13175. _super.call(this, name, position, scene);
  13176. this.inputs.addTouch();
  13177. }
  13178. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  13179. //-- Begin properties for backward compatibility for inputs
  13180. get: function () {
  13181. var touch = this.inputs.attached["touch"];
  13182. if (touch)
  13183. return touch.touchAngularSensibility;
  13184. },
  13185. set: function (value) {
  13186. var touch = this.inputs.attached["touch"];
  13187. if (touch)
  13188. touch.touchAngularSensibility = value;
  13189. },
  13190. enumerable: true,
  13191. configurable: true
  13192. });
  13193. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  13194. get: function () {
  13195. var touch = this.inputs.attached["touch"];
  13196. if (touch)
  13197. return touch.touchMoveSensibility;
  13198. },
  13199. set: function (value) {
  13200. var touch = this.inputs.attached["touch"];
  13201. if (touch)
  13202. touch.touchMoveSensibility = value;
  13203. },
  13204. enumerable: true,
  13205. configurable: true
  13206. });
  13207. TouchCamera.prototype.getTypeName = function () {
  13208. return "TouchCamera";
  13209. };
  13210. return TouchCamera;
  13211. })(BABYLON.FreeCamera);
  13212. BABYLON.TouchCamera = TouchCamera;
  13213. })(BABYLON || (BABYLON = {}));
  13214. var BABYLON;
  13215. (function (BABYLON) {
  13216. var ArcRotateCamera = (function (_super) {
  13217. __extends(ArcRotateCamera, _super);
  13218. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  13219. var _this = this;
  13220. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  13221. this.inertialAlphaOffset = 0;
  13222. this.inertialBetaOffset = 0;
  13223. this.inertialRadiusOffset = 0;
  13224. this.lowerAlphaLimit = null;
  13225. this.upperAlphaLimit = null;
  13226. this.lowerBetaLimit = 0.01;
  13227. this.upperBetaLimit = Math.PI;
  13228. this.lowerRadiusLimit = null;
  13229. this.upperRadiusLimit = null;
  13230. this.inertialPanningX = 0;
  13231. this.inertialPanningY = 0;
  13232. //-- end properties for backward compatibility for inputs
  13233. this.zoomOnFactor = 1;
  13234. this.targetScreenOffset = BABYLON.Vector2.Zero();
  13235. this.allowUpsideDown = true;
  13236. this._viewMatrix = new BABYLON.Matrix();
  13237. // Panning
  13238. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  13239. this.checkCollisions = false;
  13240. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  13241. this._collider = new BABYLON.Collider();
  13242. this._previousPosition = BABYLON.Vector3.Zero();
  13243. this._collisionVelocity = BABYLON.Vector3.Zero();
  13244. this._newPosition = BABYLON.Vector3.Zero();
  13245. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13246. if (collidedMesh === void 0) { collidedMesh = null; }
  13247. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  13248. newPosition.multiplyInPlace(_this._collider.radius);
  13249. }
  13250. if (!collidedMesh) {
  13251. _this._previousPosition.copyFrom(_this.position);
  13252. }
  13253. else {
  13254. _this.setPosition(newPosition);
  13255. if (_this.onCollide) {
  13256. _this.onCollide(collidedMesh);
  13257. }
  13258. }
  13259. // Recompute because of constraints
  13260. var cosa = Math.cos(_this.alpha);
  13261. var sina = Math.sin(_this.alpha);
  13262. var cosb = Math.cos(_this.beta);
  13263. var sinb = Math.sin(_this.beta);
  13264. if (sinb === 0) {
  13265. sinb = 0.0001;
  13266. }
  13267. var target = _this._getTargetPosition();
  13268. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  13269. _this.position.copyFrom(_this._newPosition);
  13270. var up = _this.upVector;
  13271. if (_this.allowUpsideDown && _this.beta < 0) {
  13272. up = up.clone();
  13273. up = up.negate();
  13274. }
  13275. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  13276. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  13277. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  13278. _this._collisionTriggered = false;
  13279. };
  13280. if (!target) {
  13281. this.target = BABYLON.Vector3.Zero();
  13282. }
  13283. else {
  13284. this.target = target;
  13285. }
  13286. this.alpha = alpha;
  13287. this.beta = beta;
  13288. this.radius = radius;
  13289. this.getViewMatrix();
  13290. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  13291. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  13292. }
  13293. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  13294. //-- begin properties for backward compatibility for inputs
  13295. get: function () {
  13296. var pointers = this.inputs.attached["pointers"];
  13297. if (pointers)
  13298. return pointers.angularSensibilityX;
  13299. },
  13300. set: function (value) {
  13301. var pointers = this.inputs.attached["pointers"];
  13302. if (pointers) {
  13303. pointers.angularSensibilityX = value;
  13304. }
  13305. },
  13306. enumerable: true,
  13307. configurable: true
  13308. });
  13309. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  13310. get: function () {
  13311. var pointers = this.inputs.attached["pointers"];
  13312. if (pointers)
  13313. return pointers.angularSensibilityY;
  13314. },
  13315. set: function (value) {
  13316. var pointers = this.inputs.attached["pointers"];
  13317. if (pointers) {
  13318. pointers.angularSensibilityY = value;
  13319. }
  13320. },
  13321. enumerable: true,
  13322. configurable: true
  13323. });
  13324. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  13325. get: function () {
  13326. var pointers = this.inputs.attached["pointers"];
  13327. if (pointers)
  13328. return pointers.pinchPrecision;
  13329. },
  13330. set: function (value) {
  13331. var pointers = this.inputs.attached["pointers"];
  13332. if (pointers) {
  13333. pointers.pinchPrecision = value;
  13334. }
  13335. },
  13336. enumerable: true,
  13337. configurable: true
  13338. });
  13339. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  13340. get: function () {
  13341. var pointers = this.inputs.attached["pointers"];
  13342. if (pointers)
  13343. return pointers.panningSensibility;
  13344. },
  13345. set: function (value) {
  13346. var pointers = this.inputs.attached["pointers"];
  13347. if (pointers) {
  13348. pointers.panningSensibility = value;
  13349. }
  13350. },
  13351. enumerable: true,
  13352. configurable: true
  13353. });
  13354. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  13355. get: function () {
  13356. var keyboard = this.inputs.attached["keyboard"];
  13357. if (keyboard)
  13358. return keyboard.keysUp;
  13359. },
  13360. set: function (value) {
  13361. var keyboard = this.inputs.attached["keyboard"];
  13362. if (keyboard)
  13363. keyboard.keysUp = value;
  13364. },
  13365. enumerable: true,
  13366. configurable: true
  13367. });
  13368. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  13369. get: function () {
  13370. var keyboard = this.inputs.attached["keyboard"];
  13371. if (keyboard)
  13372. return keyboard.keysDown;
  13373. },
  13374. set: function (value) {
  13375. var keyboard = this.inputs.attached["keyboard"];
  13376. if (keyboard)
  13377. keyboard.keysDown = value;
  13378. },
  13379. enumerable: true,
  13380. configurable: true
  13381. });
  13382. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  13383. get: function () {
  13384. var keyboard = this.inputs.attached["keyboard"];
  13385. if (keyboard)
  13386. return keyboard.keysLeft;
  13387. },
  13388. set: function (value) {
  13389. var keyboard = this.inputs.attached["keyboard"];
  13390. if (keyboard)
  13391. keyboard.keysLeft = value;
  13392. },
  13393. enumerable: true,
  13394. configurable: true
  13395. });
  13396. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  13397. get: function () {
  13398. var keyboard = this.inputs.attached["keyboard"];
  13399. if (keyboard)
  13400. return keyboard.keysRight;
  13401. },
  13402. set: function (value) {
  13403. var keyboard = this.inputs.attached["keyboard"];
  13404. if (keyboard)
  13405. keyboard.keysRight = value;
  13406. },
  13407. enumerable: true,
  13408. configurable: true
  13409. });
  13410. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  13411. get: function () {
  13412. var mousewheel = this.inputs.attached["mousewheel"];
  13413. if (mousewheel)
  13414. return mousewheel.wheelPrecision;
  13415. },
  13416. set: function (value) {
  13417. var mousewheel = this.inputs.attached["mousewheel"];
  13418. if (mousewheel)
  13419. mousewheel.wheelPrecision = value;
  13420. },
  13421. enumerable: true,
  13422. configurable: true
  13423. });
  13424. // Cache
  13425. ArcRotateCamera.prototype._initCache = function () {
  13426. _super.prototype._initCache.call(this);
  13427. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13428. this._cache.alpha = undefined;
  13429. this._cache.beta = undefined;
  13430. this._cache.radius = undefined;
  13431. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  13432. };
  13433. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  13434. if (!ignoreParentClass) {
  13435. _super.prototype._updateCache.call(this);
  13436. }
  13437. this._cache.target.copyFrom(this._getTargetPosition());
  13438. this._cache.alpha = this.alpha;
  13439. this._cache.beta = this.beta;
  13440. this._cache.radius = this.radius;
  13441. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  13442. };
  13443. ArcRotateCamera.prototype._getTargetPosition = function () {
  13444. if (this.target.getAbsolutePosition) {
  13445. return this.target.getAbsolutePosition();
  13446. }
  13447. return this.target;
  13448. };
  13449. // Synchronized
  13450. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  13451. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  13452. return false;
  13453. return this._cache.target.equals(this.target)
  13454. && this._cache.alpha === this.alpha
  13455. && this._cache.beta === this.beta
  13456. && this._cache.radius === this.radius
  13457. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  13458. };
  13459. // Methods
  13460. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning) {
  13461. var _this = this;
  13462. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  13463. this._useCtrlForPanning = useCtrlForPanning;
  13464. this.inputs.attachElement(element, noPreventDefault);
  13465. this._reset = function () {
  13466. _this.inertialAlphaOffset = 0;
  13467. _this.inertialBetaOffset = 0;
  13468. _this.inertialRadiusOffset = 0;
  13469. };
  13470. };
  13471. ArcRotateCamera.prototype.detachControl = function (element) {
  13472. this.inputs.detachElement(element);
  13473. if (this._reset) {
  13474. this._reset();
  13475. }
  13476. };
  13477. ArcRotateCamera.prototype._checkInputs = function () {
  13478. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  13479. if (this._collisionTriggered) {
  13480. return;
  13481. }
  13482. this.inputs.checkInputs();
  13483. // Inertia
  13484. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  13485. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  13486. this.beta += this.inertialBetaOffset;
  13487. this.radius -= this.inertialRadiusOffset;
  13488. this.inertialAlphaOffset *= this.inertia;
  13489. this.inertialBetaOffset *= this.inertia;
  13490. this.inertialRadiusOffset *= this.inertia;
  13491. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  13492. this.inertialAlphaOffset = 0;
  13493. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  13494. this.inertialBetaOffset = 0;
  13495. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  13496. this.inertialRadiusOffset = 0;
  13497. }
  13498. // Panning inertia
  13499. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  13500. if (!this._localDirection) {
  13501. this._localDirection = BABYLON.Vector3.Zero();
  13502. this._transformedDirection = BABYLON.Vector3.Zero();
  13503. }
  13504. this.inertialPanningX *= this.inertia;
  13505. this.inertialPanningY *= this.inertia;
  13506. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  13507. this.inertialPanningX = 0;
  13508. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  13509. this.inertialPanningY = 0;
  13510. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  13511. this._localDirection.multiplyInPlace(this.panningAxis);
  13512. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  13513. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  13514. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  13515. if (!this.panningAxis.y) {
  13516. this._transformedDirection.y = 0;
  13517. }
  13518. this.target.addInPlace(this._transformedDirection);
  13519. }
  13520. // Limits
  13521. this._checkLimits();
  13522. _super.prototype._checkInputs.call(this);
  13523. };
  13524. ArcRotateCamera.prototype._checkLimits = function () {
  13525. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  13526. if (this.allowUpsideDown && this.beta > Math.PI) {
  13527. this.beta = this.beta - (2 * Math.PI);
  13528. }
  13529. }
  13530. else {
  13531. if (this.beta < this.lowerBetaLimit) {
  13532. this.beta = this.lowerBetaLimit;
  13533. }
  13534. }
  13535. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  13536. if (this.allowUpsideDown && this.beta < -Math.PI) {
  13537. this.beta = this.beta + (2 * Math.PI);
  13538. }
  13539. }
  13540. else {
  13541. if (this.beta > this.upperBetaLimit) {
  13542. this.beta = this.upperBetaLimit;
  13543. }
  13544. }
  13545. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  13546. this.alpha = this.lowerAlphaLimit;
  13547. }
  13548. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  13549. this.alpha = this.upperAlphaLimit;
  13550. }
  13551. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  13552. this.radius = this.lowerRadiusLimit;
  13553. }
  13554. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  13555. this.radius = this.upperRadiusLimit;
  13556. }
  13557. };
  13558. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  13559. var radiusv3 = this.position.subtract(this._getTargetPosition());
  13560. this.radius = radiusv3.length();
  13561. // Alpha
  13562. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  13563. if (radiusv3.z < 0) {
  13564. this.alpha = 2 * Math.PI - this.alpha;
  13565. }
  13566. // Beta
  13567. this.beta = Math.acos(radiusv3.y / this.radius);
  13568. this._checkLimits();
  13569. };
  13570. ArcRotateCamera.prototype.setPosition = function (position) {
  13571. if (this.position.equals(position)) {
  13572. return;
  13573. }
  13574. this.position = position;
  13575. this.rebuildAnglesAndRadius();
  13576. };
  13577. ArcRotateCamera.prototype.setTarget = function (target) {
  13578. if (this._getTargetPosition().equals(target)) {
  13579. return;
  13580. }
  13581. this.target = target;
  13582. this.rebuildAnglesAndRadius();
  13583. };
  13584. ArcRotateCamera.prototype._getViewMatrix = function () {
  13585. // Compute
  13586. var cosa = Math.cos(this.alpha);
  13587. var sina = Math.sin(this.alpha);
  13588. var cosb = Math.cos(this.beta);
  13589. var sinb = Math.sin(this.beta);
  13590. if (sinb === 0) {
  13591. sinb = 0.0001;
  13592. }
  13593. var target = this._getTargetPosition();
  13594. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  13595. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  13596. this._collider.radius = this.collisionRadius;
  13597. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  13598. this._collisionTriggered = true;
  13599. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  13600. }
  13601. else {
  13602. this.position.copyFrom(this._newPosition);
  13603. var up = this.upVector;
  13604. if (this.allowUpsideDown && this.beta < 0) {
  13605. up = up.clone();
  13606. up = up.negate();
  13607. }
  13608. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  13609. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  13610. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  13611. }
  13612. return this._viewMatrix;
  13613. };
  13614. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  13615. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13616. meshes = meshes || this.getScene().meshes;
  13617. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  13618. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  13619. this.radius = distance * this.zoomOnFactor;
  13620. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  13621. };
  13622. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  13623. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  13624. var meshesOrMinMaxVector;
  13625. var distance;
  13626. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  13627. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  13628. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  13629. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  13630. }
  13631. else {
  13632. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  13633. distance = meshesOrMinMaxVectorAndDistance.distance;
  13634. }
  13635. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  13636. if (!doNotUpdateMaxZ) {
  13637. this.maxZ = distance * 2;
  13638. }
  13639. };
  13640. /**
  13641. * @override
  13642. * Override Camera.createRigCamera
  13643. */
  13644. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  13645. switch (this.cameraRigMode) {
  13646. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13647. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13648. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13649. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13650. case BABYLON.Camera.RIG_MODE_VR:
  13651. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  13652. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  13653. rigCam._cameraRigParams = {};
  13654. return rigCam;
  13655. }
  13656. return null;
  13657. };
  13658. /**
  13659. * @override
  13660. * Override Camera._updateRigCameras
  13661. */
  13662. ArcRotateCamera.prototype._updateRigCameras = function () {
  13663. switch (this.cameraRigMode) {
  13664. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13665. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13666. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13667. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13668. case BABYLON.Camera.RIG_MODE_VR:
  13669. var camLeft = this._rigCameras[0];
  13670. var camRight = this._rigCameras[1];
  13671. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  13672. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  13673. camLeft.beta = camRight.beta = this.beta;
  13674. camLeft.radius = camRight.radius = this.radius;
  13675. break;
  13676. }
  13677. _super.prototype._updateRigCameras.call(this);
  13678. };
  13679. ArcRotateCamera.prototype.dispose = function () {
  13680. this.inputs.clear();
  13681. _super.prototype.dispose.call(this);
  13682. };
  13683. ArcRotateCamera.prototype.getTypeName = function () {
  13684. return "ArcRotateCamera";
  13685. };
  13686. __decorate([
  13687. BABYLON.serialize()
  13688. ], ArcRotateCamera.prototype, "alpha", void 0);
  13689. __decorate([
  13690. BABYLON.serialize()
  13691. ], ArcRotateCamera.prototype, "beta", void 0);
  13692. __decorate([
  13693. BABYLON.serialize()
  13694. ], ArcRotateCamera.prototype, "radius", void 0);
  13695. __decorate([
  13696. BABYLON.serializeAsVector3()
  13697. ], ArcRotateCamera.prototype, "target", void 0);
  13698. __decorate([
  13699. BABYLON.serialize()
  13700. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  13701. __decorate([
  13702. BABYLON.serialize()
  13703. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  13704. __decorate([
  13705. BABYLON.serialize()
  13706. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  13707. __decorate([
  13708. BABYLON.serialize()
  13709. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  13710. __decorate([
  13711. BABYLON.serialize()
  13712. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  13713. __decorate([
  13714. BABYLON.serialize()
  13715. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  13716. __decorate([
  13717. BABYLON.serialize()
  13718. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  13719. __decorate([
  13720. BABYLON.serialize()
  13721. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  13722. __decorate([
  13723. BABYLON.serialize()
  13724. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  13725. __decorate([
  13726. BABYLON.serialize()
  13727. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  13728. __decorate([
  13729. BABYLON.serialize()
  13730. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  13731. __decorate([
  13732. BABYLON.serialize()
  13733. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  13734. __decorate([
  13735. BABYLON.serialize()
  13736. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  13737. return ArcRotateCamera;
  13738. })(BABYLON.TargetCamera);
  13739. BABYLON.ArcRotateCamera = ArcRotateCamera;
  13740. })(BABYLON || (BABYLON = {}));
  13741. var BABYLON;
  13742. (function (BABYLON) {
  13743. var ArcRotateCameraInputsManager = (function (_super) {
  13744. __extends(ArcRotateCameraInputsManager, _super);
  13745. function ArcRotateCameraInputsManager(camera) {
  13746. _super.call(this, camera);
  13747. }
  13748. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  13749. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  13750. return this;
  13751. };
  13752. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  13753. this.add(new BABYLON.ArcRotateCameraPointersInput());
  13754. return this;
  13755. };
  13756. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  13757. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  13758. return this;
  13759. };
  13760. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  13761. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  13762. return this;
  13763. };
  13764. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  13765. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  13766. return this;
  13767. };
  13768. return ArcRotateCameraInputsManager;
  13769. })(BABYLON.CameraInputsManager);
  13770. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  13771. })(BABYLON || (BABYLON = {}));
  13772. var BABYLON;
  13773. (function (BABYLON) {
  13774. var RenderingManager = (function () {
  13775. function RenderingManager(scene) {
  13776. this._renderingGroups = new Array();
  13777. this._scene = scene;
  13778. }
  13779. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  13780. if (this._scene._activeParticleSystems.length === 0) {
  13781. return;
  13782. }
  13783. // Particles
  13784. var activeCamera = this._scene.activeCamera;
  13785. var beforeParticlesDate = BABYLON.Tools.Now;
  13786. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  13787. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  13788. if (particleSystem.renderingGroupId !== index) {
  13789. continue;
  13790. }
  13791. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  13792. continue;
  13793. }
  13794. this._clearDepthBuffer();
  13795. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  13796. this._scene._activeParticles += particleSystem.render();
  13797. }
  13798. }
  13799. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13800. };
  13801. RenderingManager.prototype._renderSprites = function (index) {
  13802. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  13803. return;
  13804. }
  13805. // Sprites
  13806. var activeCamera = this._scene.activeCamera;
  13807. var beforeSpritessDate = BABYLON.Tools.Now;
  13808. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  13809. var spriteManager = this._scene.spriteManagers[id];
  13810. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  13811. this._clearDepthBuffer();
  13812. spriteManager.render();
  13813. }
  13814. }
  13815. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  13816. };
  13817. RenderingManager.prototype._clearDepthBuffer = function () {
  13818. if (this._depthBufferAlreadyCleaned) {
  13819. return;
  13820. }
  13821. this._scene.getEngine().clear(0, false, true);
  13822. this._depthBufferAlreadyCleaned = true;
  13823. };
  13824. RenderingManager.prototype._renderSpritesAndParticles = function () {
  13825. if (this._currentRenderSprites) {
  13826. this._renderSprites(this._currentIndex);
  13827. }
  13828. if (this._currentRenderParticles) {
  13829. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  13830. }
  13831. };
  13832. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  13833. this._currentActiveMeshes = activeMeshes;
  13834. this._currentRenderParticles = renderParticles;
  13835. this._currentRenderSprites = renderSprites;
  13836. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13837. this._depthBufferAlreadyCleaned = index == 0;
  13838. var renderingGroup = this._renderingGroups[index];
  13839. var needToStepBack = false;
  13840. this._currentIndex = index;
  13841. if (renderingGroup) {
  13842. this._clearDepthBuffer();
  13843. if (!renderingGroup.onBeforeTransparentRendering) {
  13844. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  13845. }
  13846. if (!renderingGroup.render(customRenderFunction)) {
  13847. this._renderingGroups.splice(index, 1);
  13848. needToStepBack = true;
  13849. this._renderSpritesAndParticles();
  13850. }
  13851. }
  13852. else {
  13853. this._renderSpritesAndParticles();
  13854. }
  13855. if (needToStepBack) {
  13856. index--;
  13857. }
  13858. }
  13859. };
  13860. RenderingManager.prototype.reset = function () {
  13861. this._renderingGroups.forEach(function (renderingGroup, index, array) {
  13862. if (renderingGroup) {
  13863. renderingGroup.prepare();
  13864. }
  13865. });
  13866. };
  13867. RenderingManager.prototype.dispatch = function (subMesh) {
  13868. var mesh = subMesh.getMesh();
  13869. var renderingGroupId = mesh.renderingGroupId || 0;
  13870. if (!this._renderingGroups[renderingGroupId]) {
  13871. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  13872. }
  13873. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  13874. };
  13875. RenderingManager.MAX_RENDERINGGROUPS = 4;
  13876. return RenderingManager;
  13877. })();
  13878. BABYLON.RenderingManager = RenderingManager;
  13879. })(BABYLON || (BABYLON = {}));
  13880. var BABYLON;
  13881. (function (BABYLON) {
  13882. var RenderingGroup = (function () {
  13883. function RenderingGroup(index, scene) {
  13884. this.index = index;
  13885. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  13886. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  13887. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  13888. this._scene = scene;
  13889. }
  13890. RenderingGroup.prototype.render = function (customRenderFunction) {
  13891. if (customRenderFunction) {
  13892. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  13893. return true;
  13894. }
  13895. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  13896. if (this.onBeforeTransparentRendering) {
  13897. this.onBeforeTransparentRendering();
  13898. }
  13899. return false;
  13900. }
  13901. var engine = this._scene.getEngine();
  13902. // Opaque
  13903. var subIndex;
  13904. var submesh;
  13905. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  13906. submesh = this._opaqueSubMeshes.data[subIndex];
  13907. submesh.render(false);
  13908. }
  13909. // Alpha test
  13910. engine.setAlphaTesting(true);
  13911. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  13912. submesh = this._alphaTestSubMeshes.data[subIndex];
  13913. submesh.render(false);
  13914. }
  13915. engine.setAlphaTesting(false);
  13916. if (this.onBeforeTransparentRendering) {
  13917. this.onBeforeTransparentRendering();
  13918. }
  13919. // Transparent
  13920. if (this._transparentSubMeshes.length) {
  13921. // Sorting
  13922. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  13923. submesh = this._transparentSubMeshes.data[subIndex];
  13924. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  13925. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.globalPosition).length();
  13926. }
  13927. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  13928. sortedArray.sort(function (a, b) {
  13929. // Alpha index first
  13930. if (a._alphaIndex > b._alphaIndex) {
  13931. return 1;
  13932. }
  13933. if (a._alphaIndex < b._alphaIndex) {
  13934. return -1;
  13935. }
  13936. // Then distance to camera
  13937. if (a._distanceToCamera < b._distanceToCamera) {
  13938. return 1;
  13939. }
  13940. if (a._distanceToCamera > b._distanceToCamera) {
  13941. return -1;
  13942. }
  13943. return 0;
  13944. });
  13945. // Rendering
  13946. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  13947. submesh = sortedArray[subIndex];
  13948. submesh.render(true);
  13949. }
  13950. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13951. }
  13952. return true;
  13953. };
  13954. RenderingGroup.prototype.prepare = function () {
  13955. this._opaqueSubMeshes.reset();
  13956. this._transparentSubMeshes.reset();
  13957. this._alphaTestSubMeshes.reset();
  13958. };
  13959. RenderingGroup.prototype.dispatch = function (subMesh) {
  13960. var material = subMesh.getMaterial();
  13961. var mesh = subMesh.getMesh();
  13962. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  13963. this._transparentSubMeshes.push(subMesh);
  13964. }
  13965. else if (material.needAlphaTesting()) {
  13966. this._alphaTestSubMeshes.push(subMesh);
  13967. }
  13968. else {
  13969. this._opaqueSubMeshes.push(subMesh); // Opaque
  13970. }
  13971. };
  13972. return RenderingGroup;
  13973. })();
  13974. BABYLON.RenderingGroup = RenderingGroup;
  13975. })(BABYLON || (BABYLON = {}));
  13976. var BABYLON;
  13977. (function (BABYLON) {
  13978. var PointerEventTypes = (function () {
  13979. function PointerEventTypes() {
  13980. }
  13981. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  13982. get: function () {
  13983. return PointerEventTypes._POINTERDOWN;
  13984. },
  13985. enumerable: true,
  13986. configurable: true
  13987. });
  13988. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  13989. get: function () {
  13990. return PointerEventTypes._POINTERUP;
  13991. },
  13992. enumerable: true,
  13993. configurable: true
  13994. });
  13995. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  13996. get: function () {
  13997. return PointerEventTypes._POINTERMOVE;
  13998. },
  13999. enumerable: true,
  14000. configurable: true
  14001. });
  14002. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  14003. get: function () {
  14004. return PointerEventTypes._POINTERWHEEL;
  14005. },
  14006. enumerable: true,
  14007. configurable: true
  14008. });
  14009. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  14010. get: function () {
  14011. return PointerEventTypes._POINTERPICK;
  14012. },
  14013. enumerable: true,
  14014. configurable: true
  14015. });
  14016. PointerEventTypes._POINTERDOWN = 0x01;
  14017. PointerEventTypes._POINTERUP = 0x02;
  14018. PointerEventTypes._POINTERMOVE = 0x04;
  14019. PointerEventTypes._POINTERWHEEL = 0x08;
  14020. PointerEventTypes._POINTERPICK = 0x10;
  14021. return PointerEventTypes;
  14022. })();
  14023. BABYLON.PointerEventTypes = PointerEventTypes;
  14024. /**
  14025. * This type contains all the data related to a pointer event in Babylon.js.
  14026. * 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.
  14027. */
  14028. var PointerInfo = (function () {
  14029. function PointerInfo(type, event, pickInfo) {
  14030. this.type = type;
  14031. this.event = event;
  14032. this.pickInfo = pickInfo;
  14033. }
  14034. return PointerInfo;
  14035. })();
  14036. BABYLON.PointerInfo = PointerInfo;
  14037. /**
  14038. * Represents a scene to be rendered by the engine.
  14039. * @see http://doc.babylonjs.com/page.php?p=21911
  14040. */
  14041. var Scene = (function () {
  14042. /**
  14043. * @constructor
  14044. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  14045. */
  14046. function Scene(engine) {
  14047. // Members
  14048. this.autoClear = true;
  14049. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14050. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14051. this.forceWireframe = false;
  14052. this.forcePointsCloud = false;
  14053. this.forceShowBoundingBoxes = false;
  14054. this.animationsEnabled = true;
  14055. this.constantlyUpdateMeshUnderPointer = false;
  14056. // Events
  14057. /**
  14058. * An event triggered when the scene is disposed.
  14059. * @type {BABYLON.Observable}
  14060. */
  14061. this.onDisposeObservable = new BABYLON.Observable();
  14062. /**
  14063. * An event triggered before rendering the scene
  14064. * @type {BABYLON.Observable}
  14065. */
  14066. this.onBeforeRenderObservable = new BABYLON.Observable();
  14067. /**
  14068. * An event triggered after rendering the scene
  14069. * @type {BABYLON.Observable}
  14070. */
  14071. this.onAfterRenderObservable = new BABYLON.Observable();
  14072. /**
  14073. * An event triggered when the scene is ready
  14074. * @type {BABYLON.Observable}
  14075. */
  14076. this.onReadyObservable = new BABYLON.Observable();
  14077. /**
  14078. * An event triggered before rendering a camera
  14079. * @type {BABYLON.Observable}
  14080. */
  14081. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  14082. /**
  14083. * An event triggered after rendering a camera
  14084. * @type {BABYLON.Observable}
  14085. */
  14086. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  14087. /**
  14088. * An event triggered when a camera is created
  14089. * @type {BABYLON.Observable}
  14090. */
  14091. this.onNewCameraAddedObservable = new BABYLON.Observable();
  14092. /**
  14093. * An event triggered when a camera is removed
  14094. * @type {BABYLON.Observable}
  14095. */
  14096. this.onCameraRemovedObservable = new BABYLON.Observable();
  14097. /**
  14098. * An event triggered when a light is created
  14099. * @type {BABYLON.Observable}
  14100. */
  14101. this.onNewLightAddedObservable = new BABYLON.Observable();
  14102. /**
  14103. * An event triggered when a light is removed
  14104. * @type {BABYLON.Observable}
  14105. */
  14106. this.onLightRemovedObservable = new BABYLON.Observable();
  14107. /**
  14108. * An event triggered when a geometry is created
  14109. * @type {BABYLON.Observable}
  14110. */
  14111. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  14112. /**
  14113. * An event triggered when a geometry is removed
  14114. * @type {BABYLON.Observable}
  14115. */
  14116. this.onGeometryRemovedObservable = new BABYLON.Observable();
  14117. /**
  14118. * An event triggered when a mesh is created
  14119. * @type {BABYLON.Observable}
  14120. */
  14121. this.onNewMeshAddedObservable = new BABYLON.Observable();
  14122. /**
  14123. * An event triggered when a mesh is removed
  14124. * @type {BABYLON.Observable}
  14125. */
  14126. this.onMeshRemovedObservable = new BABYLON.Observable();
  14127. // Animations
  14128. this.animations = [];
  14129. /**
  14130. * Observable event triggered each time an input event is received from the rendering canvas
  14131. */
  14132. this.onPointerObservable = new BABYLON.Observable();
  14133. 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
  14134. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  14135. this._startingPointerTime = 0;
  14136. // Fog
  14137. /**
  14138. * is fog enabled on this scene.
  14139. * @type {boolean}
  14140. */
  14141. this.fogEnabled = true;
  14142. this.fogMode = Scene.FOGMODE_NONE;
  14143. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14144. this.fogDensity = 0.1;
  14145. this.fogStart = 0;
  14146. this.fogEnd = 1000.0;
  14147. // Lights
  14148. /**
  14149. * is shadow enabled on this scene.
  14150. * @type {boolean}
  14151. */
  14152. this.shadowsEnabled = true;
  14153. /**
  14154. * is light enabled on this scene.
  14155. * @type {boolean}
  14156. */
  14157. this.lightsEnabled = true;
  14158. /**
  14159. * All of the lights added to this scene.
  14160. * @see BABYLON.Light
  14161. * @type {BABYLON.Light[]}
  14162. */
  14163. this.lights = new Array();
  14164. // Cameras
  14165. /**
  14166. * All of the cameras added to this scene.
  14167. * @see BABYLON.Camera
  14168. * @type {BABYLON.Camera[]}
  14169. */
  14170. this.cameras = new Array();
  14171. this.activeCameras = new Array();
  14172. // Meshes
  14173. /**
  14174. * All of the (abstract) meshes added to this scene.
  14175. * @see BABYLON.AbstractMesh
  14176. * @type {BABYLON.AbstractMesh[]}
  14177. */
  14178. this.meshes = new Array();
  14179. // Geometries
  14180. this._geometries = new Array();
  14181. this.materials = new Array();
  14182. this.multiMaterials = new Array();
  14183. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  14184. // Textures
  14185. this.texturesEnabled = true;
  14186. this.textures = new Array();
  14187. // Particles
  14188. this.particlesEnabled = true;
  14189. this.particleSystems = new Array();
  14190. // Sprites
  14191. this.spritesEnabled = true;
  14192. this.spriteManagers = new Array();
  14193. // Layers
  14194. this.layers = new Array();
  14195. // Skeletons
  14196. this.skeletonsEnabled = true;
  14197. this.skeletons = new Array();
  14198. // Lens flares
  14199. this.lensFlaresEnabled = true;
  14200. this.lensFlareSystems = new Array();
  14201. // Collisions
  14202. this.collisionsEnabled = true;
  14203. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  14204. // Postprocesses
  14205. this.postProcessesEnabled = true;
  14206. // Customs render targets
  14207. this.renderTargetsEnabled = true;
  14208. this.dumpNextRenderTargets = false;
  14209. this.customRenderTargets = new Array();
  14210. // Imported meshes
  14211. this.importedMeshesFiles = new Array();
  14212. // Probes
  14213. this.probesEnabled = true;
  14214. this.reflectionProbes = new Array();
  14215. this._actionManagers = new Array();
  14216. this._meshesForIntersections = new BABYLON.SmartArray(256);
  14217. // Procedural textures
  14218. this.proceduralTexturesEnabled = true;
  14219. this._proceduralTextures = new Array();
  14220. this.soundTracks = new Array();
  14221. this._audioEnabled = true;
  14222. this._headphone = false;
  14223. this._totalVertices = 0;
  14224. this._activeIndices = 0;
  14225. this._activeParticles = 0;
  14226. this._lastFrameDuration = 0;
  14227. this._evaluateActiveMeshesDuration = 0;
  14228. this._renderTargetsDuration = 0;
  14229. this._particlesDuration = 0;
  14230. this._renderDuration = 0;
  14231. this._spritesDuration = 0;
  14232. this._animationRatio = 0;
  14233. this._renderId = 0;
  14234. this._executeWhenReadyTimeoutId = -1;
  14235. this._intermediateRendering = false;
  14236. this._toBeDisposed = new BABYLON.SmartArray(256);
  14237. this._pendingData = []; //ANY
  14238. this._activeMeshes = new BABYLON.SmartArray(256);
  14239. this._processedMaterials = new BABYLON.SmartArray(256);
  14240. this._renderTargets = new BABYLON.SmartArray(256);
  14241. this._activeParticleSystems = new BABYLON.SmartArray(256);
  14242. this._activeSkeletons = new BABYLON.SmartArray(32);
  14243. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  14244. this._activeBones = 0;
  14245. this._activeAnimatables = new Array();
  14246. this._transformMatrix = BABYLON.Matrix.Zero();
  14247. this._edgesRenderers = new BABYLON.SmartArray(16);
  14248. this._uniqueIdCounter = 0;
  14249. this._engine = engine;
  14250. engine.scenes.push(this);
  14251. this._renderingManager = new BABYLON.RenderingManager(this);
  14252. this.postProcessManager = new BABYLON.PostProcessManager(this);
  14253. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  14254. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  14255. if (BABYLON.OutlineRenderer) {
  14256. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  14257. }
  14258. this.attachControl();
  14259. this._debugLayer = new BABYLON.DebugLayer(this);
  14260. if (BABYLON.SoundTrack) {
  14261. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  14262. }
  14263. //simplification queue
  14264. if (BABYLON.SimplificationQueue) {
  14265. this.simplificationQueue = new BABYLON.SimplificationQueue();
  14266. }
  14267. //collision coordinator initialization. For now legacy per default.
  14268. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  14269. }
  14270. Object.defineProperty(Scene, "FOGMODE_NONE", {
  14271. get: function () {
  14272. return Scene._FOGMODE_NONE;
  14273. },
  14274. enumerable: true,
  14275. configurable: true
  14276. });
  14277. Object.defineProperty(Scene, "FOGMODE_EXP", {
  14278. get: function () {
  14279. return Scene._FOGMODE_EXP;
  14280. },
  14281. enumerable: true,
  14282. configurable: true
  14283. });
  14284. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  14285. get: function () {
  14286. return Scene._FOGMODE_EXP2;
  14287. },
  14288. enumerable: true,
  14289. configurable: true
  14290. });
  14291. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  14292. get: function () {
  14293. return Scene._FOGMODE_LINEAR;
  14294. },
  14295. enumerable: true,
  14296. configurable: true
  14297. });
  14298. Object.defineProperty(Scene.prototype, "onDispose", {
  14299. set: function (callback) {
  14300. if (this._onDisposeObserver) {
  14301. this.onDisposeObservable.remove(this._onDisposeObserver);
  14302. }
  14303. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14304. },
  14305. enumerable: true,
  14306. configurable: true
  14307. });
  14308. Object.defineProperty(Scene.prototype, "beforeRender", {
  14309. set: function (callback) {
  14310. if (this._onBeforeRenderObserver) {
  14311. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  14312. }
  14313. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  14314. },
  14315. enumerable: true,
  14316. configurable: true
  14317. });
  14318. Object.defineProperty(Scene.prototype, "afterRender", {
  14319. set: function (callback) {
  14320. if (this._onAfterRenderObserver) {
  14321. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  14322. }
  14323. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  14324. },
  14325. enumerable: true,
  14326. configurable: true
  14327. });
  14328. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  14329. set: function (callback) {
  14330. if (this._onBeforeCameraRenderObserver) {
  14331. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  14332. }
  14333. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  14334. },
  14335. enumerable: true,
  14336. configurable: true
  14337. });
  14338. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  14339. set: function (callback) {
  14340. if (this._onAfterCameraRenderObserver) {
  14341. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  14342. }
  14343. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  14344. },
  14345. enumerable: true,
  14346. configurable: true
  14347. });
  14348. Object.defineProperty(Scene.prototype, "debugLayer", {
  14349. // Properties
  14350. get: function () {
  14351. return this._debugLayer;
  14352. },
  14353. enumerable: true,
  14354. configurable: true
  14355. });
  14356. Object.defineProperty(Scene.prototype, "workerCollisions", {
  14357. get: function () {
  14358. return this._workerCollisions;
  14359. },
  14360. set: function (enabled) {
  14361. enabled = (enabled && !!Worker);
  14362. this._workerCollisions = enabled;
  14363. if (this.collisionCoordinator) {
  14364. this.collisionCoordinator.destroy();
  14365. }
  14366. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  14367. this.collisionCoordinator.init(this);
  14368. },
  14369. enumerable: true,
  14370. configurable: true
  14371. });
  14372. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  14373. get: function () {
  14374. return this._selectionOctree;
  14375. },
  14376. enumerable: true,
  14377. configurable: true
  14378. });
  14379. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  14380. /**
  14381. * The mesh that is currently under the pointer.
  14382. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  14383. */
  14384. get: function () {
  14385. return this._pointerOverMesh;
  14386. },
  14387. enumerable: true,
  14388. configurable: true
  14389. });
  14390. Object.defineProperty(Scene.prototype, "pointerX", {
  14391. /**
  14392. * Current on-screen X position of the pointer
  14393. * @return {number} X position of the pointer
  14394. */
  14395. get: function () {
  14396. return this._pointerX;
  14397. },
  14398. enumerable: true,
  14399. configurable: true
  14400. });
  14401. Object.defineProperty(Scene.prototype, "pointerY", {
  14402. /**
  14403. * Current on-screen Y position of the pointer
  14404. * @return {number} Y position of the pointer
  14405. */
  14406. get: function () {
  14407. return this._pointerY;
  14408. },
  14409. enumerable: true,
  14410. configurable: true
  14411. });
  14412. Scene.prototype.getCachedMaterial = function () {
  14413. return this._cachedMaterial;
  14414. };
  14415. Scene.prototype.getBoundingBoxRenderer = function () {
  14416. return this._boundingBoxRenderer;
  14417. };
  14418. Scene.prototype.getOutlineRenderer = function () {
  14419. return this._outlineRenderer;
  14420. };
  14421. Scene.prototype.getEngine = function () {
  14422. return this._engine;
  14423. };
  14424. Scene.prototype.getTotalVertices = function () {
  14425. return this._totalVertices;
  14426. };
  14427. Scene.prototype.getActiveIndices = function () {
  14428. return this._activeIndices;
  14429. };
  14430. Scene.prototype.getActiveParticles = function () {
  14431. return this._activeParticles;
  14432. };
  14433. Scene.prototype.getActiveBones = function () {
  14434. return this._activeBones;
  14435. };
  14436. // Stats
  14437. Scene.prototype.getLastFrameDuration = function () {
  14438. return this._lastFrameDuration;
  14439. };
  14440. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  14441. return this._evaluateActiveMeshesDuration;
  14442. };
  14443. Scene.prototype.getActiveMeshes = function () {
  14444. return this._activeMeshes;
  14445. };
  14446. Scene.prototype.getRenderTargetsDuration = function () {
  14447. return this._renderTargetsDuration;
  14448. };
  14449. Scene.prototype.getRenderDuration = function () {
  14450. return this._renderDuration;
  14451. };
  14452. Scene.prototype.getParticlesDuration = function () {
  14453. return this._particlesDuration;
  14454. };
  14455. Scene.prototype.getSpritesDuration = function () {
  14456. return this._spritesDuration;
  14457. };
  14458. Scene.prototype.getAnimationRatio = function () {
  14459. return this._animationRatio;
  14460. };
  14461. Scene.prototype.getRenderId = function () {
  14462. return this._renderId;
  14463. };
  14464. Scene.prototype.incrementRenderId = function () {
  14465. this._renderId++;
  14466. };
  14467. Scene.prototype._updatePointerPosition = function (evt) {
  14468. var canvasRect = this._engine.getRenderingCanvasClientRect();
  14469. this._pointerX = evt.clientX - canvasRect.left;
  14470. this._pointerY = evt.clientY - canvasRect.top;
  14471. this._unTranslatedPointerX = this._pointerX;
  14472. this._unTranslatedPointerY = this._pointerY;
  14473. if (this.cameraToUseForPointers) {
  14474. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  14475. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  14476. }
  14477. };
  14478. // Pointers handling
  14479. /**
  14480. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  14481. * @param attachUp defines if you want to attach events to pointerup
  14482. * @param attachDown defines if you want to attach events to pointerdown
  14483. * @param attachMove defines if you want to attach events to pointermove
  14484. */
  14485. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  14486. var _this = this;
  14487. if (attachUp === void 0) { attachUp = true; }
  14488. if (attachDown === void 0) { attachDown = true; }
  14489. if (attachMove === void 0) { attachMove = true; }
  14490. var spritePredicate = function (sprite) {
  14491. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  14492. };
  14493. this._onPointerMove = function (evt) {
  14494. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14495. return;
  14496. }
  14497. var canvas = _this._engine.getRenderingCanvas();
  14498. _this._updatePointerPosition(evt);
  14499. if (!_this.pointerMovePredicate) {
  14500. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  14501. }
  14502. // Meshes
  14503. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  14504. if (pickResult.hit && pickResult.pickedMesh) {
  14505. _this.setPointerOverSprite(null);
  14506. _this.setPointerOverMesh(pickResult.pickedMesh);
  14507. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  14508. canvas.style.cursor = "pointer";
  14509. }
  14510. else {
  14511. canvas.style.cursor = "";
  14512. }
  14513. }
  14514. else {
  14515. _this.setPointerOverMesh(null);
  14516. // Sprites
  14517. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14518. if (pickResult.hit && pickResult.pickedSprite) {
  14519. canvas.style.cursor = "pointer";
  14520. _this.setPointerOverSprite(pickResult.pickedSprite);
  14521. }
  14522. else {
  14523. _this.setPointerOverSprite(null);
  14524. // Restore pointer
  14525. canvas.style.cursor = "";
  14526. }
  14527. }
  14528. if (_this.onPointerMove) {
  14529. _this.onPointerMove(evt, pickResult);
  14530. }
  14531. if (_this.onPointerObservable.hasObservers()) {
  14532. var type = evt.type === "mousewheel" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  14533. var pi = new PointerInfo(type, evt, pickResult);
  14534. _this.onPointerObservable.notifyObservers(pi, type);
  14535. }
  14536. };
  14537. this._onPointerDown = function (evt) {
  14538. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14539. return;
  14540. }
  14541. _this._updatePointerPosition(evt);
  14542. _this._startingPointerPosition.x = _this._pointerX;
  14543. _this._startingPointerPosition.y = _this._pointerY;
  14544. _this._startingPointerTime = new Date().getTime();
  14545. if (!_this.pointerDownPredicate) {
  14546. _this.pointerDownPredicate = function (mesh) {
  14547. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  14548. };
  14549. }
  14550. // Meshes
  14551. _this._pickedDownMesh = null;
  14552. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  14553. if (pickResult.hit && pickResult.pickedMesh) {
  14554. if (pickResult.pickedMesh.actionManager) {
  14555. _this._pickedDownMesh = pickResult.pickedMesh;
  14556. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  14557. switch (evt.button) {
  14558. case 0:
  14559. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14560. break;
  14561. case 1:
  14562. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14563. break;
  14564. case 2:
  14565. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14566. break;
  14567. }
  14568. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14569. }
  14570. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  14571. var that = _this;
  14572. window.setTimeout(function () {
  14573. 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);
  14574. if (pickResult.hit && pickResult.pickedMesh) {
  14575. if (pickResult.pickedMesh.actionManager) {
  14576. 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)) {
  14577. that._startingPointerTime = 0;
  14578. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14579. }
  14580. }
  14581. }
  14582. }, BABYLON.ActionManager.LongPressDelay);
  14583. }
  14584. }
  14585. }
  14586. if (_this.onPointerDown) {
  14587. _this.onPointerDown(evt, pickResult);
  14588. }
  14589. if (_this.onPointerObservable.hasObservers()) {
  14590. var type = PointerEventTypes.POINTERDOWN;
  14591. var pi = new PointerInfo(type, evt, pickResult);
  14592. _this.onPointerObservable.notifyObservers(pi, type);
  14593. }
  14594. // Sprites
  14595. _this._pickedDownSprite = null;
  14596. if (_this.spriteManagers.length > 0) {
  14597. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14598. if (pickResult.hit && pickResult.pickedSprite) {
  14599. if (pickResult.pickedSprite.actionManager) {
  14600. _this._pickedDownSprite = pickResult.pickedSprite;
  14601. switch (evt.button) {
  14602. case 0:
  14603. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14604. break;
  14605. case 1:
  14606. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14607. break;
  14608. case 2:
  14609. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14610. break;
  14611. }
  14612. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14613. }
  14614. }
  14615. }
  14616. };
  14617. this._onPointerUp = function (evt) {
  14618. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  14619. return;
  14620. }
  14621. _this._updatePointerPosition(evt);
  14622. if (!_this.pointerUpPredicate) {
  14623. _this.pointerUpPredicate = function (mesh) {
  14624. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  14625. };
  14626. }
  14627. // Meshes
  14628. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  14629. if (pickResult.hit && pickResult.pickedMesh) {
  14630. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  14631. if (_this.onPointerPick) {
  14632. _this.onPointerPick(evt, pickResult);
  14633. }
  14634. if (_this.onPointerObservable.hasObservers()) {
  14635. var type = PointerEventTypes.POINTERPICK;
  14636. var pi = new PointerInfo(type, evt, pickResult);
  14637. _this.onPointerObservable.notifyObservers(pi, type);
  14638. }
  14639. }
  14640. if (pickResult.pickedMesh.actionManager) {
  14641. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14642. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  14643. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  14644. }
  14645. }
  14646. }
  14647. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  14648. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  14649. }
  14650. if (_this.onPointerUp) {
  14651. _this.onPointerUp(evt, pickResult);
  14652. }
  14653. if (_this.onPointerObservable.hasObservers()) {
  14654. var type = PointerEventTypes.POINTERUP;
  14655. var pi = new PointerInfo(type, evt, pickResult);
  14656. _this.onPointerObservable.notifyObservers(pi, type);
  14657. }
  14658. _this._startingPointerTime = 0;
  14659. // Sprites
  14660. if (_this.spriteManagers.length > 0) {
  14661. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  14662. if (pickResult.hit && pickResult.pickedSprite) {
  14663. if (pickResult.pickedSprite.actionManager) {
  14664. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14665. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  14666. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  14667. }
  14668. }
  14669. }
  14670. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  14671. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  14672. }
  14673. }
  14674. };
  14675. this._onKeyDown = function (evt) {
  14676. if (_this.actionManager) {
  14677. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14678. }
  14679. };
  14680. this._onKeyUp = function (evt) {
  14681. if (_this.actionManager) {
  14682. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  14683. }
  14684. };
  14685. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14686. if (attachMove) {
  14687. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  14688. // Wheel
  14689. this._engine.getRenderingCanvas().addEventListener('mousewheel', this._onPointerMove, false);
  14690. this._engine.getRenderingCanvas().addEventListener('DOMMouseScroll', this._onPointerMove, false);
  14691. }
  14692. if (attachDown) {
  14693. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  14694. }
  14695. if (attachUp) {
  14696. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  14697. }
  14698. BABYLON.Tools.RegisterTopRootEvents([
  14699. { name: "keydown", handler: this._onKeyDown },
  14700. { name: "keyup", handler: this._onKeyUp }
  14701. ]);
  14702. };
  14703. Scene.prototype.detachControl = function () {
  14704. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14705. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  14706. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  14707. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  14708. // Wheel
  14709. this._engine.getRenderingCanvas().removeEventListener('mousewheel', this._onPointerMove);
  14710. this._engine.getRenderingCanvas().removeEventListener('DOMMouseScroll', this._onPointerMove);
  14711. BABYLON.Tools.UnregisterTopRootEvents([
  14712. { name: "keydown", handler: this._onKeyDown },
  14713. { name: "keyup", handler: this._onKeyUp }
  14714. ]);
  14715. };
  14716. // Ready
  14717. Scene.prototype.isReady = function () {
  14718. if (this._pendingData.length > 0) {
  14719. return false;
  14720. }
  14721. var index;
  14722. for (index = 0; index < this._geometries.length; index++) {
  14723. var geometry = this._geometries[index];
  14724. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14725. return false;
  14726. }
  14727. }
  14728. for (index = 0; index < this.meshes.length; index++) {
  14729. var mesh = this.meshes[index];
  14730. if (!mesh.isReady()) {
  14731. return false;
  14732. }
  14733. var mat = mesh.material;
  14734. if (mat) {
  14735. if (!mat.isReady(mesh)) {
  14736. return false;
  14737. }
  14738. }
  14739. }
  14740. return true;
  14741. };
  14742. Scene.prototype.resetCachedMaterial = function () {
  14743. this._cachedMaterial = null;
  14744. };
  14745. Scene.prototype.registerBeforeRender = function (func) {
  14746. this.onBeforeRenderObservable.add(func);
  14747. };
  14748. Scene.prototype.unregisterBeforeRender = function (func) {
  14749. this.onBeforeRenderObservable.removeCallback(func);
  14750. };
  14751. Scene.prototype.registerAfterRender = function (func) {
  14752. this.onAfterRenderObservable.add(func);
  14753. };
  14754. Scene.prototype.unregisterAfterRender = function (func) {
  14755. this.onAfterRenderObservable.removeCallback(func);
  14756. };
  14757. Scene.prototype._addPendingData = function (data) {
  14758. this._pendingData.push(data);
  14759. };
  14760. Scene.prototype._removePendingData = function (data) {
  14761. var index = this._pendingData.indexOf(data);
  14762. if (index !== -1) {
  14763. this._pendingData.splice(index, 1);
  14764. }
  14765. };
  14766. Scene.prototype.getWaitingItemsCount = function () {
  14767. return this._pendingData.length;
  14768. };
  14769. /**
  14770. * Registers a function to be executed when the scene is ready.
  14771. * @param {Function} func - the function to be executed.
  14772. */
  14773. Scene.prototype.executeWhenReady = function (func) {
  14774. var _this = this;
  14775. this.onReadyObservable.add(func);
  14776. if (this._executeWhenReadyTimeoutId !== -1) {
  14777. return;
  14778. }
  14779. this._executeWhenReadyTimeoutId = setTimeout(function () {
  14780. _this._checkIsReady();
  14781. }, 150);
  14782. };
  14783. Scene.prototype._checkIsReady = function () {
  14784. var _this = this;
  14785. if (this.isReady()) {
  14786. this.onReadyObservable.notifyObservers(this);
  14787. this.onReadyObservable.clear();
  14788. this._executeWhenReadyTimeoutId = -1;
  14789. return;
  14790. }
  14791. this._executeWhenReadyTimeoutId = setTimeout(function () {
  14792. _this._checkIsReady();
  14793. }, 150);
  14794. };
  14795. // Animations
  14796. /**
  14797. * Will start the animation sequence of a given target
  14798. * @param target - the target
  14799. * @param {number} from - from which frame should animation start
  14800. * @param {number} to - till which frame should animation run.
  14801. * @param {boolean} [loop] - should the animation loop
  14802. * @param {number} [speedRatio] - the speed in which to run the animation
  14803. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  14804. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  14805. * @return {BABYLON.Animatable} the animatable object created for this animation
  14806. * @see BABYLON.Animatable
  14807. * @see http://doc.babylonjs.com/page.php?p=22081
  14808. */
  14809. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  14810. if (speedRatio === void 0) { speedRatio = 1.0; }
  14811. this.stopAnimation(target);
  14812. if (!animatable) {
  14813. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  14814. }
  14815. // Local animations
  14816. if (target.animations) {
  14817. animatable.appendAnimations(target, target.animations);
  14818. }
  14819. // Children animations
  14820. if (target.getAnimatables) {
  14821. var animatables = target.getAnimatables();
  14822. for (var index = 0; index < animatables.length; index++) {
  14823. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  14824. }
  14825. }
  14826. animatable.reset();
  14827. return animatable;
  14828. };
  14829. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  14830. if (speedRatio === undefined) {
  14831. speedRatio = 1.0;
  14832. }
  14833. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  14834. return animatable;
  14835. };
  14836. Scene.prototype.getAnimatableByTarget = function (target) {
  14837. for (var index = 0; index < this._activeAnimatables.length; index++) {
  14838. if (this._activeAnimatables[index].target === target) {
  14839. return this._activeAnimatables[index];
  14840. }
  14841. }
  14842. return null;
  14843. };
  14844. Object.defineProperty(Scene.prototype, "Animatables", {
  14845. get: function () {
  14846. return this._activeAnimatables;
  14847. },
  14848. enumerable: true,
  14849. configurable: true
  14850. });
  14851. /**
  14852. * Will stop the animation of the given target
  14853. * @param target - the target
  14854. * @see beginAnimation
  14855. */
  14856. Scene.prototype.stopAnimation = function (target) {
  14857. var animatable = this.getAnimatableByTarget(target);
  14858. if (animatable) {
  14859. animatable.stop();
  14860. }
  14861. };
  14862. Scene.prototype._animate = function () {
  14863. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  14864. return;
  14865. }
  14866. if (!this._animationStartDate) {
  14867. if (this._pendingData.length > 0) {
  14868. return;
  14869. }
  14870. this._animationStartDate = BABYLON.Tools.Now;
  14871. }
  14872. // Getting time
  14873. var now = BABYLON.Tools.Now;
  14874. var delay = now - this._animationStartDate;
  14875. for (var index = 0; index < this._activeAnimatables.length; index++) {
  14876. this._activeAnimatables[index]._animate(delay);
  14877. }
  14878. };
  14879. // Matrix
  14880. Scene.prototype.getViewMatrix = function () {
  14881. return this._viewMatrix;
  14882. };
  14883. Scene.prototype.getProjectionMatrix = function () {
  14884. return this._projectionMatrix;
  14885. };
  14886. Scene.prototype.getTransformMatrix = function () {
  14887. return this._transformMatrix;
  14888. };
  14889. Scene.prototype.setTransformMatrix = function (view, projection) {
  14890. this._viewMatrix = view;
  14891. this._projectionMatrix = projection;
  14892. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14893. };
  14894. // Methods
  14895. Scene.prototype.addMesh = function (newMesh) {
  14896. newMesh.uniqueId = this._uniqueIdCounter++;
  14897. var position = this.meshes.push(newMesh);
  14898. //notify the collision coordinator
  14899. this.collisionCoordinator.onMeshAdded(newMesh);
  14900. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  14901. };
  14902. Scene.prototype.removeMesh = function (toRemove) {
  14903. var index = this.meshes.indexOf(toRemove);
  14904. if (index !== -1) {
  14905. // Remove from the scene if mesh found
  14906. this.meshes.splice(index, 1);
  14907. }
  14908. //notify the collision coordinator
  14909. this.collisionCoordinator.onMeshRemoved(toRemove);
  14910. this.onMeshRemovedObservable.notifyObservers(toRemove);
  14911. return index;
  14912. };
  14913. Scene.prototype.removeSkeleton = function (toRemove) {
  14914. var index = this.skeletons.indexOf(toRemove);
  14915. if (index !== -1) {
  14916. // Remove from the scene if mesh found
  14917. this.skeletons.splice(index, 1);
  14918. }
  14919. return index;
  14920. };
  14921. Scene.prototype.removeLight = function (toRemove) {
  14922. var index = this.lights.indexOf(toRemove);
  14923. if (index !== -1) {
  14924. // Remove from the scene if mesh found
  14925. this.lights.splice(index, 1);
  14926. }
  14927. this.onLightRemovedObservable.notifyObservers(toRemove);
  14928. return index;
  14929. };
  14930. Scene.prototype.removeCamera = function (toRemove) {
  14931. var index = this.cameras.indexOf(toRemove);
  14932. if (index !== -1) {
  14933. // Remove from the scene if mesh found
  14934. this.cameras.splice(index, 1);
  14935. }
  14936. // Remove from activeCameras
  14937. var index2 = this.activeCameras.indexOf(toRemove);
  14938. if (index2 !== -1) {
  14939. // Remove from the scene if mesh found
  14940. this.activeCameras.splice(index2, 1);
  14941. }
  14942. // Reset the activeCamera
  14943. if (this.activeCamera === toRemove) {
  14944. if (this.cameras.length > 0) {
  14945. this.activeCamera = this.cameras[0];
  14946. }
  14947. else {
  14948. this.activeCamera = null;
  14949. }
  14950. }
  14951. this.onCameraRemovedObservable.notifyObservers(toRemove);
  14952. return index;
  14953. };
  14954. Scene.prototype.addLight = function (newLight) {
  14955. newLight.uniqueId = this._uniqueIdCounter++;
  14956. var position = this.lights.push(newLight);
  14957. this.onNewLightAddedObservable.notifyObservers(newLight);
  14958. };
  14959. Scene.prototype.addCamera = function (newCamera) {
  14960. newCamera.uniqueId = this._uniqueIdCounter++;
  14961. var position = this.cameras.push(newCamera);
  14962. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  14963. };
  14964. /**
  14965. * Switch active camera
  14966. * @param {Camera} newCamera - new active camera
  14967. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  14968. */
  14969. Scene.prototype.swithActiveCamera = function (newCamera, attachControl) {
  14970. if (attachControl === void 0) { attachControl = true; }
  14971. var canvas = this._engine.getRenderingCanvas();
  14972. this.activeCamera.detachControl(canvas);
  14973. this.activeCamera = newCamera;
  14974. if (attachControl) {
  14975. newCamera.attachControl(canvas);
  14976. }
  14977. };
  14978. /**
  14979. * sets the active camera of the scene using its ID
  14980. * @param {string} id - the camera's ID
  14981. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  14982. * @see activeCamera
  14983. */
  14984. Scene.prototype.setActiveCameraByID = function (id) {
  14985. var camera = this.getCameraByID(id);
  14986. if (camera) {
  14987. this.activeCamera = camera;
  14988. return camera;
  14989. }
  14990. return null;
  14991. };
  14992. /**
  14993. * sets the active camera of the scene using its name
  14994. * @param {string} name - the camera's name
  14995. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  14996. * @see activeCamera
  14997. */
  14998. Scene.prototype.setActiveCameraByName = function (name) {
  14999. var camera = this.getCameraByName(name);
  15000. if (camera) {
  15001. this.activeCamera = camera;
  15002. return camera;
  15003. }
  15004. return null;
  15005. };
  15006. /**
  15007. * get a material using its id
  15008. * @param {string} the material's ID
  15009. * @return {BABYLON.Material|null} the material or null if none found.
  15010. */
  15011. Scene.prototype.getMaterialByID = function (id) {
  15012. for (var index = 0; index < this.materials.length; index++) {
  15013. if (this.materials[index].id === id) {
  15014. return this.materials[index];
  15015. }
  15016. }
  15017. return null;
  15018. };
  15019. /**
  15020. * get a material using its name
  15021. * @param {string} the material's name
  15022. * @return {BABYLON.Material|null} the material or null if none found.
  15023. */
  15024. Scene.prototype.getMaterialByName = function (name) {
  15025. for (var index = 0; index < this.materials.length; index++) {
  15026. if (this.materials[index].name === name) {
  15027. return this.materials[index];
  15028. }
  15029. }
  15030. return null;
  15031. };
  15032. Scene.prototype.getLensFlareSystemByName = function (name) {
  15033. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15034. if (this.lensFlareSystems[index].name === name) {
  15035. return this.lensFlareSystems[index];
  15036. }
  15037. }
  15038. return null;
  15039. };
  15040. Scene.prototype.getLensFlareSystemByID = function (id) {
  15041. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15042. if (this.lensFlareSystems[index].id === id) {
  15043. return this.lensFlareSystems[index];
  15044. }
  15045. }
  15046. return null;
  15047. };
  15048. Scene.prototype.getCameraByID = function (id) {
  15049. for (var index = 0; index < this.cameras.length; index++) {
  15050. if (this.cameras[index].id === id) {
  15051. return this.cameras[index];
  15052. }
  15053. }
  15054. return null;
  15055. };
  15056. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  15057. for (var index = 0; index < this.cameras.length; index++) {
  15058. if (this.cameras[index].uniqueId === uniqueId) {
  15059. return this.cameras[index];
  15060. }
  15061. }
  15062. return null;
  15063. };
  15064. /**
  15065. * get a camera using its name
  15066. * @param {string} the camera's name
  15067. * @return {BABYLON.Camera|null} the camera or null if none found.
  15068. */
  15069. Scene.prototype.getCameraByName = function (name) {
  15070. for (var index = 0; index < this.cameras.length; index++) {
  15071. if (this.cameras[index].name === name) {
  15072. return this.cameras[index];
  15073. }
  15074. }
  15075. return null;
  15076. };
  15077. /**
  15078. * get a bone using its id
  15079. * @param {string} the bone's id
  15080. * @return {BABYLON.Bone|null} the bone or null if not found
  15081. */
  15082. Scene.prototype.getBoneByID = function (id) {
  15083. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15084. var skeleton = this.skeletons[skeletonIndex];
  15085. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15086. if (skeleton.bones[boneIndex].id === id) {
  15087. return skeleton.bones[boneIndex];
  15088. }
  15089. }
  15090. }
  15091. return null;
  15092. };
  15093. /**
  15094. * get a bone using its id
  15095. * @param {string} the bone's name
  15096. * @return {BABYLON.Bone|null} the bone or null if not found
  15097. */
  15098. Scene.prototype.getBoneByName = function (name) {
  15099. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  15100. var skeleton = this.skeletons[skeletonIndex];
  15101. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  15102. if (skeleton.bones[boneIndex].name === name) {
  15103. return skeleton.bones[boneIndex];
  15104. }
  15105. }
  15106. }
  15107. return null;
  15108. };
  15109. /**
  15110. * get a light node using its name
  15111. * @param {string} the light's name
  15112. * @return {BABYLON.Light|null} the light or null if none found.
  15113. */
  15114. Scene.prototype.getLightByName = function (name) {
  15115. for (var index = 0; index < this.lights.length; index++) {
  15116. if (this.lights[index].name === name) {
  15117. return this.lights[index];
  15118. }
  15119. }
  15120. return null;
  15121. };
  15122. /**
  15123. * get a light node using its ID
  15124. * @param {string} the light's id
  15125. * @return {BABYLON.Light|null} the light or null if none found.
  15126. */
  15127. Scene.prototype.getLightByID = function (id) {
  15128. for (var index = 0; index < this.lights.length; index++) {
  15129. if (this.lights[index].id === id) {
  15130. return this.lights[index];
  15131. }
  15132. }
  15133. return null;
  15134. };
  15135. /**
  15136. * get a light node using its scene-generated unique ID
  15137. * @param {number} the light's unique id
  15138. * @return {BABYLON.Light|null} the light or null if none found.
  15139. */
  15140. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  15141. for (var index = 0; index < this.lights.length; index++) {
  15142. if (this.lights[index].uniqueId === uniqueId) {
  15143. return this.lights[index];
  15144. }
  15145. }
  15146. return null;
  15147. };
  15148. /**
  15149. * get a particle system by id
  15150. * @param id {number} the particle system id
  15151. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  15152. */
  15153. Scene.prototype.getParticleSystemByID = function (id) {
  15154. for (var index = 0; index < this.particleSystems.length; index++) {
  15155. if (this.particleSystems[index].id === id) {
  15156. return this.particleSystems[index];
  15157. }
  15158. }
  15159. return null;
  15160. };
  15161. /**
  15162. * get a geometry using its ID
  15163. * @param {string} the geometry's id
  15164. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  15165. */
  15166. Scene.prototype.getGeometryByID = function (id) {
  15167. for (var index = 0; index < this._geometries.length; index++) {
  15168. if (this._geometries[index].id === id) {
  15169. return this._geometries[index];
  15170. }
  15171. }
  15172. return null;
  15173. };
  15174. /**
  15175. * add a new geometry to this scene.
  15176. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  15177. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  15178. * @return {boolean} was the geometry added or not
  15179. */
  15180. Scene.prototype.pushGeometry = function (geometry, force) {
  15181. if (!force && this.getGeometryByID(geometry.id)) {
  15182. return false;
  15183. }
  15184. this._geometries.push(geometry);
  15185. //notify the collision coordinator
  15186. this.collisionCoordinator.onGeometryAdded(geometry);
  15187. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  15188. return true;
  15189. };
  15190. /**
  15191. * Removes an existing geometry
  15192. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  15193. * @return {boolean} was the geometry removed or not
  15194. */
  15195. Scene.prototype.removeGeometry = function (geometry) {
  15196. var index = this._geometries.indexOf(geometry);
  15197. if (index > -1) {
  15198. this._geometries.splice(index, 1);
  15199. //notify the collision coordinator
  15200. this.collisionCoordinator.onGeometryDeleted(geometry);
  15201. this.onGeometryRemovedObservable.notifyObservers(geometry);
  15202. return true;
  15203. }
  15204. return false;
  15205. };
  15206. Scene.prototype.getGeometries = function () {
  15207. return this._geometries;
  15208. };
  15209. /**
  15210. * Get the first added mesh found of a given ID
  15211. * @param {string} id - the id to search for
  15212. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15213. */
  15214. Scene.prototype.getMeshByID = function (id) {
  15215. for (var index = 0; index < this.meshes.length; index++) {
  15216. if (this.meshes[index].id === id) {
  15217. return this.meshes[index];
  15218. }
  15219. }
  15220. return null;
  15221. };
  15222. /**
  15223. * Get a mesh with its auto-generated unique id
  15224. * @param {number} uniqueId - the unique id to search for
  15225. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15226. */
  15227. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  15228. for (var index = 0; index < this.meshes.length; index++) {
  15229. if (this.meshes[index].uniqueId === uniqueId) {
  15230. return this.meshes[index];
  15231. }
  15232. }
  15233. return null;
  15234. };
  15235. /**
  15236. * Get a the last added mesh found of a given ID
  15237. * @param {string} id - the id to search for
  15238. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  15239. */
  15240. Scene.prototype.getLastMeshByID = function (id) {
  15241. for (var index = this.meshes.length - 1; index >= 0; index--) {
  15242. if (this.meshes[index].id === id) {
  15243. return this.meshes[index];
  15244. }
  15245. }
  15246. return null;
  15247. };
  15248. /**
  15249. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  15250. * @param {string} id - the id to search for
  15251. * @return {BABYLON.Node|null} the node found or null if not found at all.
  15252. */
  15253. Scene.prototype.getLastEntryByID = function (id) {
  15254. var index;
  15255. for (index = this.meshes.length - 1; index >= 0; index--) {
  15256. if (this.meshes[index].id === id) {
  15257. return this.meshes[index];
  15258. }
  15259. }
  15260. for (index = this.cameras.length - 1; index >= 0; index--) {
  15261. if (this.cameras[index].id === id) {
  15262. return this.cameras[index];
  15263. }
  15264. }
  15265. for (index = this.lights.length - 1; index >= 0; index--) {
  15266. if (this.lights[index].id === id) {
  15267. return this.lights[index];
  15268. }
  15269. }
  15270. return null;
  15271. };
  15272. Scene.prototype.getNodeByID = function (id) {
  15273. var mesh = this.getMeshByID(id);
  15274. if (mesh) {
  15275. return mesh;
  15276. }
  15277. var light = this.getLightByID(id);
  15278. if (light) {
  15279. return light;
  15280. }
  15281. var camera = this.getCameraByID(id);
  15282. if (camera) {
  15283. return camera;
  15284. }
  15285. var bone = this.getBoneByID(id);
  15286. return bone;
  15287. };
  15288. Scene.prototype.getNodeByName = function (name) {
  15289. var mesh = this.getMeshByName(name);
  15290. if (mesh) {
  15291. return mesh;
  15292. }
  15293. var light = this.getLightByName(name);
  15294. if (light) {
  15295. return light;
  15296. }
  15297. var camera = this.getCameraByName(name);
  15298. if (camera) {
  15299. return camera;
  15300. }
  15301. var bone = this.getBoneByName(name);
  15302. return bone;
  15303. };
  15304. Scene.prototype.getMeshByName = function (name) {
  15305. for (var index = 0; index < this.meshes.length; index++) {
  15306. if (this.meshes[index].name === name) {
  15307. return this.meshes[index];
  15308. }
  15309. }
  15310. return null;
  15311. };
  15312. Scene.prototype.getSoundByName = function (name) {
  15313. var index;
  15314. if (BABYLON.AudioEngine) {
  15315. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  15316. if (this.mainSoundTrack.soundCollection[index].name === name) {
  15317. return this.mainSoundTrack.soundCollection[index];
  15318. }
  15319. }
  15320. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  15321. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  15322. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  15323. return this.soundTracks[sdIndex].soundCollection[index];
  15324. }
  15325. }
  15326. }
  15327. }
  15328. return null;
  15329. };
  15330. Scene.prototype.getLastSkeletonByID = function (id) {
  15331. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  15332. if (this.skeletons[index].id === id) {
  15333. return this.skeletons[index];
  15334. }
  15335. }
  15336. return null;
  15337. };
  15338. Scene.prototype.getSkeletonById = function (id) {
  15339. for (var index = 0; index < this.skeletons.length; index++) {
  15340. if (this.skeletons[index].id === id) {
  15341. return this.skeletons[index];
  15342. }
  15343. }
  15344. return null;
  15345. };
  15346. Scene.prototype.getSkeletonByName = function (name) {
  15347. for (var index = 0; index < this.skeletons.length; index++) {
  15348. if (this.skeletons[index].name === name) {
  15349. return this.skeletons[index];
  15350. }
  15351. }
  15352. return null;
  15353. };
  15354. Scene.prototype.isActiveMesh = function (mesh) {
  15355. return (this._activeMeshes.indexOf(mesh) !== -1);
  15356. };
  15357. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  15358. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  15359. var material = subMesh.getMaterial();
  15360. if (mesh.showSubMeshesBoundingBox) {
  15361. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  15362. }
  15363. if (material) {
  15364. // Render targets
  15365. if (material.getRenderTargetTextures) {
  15366. if (this._processedMaterials.indexOf(material) === -1) {
  15367. this._processedMaterials.push(material);
  15368. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  15369. }
  15370. }
  15371. // Dispatch
  15372. this._activeIndices += subMesh.indexCount;
  15373. this._renderingManager.dispatch(subMesh);
  15374. }
  15375. }
  15376. };
  15377. Scene.prototype._isInIntermediateRendering = function () {
  15378. return this._intermediateRendering;
  15379. };
  15380. Scene.prototype._evaluateActiveMeshes = function () {
  15381. this.activeCamera._activeMeshes.reset();
  15382. this._activeMeshes.reset();
  15383. this._renderingManager.reset();
  15384. this._processedMaterials.reset();
  15385. this._activeParticleSystems.reset();
  15386. this._activeSkeletons.reset();
  15387. this._softwareSkinnedMeshes.reset();
  15388. this._boundingBoxRenderer.reset();
  15389. this._edgesRenderers.reset();
  15390. if (!this._frustumPlanes) {
  15391. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15392. }
  15393. else {
  15394. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15395. }
  15396. // Meshes
  15397. var meshes;
  15398. var len;
  15399. if (this._selectionOctree) {
  15400. var selection = this._selectionOctree.select(this._frustumPlanes);
  15401. meshes = selection.data;
  15402. len = selection.length;
  15403. }
  15404. else {
  15405. len = this.meshes.length;
  15406. meshes = this.meshes;
  15407. }
  15408. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  15409. var mesh = meshes[meshIndex];
  15410. if (mesh.isBlocked) {
  15411. continue;
  15412. }
  15413. this._totalVertices += mesh.getTotalVertices();
  15414. if (!mesh.isReady() || !mesh.isEnabled()) {
  15415. continue;
  15416. }
  15417. mesh.computeWorldMatrix();
  15418. // Intersections
  15419. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  15420. this._meshesForIntersections.pushNoDuplicate(mesh);
  15421. }
  15422. // Switch to current LOD
  15423. var meshLOD = mesh.getLOD(this.activeCamera);
  15424. if (!meshLOD) {
  15425. continue;
  15426. }
  15427. mesh._preActivate();
  15428. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  15429. this._activeMeshes.push(mesh);
  15430. this.activeCamera._activeMeshes.push(mesh);
  15431. mesh._activate(this._renderId);
  15432. this._activeMesh(meshLOD);
  15433. }
  15434. }
  15435. // Particle systems
  15436. var beforeParticlesDate = BABYLON.Tools.Now;
  15437. if (this.particlesEnabled) {
  15438. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  15439. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  15440. var particleSystem = this.particleSystems[particleIndex];
  15441. if (!particleSystem.isStarted()) {
  15442. continue;
  15443. }
  15444. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  15445. this._activeParticleSystems.push(particleSystem);
  15446. particleSystem.animate();
  15447. }
  15448. }
  15449. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  15450. }
  15451. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  15452. };
  15453. Scene.prototype._activeMesh = function (mesh) {
  15454. if (mesh.skeleton && this.skeletonsEnabled) {
  15455. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  15456. if (!mesh.computeBonesUsingShaders) {
  15457. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  15458. }
  15459. }
  15460. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  15461. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  15462. }
  15463. if (mesh._edgesRenderer) {
  15464. this._edgesRenderers.push(mesh._edgesRenderer);
  15465. }
  15466. if (mesh && mesh.subMeshes) {
  15467. // Submeshes Octrees
  15468. var len;
  15469. var subMeshes;
  15470. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  15471. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  15472. len = intersections.length;
  15473. subMeshes = intersections.data;
  15474. }
  15475. else {
  15476. subMeshes = mesh.subMeshes;
  15477. len = subMeshes.length;
  15478. }
  15479. for (var subIndex = 0; subIndex < len; subIndex++) {
  15480. var subMesh = subMeshes[subIndex];
  15481. this._evaluateSubMesh(subMesh, mesh);
  15482. }
  15483. }
  15484. };
  15485. Scene.prototype.updateTransformMatrix = function (force) {
  15486. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  15487. };
  15488. Scene.prototype._renderForCamera = function (camera) {
  15489. var engine = this._engine;
  15490. this.activeCamera = camera;
  15491. if (!this.activeCamera)
  15492. throw new Error("Active camera not set");
  15493. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  15494. // Viewport
  15495. engine.setViewport(this.activeCamera.viewport);
  15496. // Camera
  15497. this.resetCachedMaterial();
  15498. this._renderId++;
  15499. this.updateTransformMatrix();
  15500. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  15501. // Meshes
  15502. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  15503. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  15504. this._evaluateActiveMeshes();
  15505. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  15506. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  15507. // Skeletons
  15508. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  15509. var skeleton = this._activeSkeletons.data[skeletonIndex];
  15510. skeleton.prepare();
  15511. }
  15512. // Software skinning
  15513. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  15514. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  15515. mesh.applySkeleton(mesh.skeleton);
  15516. }
  15517. // Render targets
  15518. var beforeRenderTargetDate = BABYLON.Tools.Now;
  15519. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  15520. this._intermediateRendering = true;
  15521. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  15522. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  15523. var renderTarget = this._renderTargets.data[renderIndex];
  15524. if (renderTarget._shouldRender()) {
  15525. this._renderId++;
  15526. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  15527. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  15528. }
  15529. }
  15530. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  15531. this._intermediateRendering = false;
  15532. this._renderId++;
  15533. engine.restoreDefaultFramebuffer(); // Restore back buffer
  15534. }
  15535. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  15536. // Prepare Frame
  15537. this.postProcessManager._prepareFrame();
  15538. var beforeRenderDate = BABYLON.Tools.Now;
  15539. // Backgrounds
  15540. var layerIndex;
  15541. var layer;
  15542. if (this.layers.length) {
  15543. engine.setDepthBuffer(false);
  15544. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  15545. layer = this.layers[layerIndex];
  15546. if (layer.isBackground) {
  15547. layer.render();
  15548. }
  15549. }
  15550. engine.setDepthBuffer(true);
  15551. }
  15552. // Render
  15553. BABYLON.Tools.StartPerformanceCounter("Main render");
  15554. this._renderingManager.render(null, null, true, true);
  15555. BABYLON.Tools.EndPerformanceCounter("Main render");
  15556. // Bounding boxes
  15557. this._boundingBoxRenderer.render();
  15558. // Edges
  15559. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15560. this._edgesRenderers.data[edgesRendererIndex].render();
  15561. }
  15562. // Lens flares
  15563. if (this.lensFlaresEnabled) {
  15564. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  15565. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  15566. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  15567. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  15568. lensFlareSystem.render();
  15569. }
  15570. }
  15571. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  15572. }
  15573. // Foregrounds
  15574. if (this.layers.length) {
  15575. engine.setDepthBuffer(false);
  15576. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  15577. layer = this.layers[layerIndex];
  15578. if (!layer.isBackground) {
  15579. layer.render();
  15580. }
  15581. }
  15582. engine.setDepthBuffer(true);
  15583. }
  15584. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  15585. // Finalize frame
  15586. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  15587. // Update camera
  15588. this.activeCamera._updateFromScene();
  15589. // Reset some special arrays
  15590. this._renderTargets.reset();
  15591. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  15592. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  15593. };
  15594. Scene.prototype._processSubCameras = function (camera) {
  15595. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  15596. this._renderForCamera(camera);
  15597. return;
  15598. }
  15599. // rig cameras
  15600. for (var index = 0; index < camera._rigCameras.length; index++) {
  15601. this._renderForCamera(camera._rigCameras[index]);
  15602. }
  15603. this.activeCamera = camera;
  15604. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  15605. // Update camera
  15606. this.activeCamera._updateFromScene();
  15607. };
  15608. Scene.prototype._checkIntersections = function () {
  15609. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  15610. var sourceMesh = this._meshesForIntersections.data[index];
  15611. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  15612. var action = sourceMesh.actionManager.actions[actionIndex];
  15613. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15614. var parameters = action.getTriggerParameter();
  15615. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  15616. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  15617. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  15618. if (areIntersecting && currentIntersectionInProgress === -1) {
  15619. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  15620. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  15621. sourceMesh._intersectionsInProgress.push(otherMesh);
  15622. }
  15623. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15624. sourceMesh._intersectionsInProgress.push(otherMesh);
  15625. }
  15626. }
  15627. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  15628. //They intersected, and now they don't.
  15629. //is this trigger an exit trigger? execute an event.
  15630. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15631. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  15632. }
  15633. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  15634. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  15635. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  15636. }
  15637. }
  15638. }
  15639. }
  15640. }
  15641. };
  15642. Scene.prototype.render = function () {
  15643. var startDate = BABYLON.Tools.Now;
  15644. this._particlesDuration = 0;
  15645. this._spritesDuration = 0;
  15646. this._activeParticles = 0;
  15647. this._renderDuration = 0;
  15648. this._renderTargetsDuration = 0;
  15649. this._evaluateActiveMeshesDuration = 0;
  15650. this._totalVertices = 0;
  15651. this._activeIndices = 0;
  15652. this._activeBones = 0;
  15653. this.getEngine().resetDrawCalls();
  15654. this._meshesForIntersections.reset();
  15655. this.resetCachedMaterial();
  15656. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  15657. // Actions
  15658. if (this.actionManager) {
  15659. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  15660. }
  15661. //Simplification Queue
  15662. if (this.simplificationQueue && !this.simplificationQueue.running) {
  15663. this.simplificationQueue.executeNext();
  15664. }
  15665. // Animations
  15666. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  15667. this._animationRatio = deltaTime * (60.0 / 1000.0);
  15668. this._animate();
  15669. // Physics
  15670. if (this._physicsEngine) {
  15671. BABYLON.Tools.StartPerformanceCounter("Physics");
  15672. this._physicsEngine._step(deltaTime / 1000.0);
  15673. BABYLON.Tools.EndPerformanceCounter("Physics");
  15674. }
  15675. // Before render
  15676. this.onBeforeRenderObservable.notifyObservers(this);
  15677. // Customs render targets
  15678. var beforeRenderTargetDate = BABYLON.Tools.Now;
  15679. var engine = this.getEngine();
  15680. var currentActiveCamera = this.activeCamera;
  15681. if (this.renderTargetsEnabled) {
  15682. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15683. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  15684. var renderTarget = this.customRenderTargets[customIndex];
  15685. if (renderTarget._shouldRender()) {
  15686. this._renderId++;
  15687. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  15688. if (!this.activeCamera)
  15689. throw new Error("Active camera not set");
  15690. // Viewport
  15691. engine.setViewport(this.activeCamera.viewport);
  15692. // Camera
  15693. this.updateTransformMatrix();
  15694. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  15695. }
  15696. }
  15697. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  15698. this._renderId++;
  15699. }
  15700. if (this.customRenderTargets.length > 0) {
  15701. engine.restoreDefaultFramebuffer();
  15702. }
  15703. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  15704. this.activeCamera = currentActiveCamera;
  15705. // Procedural textures
  15706. if (this.proceduralTexturesEnabled) {
  15707. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  15708. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  15709. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  15710. if (proceduralTexture._shouldRender()) {
  15711. proceduralTexture.render();
  15712. }
  15713. }
  15714. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  15715. }
  15716. // Clear
  15717. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  15718. // Shadows
  15719. if (this.shadowsEnabled) {
  15720. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  15721. var light = this.lights[lightIndex];
  15722. var shadowGenerator = light.getShadowGenerator();
  15723. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  15724. this._renderTargets.push(shadowGenerator.getShadowMap());
  15725. }
  15726. }
  15727. }
  15728. // Depth renderer
  15729. if (this._depthRenderer) {
  15730. this._renderTargets.push(this._depthRenderer.getDepthMap());
  15731. }
  15732. // RenderPipeline
  15733. this.postProcessRenderPipelineManager.update();
  15734. // Multi-cameras?
  15735. if (this.activeCameras.length > 0) {
  15736. var currentRenderId = this._renderId;
  15737. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  15738. this._renderId = currentRenderId;
  15739. if (cameraIndex > 0) {
  15740. this._engine.clear(0, false, true);
  15741. }
  15742. this._processSubCameras(this.activeCameras[cameraIndex]);
  15743. }
  15744. }
  15745. else {
  15746. if (!this.activeCamera) {
  15747. throw new Error("No camera defined");
  15748. }
  15749. this._processSubCameras(this.activeCamera);
  15750. }
  15751. // Intersection checks
  15752. this._checkIntersections();
  15753. // Update the audio listener attached to the camera
  15754. if (BABYLON.AudioEngine) {
  15755. this._updateAudioParameters();
  15756. }
  15757. // After render
  15758. if (this.afterRender) {
  15759. this.afterRender();
  15760. }
  15761. this.onAfterRenderObservable.notifyObservers(this);
  15762. // Cleaning
  15763. for (var index = 0; index < this._toBeDisposed.length; index++) {
  15764. this._toBeDisposed.data[index].dispose();
  15765. this._toBeDisposed[index] = null;
  15766. }
  15767. this._toBeDisposed.reset();
  15768. if (this.dumpNextRenderTargets) {
  15769. this.dumpNextRenderTargets = false;
  15770. }
  15771. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  15772. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  15773. };
  15774. Scene.prototype._updateAudioParameters = function () {
  15775. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  15776. return;
  15777. }
  15778. var listeningCamera;
  15779. var audioEngine = BABYLON.Engine.audioEngine;
  15780. if (this.activeCameras.length > 0) {
  15781. listeningCamera = this.activeCameras[0];
  15782. }
  15783. else {
  15784. listeningCamera = this.activeCamera;
  15785. }
  15786. if (listeningCamera && audioEngine.canUseWebAudio) {
  15787. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  15788. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  15789. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  15790. cameraDirection.normalize();
  15791. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  15792. var i;
  15793. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15794. var sound = this.mainSoundTrack.soundCollection[i];
  15795. if (sound.useCustomAttenuation) {
  15796. sound.updateDistanceFromListener();
  15797. }
  15798. }
  15799. for (i = 0; i < this.soundTracks.length; i++) {
  15800. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15801. sound = this.soundTracks[i].soundCollection[j];
  15802. if (sound.useCustomAttenuation) {
  15803. sound.updateDistanceFromListener();
  15804. }
  15805. }
  15806. }
  15807. }
  15808. };
  15809. Object.defineProperty(Scene.prototype, "audioEnabled", {
  15810. // Audio
  15811. get: function () {
  15812. return this._audioEnabled;
  15813. },
  15814. set: function (value) {
  15815. this._audioEnabled = value;
  15816. if (BABYLON.AudioEngine) {
  15817. if (this._audioEnabled) {
  15818. this._enableAudio();
  15819. }
  15820. else {
  15821. this._disableAudio();
  15822. }
  15823. }
  15824. },
  15825. enumerable: true,
  15826. configurable: true
  15827. });
  15828. Scene.prototype._disableAudio = function () {
  15829. var i;
  15830. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15831. this.mainSoundTrack.soundCollection[i].pause();
  15832. }
  15833. for (i = 0; i < this.soundTracks.length; i++) {
  15834. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15835. this.soundTracks[i].soundCollection[j].pause();
  15836. }
  15837. }
  15838. };
  15839. Scene.prototype._enableAudio = function () {
  15840. var i;
  15841. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  15842. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  15843. this.mainSoundTrack.soundCollection[i].play();
  15844. }
  15845. }
  15846. for (i = 0; i < this.soundTracks.length; i++) {
  15847. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  15848. if (this.soundTracks[i].soundCollection[j].isPaused) {
  15849. this.soundTracks[i].soundCollection[j].play();
  15850. }
  15851. }
  15852. }
  15853. };
  15854. Object.defineProperty(Scene.prototype, "headphone", {
  15855. get: function () {
  15856. return this._headphone;
  15857. },
  15858. set: function (value) {
  15859. this._headphone = value;
  15860. if (BABYLON.AudioEngine) {
  15861. if (this._headphone) {
  15862. this._switchAudioModeForHeadphones();
  15863. }
  15864. else {
  15865. this._switchAudioModeForNormalSpeakers();
  15866. }
  15867. }
  15868. },
  15869. enumerable: true,
  15870. configurable: true
  15871. });
  15872. Scene.prototype._switchAudioModeForHeadphones = function () {
  15873. this.mainSoundTrack.switchPanningModelToHRTF();
  15874. for (var i = 0; i < this.soundTracks.length; i++) {
  15875. this.soundTracks[i].switchPanningModelToHRTF();
  15876. }
  15877. };
  15878. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  15879. this.mainSoundTrack.switchPanningModelToEqualPower();
  15880. for (var i = 0; i < this.soundTracks.length; i++) {
  15881. this.soundTracks[i].switchPanningModelToEqualPower();
  15882. }
  15883. };
  15884. Scene.prototype.enableDepthRenderer = function () {
  15885. if (this._depthRenderer) {
  15886. return this._depthRenderer;
  15887. }
  15888. this._depthRenderer = new BABYLON.DepthRenderer(this);
  15889. return this._depthRenderer;
  15890. };
  15891. Scene.prototype.disableDepthRenderer = function () {
  15892. if (!this._depthRenderer) {
  15893. return;
  15894. }
  15895. this._depthRenderer.dispose();
  15896. this._depthRenderer = null;
  15897. };
  15898. Scene.prototype.freezeMaterials = function () {
  15899. for (var i = 0; i < this.materials.length; i++) {
  15900. this.materials[i].freeze();
  15901. }
  15902. };
  15903. Scene.prototype.unfreezeMaterials = function () {
  15904. for (var i = 0; i < this.materials.length; i++) {
  15905. this.materials[i].unfreeze();
  15906. }
  15907. };
  15908. Scene.prototype.dispose = function () {
  15909. this.beforeRender = null;
  15910. this.afterRender = null;
  15911. this.skeletons = [];
  15912. this._boundingBoxRenderer.dispose();
  15913. if (this._depthRenderer) {
  15914. this._depthRenderer.dispose();
  15915. }
  15916. // Debug layer
  15917. this.debugLayer.hide();
  15918. // Events
  15919. if (this.onDispose) {
  15920. this.onDispose();
  15921. }
  15922. this.onBeforeRenderObservable.clear();
  15923. this.onAfterRenderObservable.clear();
  15924. this.detachControl();
  15925. // Release sounds & sounds tracks
  15926. if (BABYLON.AudioEngine) {
  15927. this.disposeSounds();
  15928. }
  15929. // Detach cameras
  15930. var canvas = this._engine.getRenderingCanvas();
  15931. var index;
  15932. for (index = 0; index < this.cameras.length; index++) {
  15933. this.cameras[index].detachControl(canvas);
  15934. }
  15935. // Release lights
  15936. while (this.lights.length) {
  15937. this.lights[0].dispose();
  15938. }
  15939. // Release meshes
  15940. while (this.meshes.length) {
  15941. this.meshes[0].dispose(true);
  15942. }
  15943. // Release cameras
  15944. while (this.cameras.length) {
  15945. this.cameras[0].dispose();
  15946. }
  15947. // Release materials
  15948. while (this.materials.length) {
  15949. this.materials[0].dispose();
  15950. }
  15951. // Release particles
  15952. while (this.particleSystems.length) {
  15953. this.particleSystems[0].dispose();
  15954. }
  15955. // Release sprites
  15956. while (this.spriteManagers.length) {
  15957. this.spriteManagers[0].dispose();
  15958. }
  15959. // Release layers
  15960. while (this.layers.length) {
  15961. this.layers[0].dispose();
  15962. }
  15963. // Release textures
  15964. while (this.textures.length) {
  15965. this.textures[0].dispose();
  15966. }
  15967. // Post-processes
  15968. this.postProcessManager.dispose();
  15969. // Physics
  15970. if (this._physicsEngine) {
  15971. this.disablePhysicsEngine();
  15972. }
  15973. // Remove from engine
  15974. index = this._engine.scenes.indexOf(this);
  15975. if (index > -1) {
  15976. this._engine.scenes.splice(index, 1);
  15977. }
  15978. this._engine.wipeCaches();
  15979. };
  15980. // Release sounds & sounds tracks
  15981. Scene.prototype.disposeSounds = function () {
  15982. this.mainSoundTrack.dispose();
  15983. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  15984. this.soundTracks[scIndex].dispose();
  15985. }
  15986. };
  15987. // Octrees
  15988. Scene.prototype.getWorldExtends = function () {
  15989. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15990. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  15991. for (var index = 0; index < this.meshes.length; index++) {
  15992. var mesh = this.meshes[index];
  15993. mesh.computeWorldMatrix(true);
  15994. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  15995. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  15996. BABYLON.Tools.CheckExtends(minBox, min, max);
  15997. BABYLON.Tools.CheckExtends(maxBox, min, max);
  15998. }
  15999. return {
  16000. min: min,
  16001. max: max
  16002. };
  16003. };
  16004. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  16005. if (maxCapacity === void 0) { maxCapacity = 64; }
  16006. if (maxDepth === void 0) { maxDepth = 2; }
  16007. if (!this._selectionOctree) {
  16008. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  16009. }
  16010. var worldExtends = this.getWorldExtends();
  16011. // Update octree
  16012. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  16013. return this._selectionOctree;
  16014. };
  16015. // Picking
  16016. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  16017. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  16018. var engine = this._engine;
  16019. if (!camera) {
  16020. if (!this.activeCamera)
  16021. throw new Error("Active camera not set");
  16022. camera = this.activeCamera;
  16023. }
  16024. var cameraViewport = camera.viewport;
  16025. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  16026. // Moving coordinates to local viewport world
  16027. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  16028. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  16029. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  16030. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  16031. };
  16032. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  16033. var engine = this._engine;
  16034. if (!camera) {
  16035. if (!this.activeCamera)
  16036. throw new Error("Active camera not set");
  16037. camera = this.activeCamera;
  16038. }
  16039. var cameraViewport = camera.viewport;
  16040. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  16041. var identity = BABYLON.Matrix.Identity();
  16042. // Moving coordinates to local viewport world
  16043. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  16044. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  16045. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  16046. };
  16047. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  16048. var pickingInfo = null;
  16049. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  16050. var mesh = this.meshes[meshIndex];
  16051. if (predicate) {
  16052. if (!predicate(mesh)) {
  16053. continue;
  16054. }
  16055. }
  16056. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  16057. continue;
  16058. }
  16059. var world = mesh.getWorldMatrix();
  16060. var ray = rayFunction(world);
  16061. var result = mesh.intersects(ray, fastCheck);
  16062. if (!result || !result.hit)
  16063. continue;
  16064. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  16065. continue;
  16066. pickingInfo = result;
  16067. if (fastCheck) {
  16068. break;
  16069. }
  16070. }
  16071. return pickingInfo || new BABYLON.PickingInfo();
  16072. };
  16073. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  16074. var pickingInfo = null;
  16075. camera = camera || this.activeCamera;
  16076. if (this.spriteManagers.length > 0) {
  16077. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  16078. var spriteManager = this.spriteManagers[spriteIndex];
  16079. if (!spriteManager.isPickable) {
  16080. continue;
  16081. }
  16082. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  16083. if (!result || !result.hit)
  16084. continue;
  16085. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  16086. continue;
  16087. pickingInfo = result;
  16088. if (fastCheck) {
  16089. break;
  16090. }
  16091. }
  16092. }
  16093. return pickingInfo || new BABYLON.PickingInfo();
  16094. };
  16095. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  16096. var _this = this;
  16097. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  16098. /// <param name="x">X position on screen</param>
  16099. /// <param name="y">Y position on screen</param>
  16100. /// <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>
  16101. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  16102. /// <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>
  16103. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  16104. };
  16105. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  16106. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  16107. /// <param name="x">X position on screen</param>
  16108. /// <param name="y">Y position on screen</param>
  16109. /// <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>
  16110. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  16111. /// <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>
  16112. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  16113. };
  16114. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  16115. var _this = this;
  16116. return this._internalPick(function (world) {
  16117. if (!_this._pickWithRayInverseMatrix) {
  16118. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  16119. }
  16120. world.invertToRef(_this._pickWithRayInverseMatrix);
  16121. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  16122. }, predicate, fastCheck);
  16123. };
  16124. Scene.prototype.setPointerOverMesh = function (mesh) {
  16125. if (this._pointerOverMesh === mesh) {
  16126. return;
  16127. }
  16128. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  16129. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  16130. }
  16131. this._pointerOverMesh = mesh;
  16132. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  16133. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  16134. }
  16135. };
  16136. Scene.prototype.getPointerOverMesh = function () {
  16137. return this._pointerOverMesh;
  16138. };
  16139. Scene.prototype.setPointerOverSprite = function (sprite) {
  16140. if (this._pointerOverSprite === sprite) {
  16141. return;
  16142. }
  16143. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  16144. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  16145. }
  16146. this._pointerOverSprite = sprite;
  16147. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  16148. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  16149. }
  16150. };
  16151. Scene.prototype.getPointerOverSprite = function () {
  16152. return this._pointerOverSprite;
  16153. };
  16154. // Physics
  16155. Scene.prototype.getPhysicsEngine = function () {
  16156. return this._physicsEngine;
  16157. };
  16158. /**
  16159. * Enables physics to the current scene
  16160. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  16161. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  16162. * @return {boolean} was the physics engine initialized
  16163. */
  16164. Scene.prototype.enablePhysics = function (gravity, plugin) {
  16165. if (this._physicsEngine) {
  16166. return true;
  16167. }
  16168. try {
  16169. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  16170. return true;
  16171. }
  16172. catch (e) {
  16173. BABYLON.Tools.Error(e.message);
  16174. return false;
  16175. }
  16176. };
  16177. Scene.prototype.disablePhysicsEngine = function () {
  16178. if (!this._physicsEngine) {
  16179. return;
  16180. }
  16181. this._physicsEngine.dispose();
  16182. this._physicsEngine = undefined;
  16183. };
  16184. Scene.prototype.isPhysicsEnabled = function () {
  16185. return this._physicsEngine !== undefined;
  16186. };
  16187. /**
  16188. *
  16189. * Sets the gravity of the physics engine (and NOT of the scene)
  16190. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  16191. */
  16192. Scene.prototype.setGravity = function (gravity) {
  16193. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  16194. if (!this._physicsEngine) {
  16195. return;
  16196. }
  16197. this._physicsEngine.setGravity(gravity);
  16198. };
  16199. /**
  16200. * Legacy support, using the new API
  16201. * @Deprecated
  16202. */
  16203. Scene.prototype.createCompoundImpostor = function (parts, options) {
  16204. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  16205. if (parts.parts) {
  16206. options = parts;
  16207. parts = parts.parts;
  16208. }
  16209. var mainMesh = parts[0].mesh;
  16210. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  16211. for (var index = 1; index < parts.length; index++) {
  16212. var mesh = parts[index].mesh;
  16213. if (mesh.parent !== mainMesh) {
  16214. mesh.position = mesh.position.subtract(mainMesh.position);
  16215. mesh.parent = mainMesh;
  16216. }
  16217. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  16218. }
  16219. mainMesh.physicsImpostor.forceUpdate();
  16220. };
  16221. Scene.prototype.deleteCompoundImpostor = function (compound) {
  16222. var mesh = compound.parts[0].mesh;
  16223. mesh.physicsImpostor.dispose();
  16224. mesh.physicsImpostor = null;
  16225. };
  16226. // Misc.
  16227. Scene.prototype.createDefaultCameraOrLight = function () {
  16228. // Light
  16229. if (this.lights.length === 0) {
  16230. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  16231. }
  16232. // Camera
  16233. if (!this.activeCamera) {
  16234. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  16235. // Compute position
  16236. var worldExtends = this.getWorldExtends();
  16237. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  16238. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  16239. camera.setTarget(worldCenter);
  16240. this.activeCamera = camera;
  16241. }
  16242. };
  16243. // Tags
  16244. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  16245. if (tagsQuery === undefined) {
  16246. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  16247. return list;
  16248. }
  16249. var listByTags = [];
  16250. forEach = forEach || (function (item) { return; });
  16251. for (var i in list) {
  16252. var item = list[i];
  16253. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  16254. listByTags.push(item);
  16255. forEach(item);
  16256. }
  16257. }
  16258. return listByTags;
  16259. };
  16260. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  16261. return this._getByTags(this.meshes, tagsQuery, forEach);
  16262. };
  16263. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  16264. return this._getByTags(this.cameras, tagsQuery, forEach);
  16265. };
  16266. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  16267. return this._getByTags(this.lights, tagsQuery, forEach);
  16268. };
  16269. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  16270. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  16271. };
  16272. // Statics
  16273. Scene._FOGMODE_NONE = 0;
  16274. Scene._FOGMODE_EXP = 1;
  16275. Scene._FOGMODE_EXP2 = 2;
  16276. Scene._FOGMODE_LINEAR = 3;
  16277. Scene.MinDeltaTime = 1.0;
  16278. Scene.MaxDeltaTime = 1000.0;
  16279. return Scene;
  16280. })();
  16281. BABYLON.Scene = Scene;
  16282. })(BABYLON || (BABYLON = {}));
  16283. var BABYLON;
  16284. (function (BABYLON) {
  16285. var VertexBuffer = (function () {
  16286. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  16287. if (engine instanceof BABYLON.Mesh) {
  16288. this._engine = engine.getScene().getEngine();
  16289. }
  16290. else {
  16291. this._engine = engine;
  16292. }
  16293. this._updatable = updatable;
  16294. this._data = data;
  16295. if (!postponeInternalCreation) {
  16296. this.create();
  16297. }
  16298. this._kind = kind;
  16299. if (stride) {
  16300. this._strideSize = stride;
  16301. return;
  16302. }
  16303. // Deduce stride from kind
  16304. switch (kind) {
  16305. case VertexBuffer.PositionKind:
  16306. this._strideSize = 3;
  16307. break;
  16308. case VertexBuffer.NormalKind:
  16309. this._strideSize = 3;
  16310. break;
  16311. case VertexBuffer.UVKind:
  16312. case VertexBuffer.UV2Kind:
  16313. case VertexBuffer.UV3Kind:
  16314. case VertexBuffer.UV4Kind:
  16315. case VertexBuffer.UV5Kind:
  16316. case VertexBuffer.UV6Kind:
  16317. this._strideSize = 2;
  16318. break;
  16319. case VertexBuffer.ColorKind:
  16320. this._strideSize = 4;
  16321. break;
  16322. case VertexBuffer.MatricesIndicesKind:
  16323. case VertexBuffer.MatricesIndicesExtraKind:
  16324. this._strideSize = 4;
  16325. break;
  16326. case VertexBuffer.MatricesWeightsKind:
  16327. case VertexBuffer.MatricesWeightsExtraKind:
  16328. this._strideSize = 4;
  16329. break;
  16330. }
  16331. }
  16332. // Properties
  16333. VertexBuffer.prototype.isUpdatable = function () {
  16334. return this._updatable;
  16335. };
  16336. VertexBuffer.prototype.getData = function () {
  16337. return this._data;
  16338. };
  16339. VertexBuffer.prototype.getBuffer = function () {
  16340. return this._buffer;
  16341. };
  16342. VertexBuffer.prototype.getStrideSize = function () {
  16343. return this._strideSize;
  16344. };
  16345. // Methods
  16346. VertexBuffer.prototype.create = function (data) {
  16347. if (!data && this._buffer) {
  16348. return; // nothing to do
  16349. }
  16350. data = data || this._data;
  16351. if (!this._buffer) {
  16352. if (this._updatable) {
  16353. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  16354. }
  16355. else {
  16356. this._buffer = this._engine.createVertexBuffer(data);
  16357. }
  16358. }
  16359. if (this._updatable) {
  16360. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  16361. this._data = data;
  16362. }
  16363. };
  16364. VertexBuffer.prototype.update = function (data) {
  16365. this.create(data);
  16366. };
  16367. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  16368. if (!this._buffer) {
  16369. return;
  16370. }
  16371. if (this._updatable) {
  16372. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  16373. this._data = null;
  16374. }
  16375. };
  16376. VertexBuffer.prototype.dispose = function () {
  16377. if (!this._buffer) {
  16378. return;
  16379. }
  16380. if (this._engine._releaseBuffer(this._buffer)) {
  16381. this._buffer = null;
  16382. }
  16383. };
  16384. Object.defineProperty(VertexBuffer, "PositionKind", {
  16385. get: function () {
  16386. return VertexBuffer._PositionKind;
  16387. },
  16388. enumerable: true,
  16389. configurable: true
  16390. });
  16391. Object.defineProperty(VertexBuffer, "NormalKind", {
  16392. get: function () {
  16393. return VertexBuffer._NormalKind;
  16394. },
  16395. enumerable: true,
  16396. configurable: true
  16397. });
  16398. Object.defineProperty(VertexBuffer, "UVKind", {
  16399. get: function () {
  16400. return VertexBuffer._UVKind;
  16401. },
  16402. enumerable: true,
  16403. configurable: true
  16404. });
  16405. Object.defineProperty(VertexBuffer, "UV2Kind", {
  16406. get: function () {
  16407. return VertexBuffer._UV2Kind;
  16408. },
  16409. enumerable: true,
  16410. configurable: true
  16411. });
  16412. Object.defineProperty(VertexBuffer, "UV3Kind", {
  16413. get: function () {
  16414. return VertexBuffer._UV3Kind;
  16415. },
  16416. enumerable: true,
  16417. configurable: true
  16418. });
  16419. Object.defineProperty(VertexBuffer, "UV4Kind", {
  16420. get: function () {
  16421. return VertexBuffer._UV4Kind;
  16422. },
  16423. enumerable: true,
  16424. configurable: true
  16425. });
  16426. Object.defineProperty(VertexBuffer, "UV5Kind", {
  16427. get: function () {
  16428. return VertexBuffer._UV5Kind;
  16429. },
  16430. enumerable: true,
  16431. configurable: true
  16432. });
  16433. Object.defineProperty(VertexBuffer, "UV6Kind", {
  16434. get: function () {
  16435. return VertexBuffer._UV6Kind;
  16436. },
  16437. enumerable: true,
  16438. configurable: true
  16439. });
  16440. Object.defineProperty(VertexBuffer, "ColorKind", {
  16441. get: function () {
  16442. return VertexBuffer._ColorKind;
  16443. },
  16444. enumerable: true,
  16445. configurable: true
  16446. });
  16447. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  16448. get: function () {
  16449. return VertexBuffer._MatricesIndicesKind;
  16450. },
  16451. enumerable: true,
  16452. configurable: true
  16453. });
  16454. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  16455. get: function () {
  16456. return VertexBuffer._MatricesWeightsKind;
  16457. },
  16458. enumerable: true,
  16459. configurable: true
  16460. });
  16461. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  16462. get: function () {
  16463. return VertexBuffer._MatricesIndicesExtraKind;
  16464. },
  16465. enumerable: true,
  16466. configurable: true
  16467. });
  16468. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  16469. get: function () {
  16470. return VertexBuffer._MatricesWeightsExtraKind;
  16471. },
  16472. enumerable: true,
  16473. configurable: true
  16474. });
  16475. // Enums
  16476. VertexBuffer._PositionKind = "position";
  16477. VertexBuffer._NormalKind = "normal";
  16478. VertexBuffer._UVKind = "uv";
  16479. VertexBuffer._UV2Kind = "uv2";
  16480. VertexBuffer._UV3Kind = "uv3";
  16481. VertexBuffer._UV4Kind = "uv4";
  16482. VertexBuffer._UV5Kind = "uv5";
  16483. VertexBuffer._UV6Kind = "uv6";
  16484. VertexBuffer._ColorKind = "color";
  16485. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  16486. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  16487. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  16488. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  16489. return VertexBuffer;
  16490. })();
  16491. BABYLON.VertexBuffer = VertexBuffer;
  16492. })(BABYLON || (BABYLON = {}));
  16493. var BABYLON;
  16494. (function (BABYLON) {
  16495. /**
  16496. * Creates an instance based on a source mesh.
  16497. */
  16498. var InstancedMesh = (function (_super) {
  16499. __extends(InstancedMesh, _super);
  16500. function InstancedMesh(name, source) {
  16501. _super.call(this, name, source.getScene());
  16502. source.instances.push(this);
  16503. this._sourceMesh = source;
  16504. this.position.copyFrom(source.position);
  16505. this.rotation.copyFrom(source.rotation);
  16506. this.scaling.copyFrom(source.scaling);
  16507. if (source.rotationQuaternion) {
  16508. this.rotationQuaternion = source.rotationQuaternion.clone();
  16509. }
  16510. this.infiniteDistance = source.infiniteDistance;
  16511. this.setPivotMatrix(source.getPivotMatrix());
  16512. this.refreshBoundingInfo();
  16513. this._syncSubMeshes();
  16514. }
  16515. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  16516. // Methods
  16517. get: function () {
  16518. return this._sourceMesh.receiveShadows;
  16519. },
  16520. enumerable: true,
  16521. configurable: true
  16522. });
  16523. Object.defineProperty(InstancedMesh.prototype, "material", {
  16524. get: function () {
  16525. return this._sourceMesh.material;
  16526. },
  16527. enumerable: true,
  16528. configurable: true
  16529. });
  16530. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  16531. get: function () {
  16532. return this._sourceMesh.visibility;
  16533. },
  16534. enumerable: true,
  16535. configurable: true
  16536. });
  16537. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  16538. get: function () {
  16539. return this._sourceMesh.skeleton;
  16540. },
  16541. enumerable: true,
  16542. configurable: true
  16543. });
  16544. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  16545. get: function () {
  16546. return this._sourceMesh.renderingGroupId;
  16547. },
  16548. enumerable: true,
  16549. configurable: true
  16550. });
  16551. InstancedMesh.prototype.getTotalVertices = function () {
  16552. return this._sourceMesh.getTotalVertices();
  16553. };
  16554. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  16555. get: function () {
  16556. return this._sourceMesh;
  16557. },
  16558. enumerable: true,
  16559. configurable: true
  16560. });
  16561. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  16562. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  16563. };
  16564. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  16565. return this._sourceMesh.isVerticesDataPresent(kind);
  16566. };
  16567. InstancedMesh.prototype.getIndices = function () {
  16568. return this._sourceMesh.getIndices();
  16569. };
  16570. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  16571. get: function () {
  16572. return this._sourceMesh._positions;
  16573. },
  16574. enumerable: true,
  16575. configurable: true
  16576. });
  16577. InstancedMesh.prototype.refreshBoundingInfo = function () {
  16578. var meshBB = this._sourceMesh.getBoundingInfo();
  16579. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  16580. this._updateBoundingInfo();
  16581. };
  16582. InstancedMesh.prototype._preActivate = function () {
  16583. if (this._currentLOD) {
  16584. this._currentLOD._preActivate();
  16585. }
  16586. };
  16587. InstancedMesh.prototype._activate = function (renderId) {
  16588. if (this._currentLOD) {
  16589. this._currentLOD._registerInstanceForRenderId(this, renderId);
  16590. }
  16591. };
  16592. InstancedMesh.prototype.getLOD = function (camera) {
  16593. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  16594. if (this._currentLOD === this.sourceMesh) {
  16595. return this;
  16596. }
  16597. return this._currentLOD;
  16598. };
  16599. InstancedMesh.prototype._syncSubMeshes = function () {
  16600. this.releaseSubMeshes();
  16601. if (this._sourceMesh.subMeshes) {
  16602. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  16603. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  16604. }
  16605. }
  16606. };
  16607. InstancedMesh.prototype._generatePointsArray = function () {
  16608. return this._sourceMesh._generatePointsArray();
  16609. };
  16610. // Clone
  16611. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16612. var result = this._sourceMesh.createInstance(name);
  16613. // Deep copy
  16614. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  16615. // Bounding info
  16616. this.refreshBoundingInfo();
  16617. // Parent
  16618. if (newParent) {
  16619. result.parent = newParent;
  16620. }
  16621. if (!doNotCloneChildren) {
  16622. // Children
  16623. for (var index = 0; index < this.getScene().meshes.length; index++) {
  16624. var mesh = this.getScene().meshes[index];
  16625. if (mesh.parent === this) {
  16626. mesh.clone(mesh.name, result);
  16627. }
  16628. }
  16629. }
  16630. result.computeWorldMatrix(true);
  16631. return result;
  16632. };
  16633. // Dispoe
  16634. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  16635. // Remove from mesh
  16636. var index = this._sourceMesh.instances.indexOf(this);
  16637. this._sourceMesh.instances.splice(index, 1);
  16638. _super.prototype.dispose.call(this, doNotRecurse);
  16639. };
  16640. return InstancedMesh;
  16641. })(BABYLON.AbstractMesh);
  16642. BABYLON.InstancedMesh = InstancedMesh;
  16643. })(BABYLON || (BABYLON = {}));
  16644. var BABYLON;
  16645. (function (BABYLON) {
  16646. var _InstancesBatch = (function () {
  16647. function _InstancesBatch() {
  16648. this.mustReturn = false;
  16649. this.visibleInstances = new Array();
  16650. this.renderSelf = new Array();
  16651. }
  16652. return _InstancesBatch;
  16653. })();
  16654. BABYLON._InstancesBatch = _InstancesBatch;
  16655. var Mesh = (function (_super) {
  16656. __extends(Mesh, _super);
  16657. /**
  16658. * @constructor
  16659. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  16660. * @param {Scene} scene - The scene to add this mesh to.
  16661. * @param {Node} parent - The parent of this mesh, if it has one
  16662. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  16663. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  16664. * When false, achieved by calling a clone(), also passing False.
  16665. * This will make creation of children, recursive.
  16666. */
  16667. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  16668. if (parent === void 0) { parent = null; }
  16669. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  16670. _super.call(this, name, scene);
  16671. // Events
  16672. /**
  16673. * An event triggered before rendering the mesh
  16674. * @type {BABYLON.Observable}
  16675. */
  16676. this.onBeforeRenderObservable = new BABYLON.Observable();
  16677. /**
  16678. * An event triggered after rendering the mesh
  16679. * @type {BABYLON.Observable}
  16680. */
  16681. this.onAfterRenderObservable = new BABYLON.Observable();
  16682. /**
  16683. * An event triggered before drawing the mesh
  16684. * @type {BABYLON.Observable}
  16685. */
  16686. this.onBeforeDrawObservable = new BABYLON.Observable();
  16687. // Members
  16688. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  16689. this.instances = new Array();
  16690. this._LODLevels = new Array();
  16691. this._visibleInstances = {};
  16692. this._renderIdForInstances = new Array();
  16693. this._batchCache = new _InstancesBatch();
  16694. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  16695. this._sideOrientation = Mesh._DEFAULTSIDE;
  16696. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  16697. if (source) {
  16698. // Geometry
  16699. if (source._geometry) {
  16700. source._geometry.applyToMesh(this);
  16701. }
  16702. // Deep copy
  16703. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  16704. // Pivot
  16705. this.setPivotMatrix(source.getPivotMatrix());
  16706. this.id = name + "." + source.id;
  16707. // Material
  16708. this.material = source.material;
  16709. var index;
  16710. if (!doNotCloneChildren) {
  16711. // Children
  16712. for (index = 0; index < scene.meshes.length; index++) {
  16713. var mesh = scene.meshes[index];
  16714. if (mesh.parent === source) {
  16715. // doNotCloneChildren is always going to be False
  16716. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  16717. }
  16718. }
  16719. }
  16720. // Physics clone
  16721. var physicsEngine = this.getScene().getPhysicsEngine();
  16722. if (clonePhysicsImpostor && physicsEngine) {
  16723. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  16724. if (impostor) {
  16725. this.physicsImpostor = impostor.clone(this);
  16726. }
  16727. }
  16728. // Particles
  16729. for (index = 0; index < scene.particleSystems.length; index++) {
  16730. var system = scene.particleSystems[index];
  16731. if (system.emitter === source) {
  16732. system.clone(system.name, this);
  16733. }
  16734. }
  16735. this.computeWorldMatrix(true);
  16736. }
  16737. // Parent
  16738. if (parent !== null) {
  16739. this.parent = parent;
  16740. }
  16741. }
  16742. Object.defineProperty(Mesh, "FRONTSIDE", {
  16743. /**
  16744. * Mesh side orientation : usually the external or front surface
  16745. */
  16746. get: function () {
  16747. return Mesh._FRONTSIDE;
  16748. },
  16749. enumerable: true,
  16750. configurable: true
  16751. });
  16752. Object.defineProperty(Mesh, "BACKSIDE", {
  16753. /**
  16754. * Mesh side orientation : usually the internal or back surface
  16755. */
  16756. get: function () {
  16757. return Mesh._BACKSIDE;
  16758. },
  16759. enumerable: true,
  16760. configurable: true
  16761. });
  16762. Object.defineProperty(Mesh, "DOUBLESIDE", {
  16763. /**
  16764. * Mesh side orientation : both internal and external or front and back surfaces
  16765. */
  16766. get: function () {
  16767. return Mesh._DOUBLESIDE;
  16768. },
  16769. enumerable: true,
  16770. configurable: true
  16771. });
  16772. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  16773. /**
  16774. * Mesh side orientation : by default, `FRONTSIDE`
  16775. */
  16776. get: function () {
  16777. return Mesh._DEFAULTSIDE;
  16778. },
  16779. enumerable: true,
  16780. configurable: true
  16781. });
  16782. Object.defineProperty(Mesh, "NO_CAP", {
  16783. /**
  16784. * Mesh cap setting : no cap
  16785. */
  16786. get: function () {
  16787. return Mesh._NO_CAP;
  16788. },
  16789. enumerable: true,
  16790. configurable: true
  16791. });
  16792. Object.defineProperty(Mesh, "CAP_START", {
  16793. /**
  16794. * Mesh cap setting : one cap at the beginning of the mesh
  16795. */
  16796. get: function () {
  16797. return Mesh._CAP_START;
  16798. },
  16799. enumerable: true,
  16800. configurable: true
  16801. });
  16802. Object.defineProperty(Mesh, "CAP_END", {
  16803. /**
  16804. * Mesh cap setting : one cap at the end of the mesh
  16805. */
  16806. get: function () {
  16807. return Mesh._CAP_END;
  16808. },
  16809. enumerable: true,
  16810. configurable: true
  16811. });
  16812. Object.defineProperty(Mesh, "CAP_ALL", {
  16813. /**
  16814. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  16815. */
  16816. get: function () {
  16817. return Mesh._CAP_ALL;
  16818. },
  16819. enumerable: true,
  16820. configurable: true
  16821. });
  16822. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  16823. set: function (callback) {
  16824. if (this._onBeforeDrawObserver) {
  16825. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  16826. }
  16827. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  16828. },
  16829. enumerable: true,
  16830. configurable: true
  16831. });
  16832. // Methods
  16833. /**
  16834. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16835. */
  16836. Mesh.prototype.toString = function (fullDetails) {
  16837. var ret = _super.prototype.toString.call(this, fullDetails);
  16838. ret += ", n vertices: " + this.getTotalVertices();
  16839. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  16840. if (this.animations) {
  16841. for (var i = 0; i < this.animations.length; i++) {
  16842. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16843. }
  16844. }
  16845. if (fullDetails) {
  16846. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  16847. }
  16848. return ret;
  16849. };
  16850. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  16851. get: function () {
  16852. return this._LODLevels.length > 0;
  16853. },
  16854. enumerable: true,
  16855. configurable: true
  16856. });
  16857. Mesh.prototype._sortLODLevels = function () {
  16858. this._LODLevels.sort(function (a, b) {
  16859. if (a.distance < b.distance) {
  16860. return 1;
  16861. }
  16862. if (a.distance > b.distance) {
  16863. return -1;
  16864. }
  16865. return 0;
  16866. });
  16867. };
  16868. /**
  16869. * Add a mesh as LOD level triggered at the given distance.
  16870. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  16871. * @param {number} distance - the distance from the center of the object to show this level
  16872. * @param {Mesh} mesh - the mesh to be added as LOD level
  16873. * @return {Mesh} this mesh (for chaining)
  16874. */
  16875. Mesh.prototype.addLODLevel = function (distance, mesh) {
  16876. if (mesh && mesh._masterMesh) {
  16877. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  16878. return this;
  16879. }
  16880. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  16881. this._LODLevels.push(level);
  16882. if (mesh) {
  16883. mesh._masterMesh = this;
  16884. }
  16885. this._sortLODLevels();
  16886. return this;
  16887. };
  16888. /**
  16889. * Returns the LOD level mesh at the passed distance or null if not found.
  16890. * It is related to the method `addLODLevel(distance, mesh)`.
  16891. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  16892. */
  16893. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  16894. for (var index = 0; index < this._LODLevels.length; index++) {
  16895. var level = this._LODLevels[index];
  16896. if (level.distance === distance) {
  16897. return level.mesh;
  16898. }
  16899. }
  16900. return null;
  16901. };
  16902. /**
  16903. * Remove a mesh from the LOD array
  16904. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  16905. * @param {Mesh} mesh - the mesh to be removed.
  16906. * @return {Mesh} this mesh (for chaining)
  16907. */
  16908. Mesh.prototype.removeLODLevel = function (mesh) {
  16909. for (var index = 0; index < this._LODLevels.length; index++) {
  16910. if (this._LODLevels[index].mesh === mesh) {
  16911. this._LODLevels.splice(index, 1);
  16912. if (mesh) {
  16913. mesh._masterMesh = null;
  16914. }
  16915. }
  16916. }
  16917. this._sortLODLevels();
  16918. return this;
  16919. };
  16920. /**
  16921. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  16922. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  16923. */
  16924. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  16925. if (!this._LODLevels || this._LODLevels.length === 0) {
  16926. return this;
  16927. }
  16928. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  16929. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  16930. if (this.onLODLevelSelection) {
  16931. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  16932. }
  16933. return this;
  16934. }
  16935. for (var index = 0; index < this._LODLevels.length; index++) {
  16936. var level = this._LODLevels[index];
  16937. if (level.distance < distanceToCamera) {
  16938. if (level.mesh) {
  16939. level.mesh._preActivate();
  16940. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16941. }
  16942. if (this.onLODLevelSelection) {
  16943. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  16944. }
  16945. return level.mesh;
  16946. }
  16947. }
  16948. if (this.onLODLevelSelection) {
  16949. this.onLODLevelSelection(distanceToCamera, this, this);
  16950. }
  16951. return this;
  16952. };
  16953. Object.defineProperty(Mesh.prototype, "geometry", {
  16954. /**
  16955. * Returns the mesh internal `Geometry` object.
  16956. */
  16957. get: function () {
  16958. return this._geometry;
  16959. },
  16960. enumerable: true,
  16961. configurable: true
  16962. });
  16963. /**
  16964. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  16965. */
  16966. Mesh.prototype.getTotalVertices = function () {
  16967. if (!this._geometry) {
  16968. return 0;
  16969. }
  16970. return this._geometry.getTotalVertices();
  16971. };
  16972. /**
  16973. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  16974. * If `copywhenShared` is true (default false) and if the mesh has submeshes, the submesh data are duplicated in the returned array.
  16975. * Returns null if the mesh has no geometry or no vertex buffer.
  16976. * Possible `kind` values :
  16977. * - BABYLON.VertexBuffer.PositionKind
  16978. * - BABYLON.VertexBuffer.UVKind
  16979. * - BABYLON.VertexBuffer.UV2Kind
  16980. * - BABYLON.VertexBuffer.UV3Kind
  16981. * - BABYLON.VertexBuffer.UV4Kind
  16982. * - BABYLON.VertexBuffer.UV5Kind
  16983. * - BABYLON.VertexBuffer.UV6Kind
  16984. * - BABYLON.VertexBuffer.ColorKind
  16985. * - BABYLON.VertexBuffer.MatricesIndicesKind
  16986. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  16987. * - BABYLON.VertexBuffer.MatricesWeightsKind
  16988. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  16989. */
  16990. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  16991. if (!this._geometry) {
  16992. return null;
  16993. }
  16994. return this._geometry.getVerticesData(kind, copyWhenShared);
  16995. };
  16996. /**
  16997. * Returns the mesh `VertexBuffer` object from the requested `kind` : positions, indices, normals, etc.
  16998. * Returns `undefined` if the mesh has no geometry.
  16999. * Possible `kind` values :
  17000. * - BABYLON.VertexBuffer.PositionKind
  17001. * - BABYLON.VertexBuffer.UVKind
  17002. * - BABYLON.VertexBuffer.UV2Kind
  17003. * - BABYLON.VertexBuffer.UV3Kind
  17004. * - BABYLON.VertexBuffer.UV4Kind
  17005. * - BABYLON.VertexBuffer.UV5Kind
  17006. * - BABYLON.VertexBuffer.UV6Kind
  17007. * - BABYLON.VertexBuffer.ColorKind
  17008. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17009. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17010. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17011. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17012. */
  17013. Mesh.prototype.getVertexBuffer = function (kind) {
  17014. if (!this._geometry) {
  17015. return undefined;
  17016. }
  17017. return this._geometry.getVertexBuffer(kind);
  17018. };
  17019. /**
  17020. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  17021. * Possible `kind` values :
  17022. * - BABYLON.VertexBuffer.PositionKind
  17023. * - BABYLON.VertexBuffer.UVKind
  17024. * - BABYLON.VertexBuffer.UV2Kind
  17025. * - BABYLON.VertexBuffer.UV3Kind
  17026. * - BABYLON.VertexBuffer.UV4Kind
  17027. * - BABYLON.VertexBuffer.UV5Kind
  17028. * - BABYLON.VertexBuffer.UV6Kind
  17029. * - BABYLON.VertexBuffer.ColorKind
  17030. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17031. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17032. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17033. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17034. */
  17035. Mesh.prototype.isVerticesDataPresent = function (kind) {
  17036. if (!this._geometry) {
  17037. if (this._delayInfo) {
  17038. return this._delayInfo.indexOf(kind) !== -1;
  17039. }
  17040. return false;
  17041. }
  17042. return this._geometry.isVerticesDataPresent(kind);
  17043. };
  17044. /**
  17045. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  17046. * Possible `kind` values :
  17047. * - BABYLON.VertexBuffer.PositionKind
  17048. * - BABYLON.VertexBuffer.UVKind
  17049. * - BABYLON.VertexBuffer.UV2Kind
  17050. * - BABYLON.VertexBuffer.UV3Kind
  17051. * - BABYLON.VertexBuffer.UV4Kind
  17052. * - BABYLON.VertexBuffer.UV5Kind
  17053. * - BABYLON.VertexBuffer.UV6Kind
  17054. * - BABYLON.VertexBuffer.ColorKind
  17055. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17056. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17057. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17058. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17059. */
  17060. Mesh.prototype.getVerticesDataKinds = function () {
  17061. if (!this._geometry) {
  17062. var result = [];
  17063. if (this._delayInfo) {
  17064. for (var kind in this._delayInfo) {
  17065. result.push(kind);
  17066. }
  17067. }
  17068. return result;
  17069. }
  17070. return this._geometry.getVerticesDataKinds();
  17071. };
  17072. /**
  17073. * Returns a positive integer : the total number of indices in this mesh geometry.
  17074. * Returns zero if the mesh has no geometry.
  17075. */
  17076. Mesh.prototype.getTotalIndices = function () {
  17077. if (!this._geometry) {
  17078. return 0;
  17079. }
  17080. return this._geometry.getTotalIndices();
  17081. };
  17082. /**
  17083. * Returns an array of integers or a Int32Array populated with the mesh indices.
  17084. * If the parameter `copyWhenShared` is true (default false) and if the mesh has submeshes, the submesh indices are duplicated in the returned array.
  17085. * Returns an empty array if the mesh has no geometry.
  17086. */
  17087. Mesh.prototype.getIndices = function (copyWhenShared) {
  17088. if (!this._geometry) {
  17089. return [];
  17090. }
  17091. return this._geometry.getIndices(copyWhenShared);
  17092. };
  17093. Object.defineProperty(Mesh.prototype, "isBlocked", {
  17094. get: function () {
  17095. return this._masterMesh !== null && this._masterMesh !== undefined;
  17096. },
  17097. enumerable: true,
  17098. configurable: true
  17099. });
  17100. /**
  17101. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  17102. */
  17103. Mesh.prototype.isReady = function () {
  17104. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17105. return false;
  17106. }
  17107. return _super.prototype.isReady.call(this);
  17108. };
  17109. /**
  17110. * Boolean : true if the mesh has been disposed.
  17111. */
  17112. Mesh.prototype.isDisposed = function () {
  17113. return this._isDisposed;
  17114. };
  17115. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  17116. get: function () {
  17117. return this._sideOrientation;
  17118. },
  17119. /**
  17120. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  17121. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  17122. */
  17123. set: function (sideO) {
  17124. this._sideOrientation = sideO;
  17125. },
  17126. enumerable: true,
  17127. configurable: true
  17128. });
  17129. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  17130. /**
  17131. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  17132. * This property is pertinent only for updatable parametric shapes.
  17133. */
  17134. get: function () {
  17135. return this._areNormalsFrozen;
  17136. },
  17137. enumerable: true,
  17138. configurable: true
  17139. });
  17140. /**
  17141. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  17142. * It has no effect at all on other shapes.
  17143. * It prevents the mesh normals from being recomputed on next `positions` array update.
  17144. */
  17145. Mesh.prototype.freezeNormals = function () {
  17146. this._areNormalsFrozen = true;
  17147. };
  17148. /**
  17149. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  17150. * It has no effect at all on other shapes.
  17151. * It reactivates the mesh normals computation if it was previously frozen.
  17152. */
  17153. Mesh.prototype.unfreezeNormals = function () {
  17154. this._areNormalsFrozen = false;
  17155. };
  17156. // Methods
  17157. Mesh.prototype._preActivate = function () {
  17158. var sceneRenderId = this.getScene().getRenderId();
  17159. if (this._preActivateId === sceneRenderId) {
  17160. return;
  17161. }
  17162. this._preActivateId = sceneRenderId;
  17163. this._visibleInstances = null;
  17164. };
  17165. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17166. if (this._visibleInstances) {
  17167. this._visibleInstances.intermediateDefaultRenderId = renderId;
  17168. }
  17169. };
  17170. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  17171. if (!this._visibleInstances) {
  17172. this._visibleInstances = {};
  17173. this._visibleInstances.defaultRenderId = renderId;
  17174. this._visibleInstances.selfDefaultRenderId = this._renderId;
  17175. }
  17176. if (!this._visibleInstances[renderId]) {
  17177. this._visibleInstances[renderId] = new Array();
  17178. }
  17179. this._visibleInstances[renderId].push(instance);
  17180. };
  17181. /**
  17182. * This method recomputes and sets a new `BoundingInfo` to the mesh unless it is locked.
  17183. * This means the mesh underlying bounding box and shpere are recomputed.
  17184. */
  17185. Mesh.prototype.refreshBoundingInfo = function () {
  17186. if (this._boundingInfo.isLocked) {
  17187. return;
  17188. }
  17189. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17190. if (data) {
  17191. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  17192. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  17193. }
  17194. if (this.subMeshes) {
  17195. for (var index = 0; index < this.subMeshes.length; index++) {
  17196. this.subMeshes[index].refreshBoundingInfo();
  17197. }
  17198. }
  17199. this._updateBoundingInfo();
  17200. };
  17201. Mesh.prototype._createGlobalSubMesh = function () {
  17202. var totalVertices = this.getTotalVertices();
  17203. if (!totalVertices || !this.getIndices()) {
  17204. return null;
  17205. }
  17206. this.releaseSubMeshes();
  17207. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  17208. };
  17209. Mesh.prototype.subdivide = function (count) {
  17210. if (count < 1) {
  17211. return;
  17212. }
  17213. var totalIndices = this.getTotalIndices();
  17214. var subdivisionSize = (totalIndices / count) | 0;
  17215. var offset = 0;
  17216. // Ensure that subdivisionSize is a multiple of 3
  17217. while (subdivisionSize % 3 !== 0) {
  17218. subdivisionSize++;
  17219. }
  17220. this.releaseSubMeshes();
  17221. for (var index = 0; index < count; index++) {
  17222. if (offset >= totalIndices) {
  17223. break;
  17224. }
  17225. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  17226. offset += subdivisionSize;
  17227. }
  17228. this.synchronizeInstances();
  17229. };
  17230. /**
  17231. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17232. * If the mesh has no geometry, a new `Geometry` object is set to the mesh and then passed this vertex data.
  17233. * The `data` are either a numeric array either a Float32Array.
  17234. * 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).
  17235. * Note that a new underlying `VertexBuffer` object is created each call.
  17236. * If the `kind` is the `PositionKind`, the mesh `BoundingInfo` is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17237. * The same for the mesh submeshes if any.
  17238. *
  17239. * Possible `kind` values :
  17240. * - BABYLON.VertexBuffer.PositionKind
  17241. * - BABYLON.VertexBuffer.UVKind
  17242. * - BABYLON.VertexBuffer.UV2Kind
  17243. * - BABYLON.VertexBuffer.UV3Kind
  17244. * - BABYLON.VertexBuffer.UV4Kind
  17245. * - BABYLON.VertexBuffer.UV5Kind
  17246. * - BABYLON.VertexBuffer.UV6Kind
  17247. * - BABYLON.VertexBuffer.ColorKind
  17248. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17249. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17250. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17251. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17252. */
  17253. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17254. if (!this._geometry) {
  17255. var vertexData = new BABYLON.VertexData();
  17256. vertexData.set(data, kind);
  17257. var scene = this.getScene();
  17258. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  17259. }
  17260. else {
  17261. this._geometry.setVerticesData(kind, data, updatable, stride);
  17262. }
  17263. };
  17264. /**
  17265. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17266. * If the mesh has no geometry, it is simply returned as it is.
  17267. * The `data` are either a numeric array either a Float32Array.
  17268. * No new underlying `VertexBuffer` object is created.
  17269. * 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.
  17270. * The same for the mesh submeshes if any.
  17271. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17272. *
  17273. * Possible `kind` values :
  17274. * - BABYLON.VertexBuffer.PositionKind
  17275. * - BABYLON.VertexBuffer.UVKind
  17276. * - BABYLON.VertexBuffer.UV2Kind
  17277. * - BABYLON.VertexBuffer.UV3Kind
  17278. * - BABYLON.VertexBuffer.UV4Kind
  17279. * - BABYLON.VertexBuffer.UV5Kind
  17280. * - BABYLON.VertexBuffer.UV6Kind
  17281. * - BABYLON.VertexBuffer.ColorKind
  17282. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17283. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17284. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17285. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17286. */
  17287. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17288. if (!this._geometry) {
  17289. return;
  17290. }
  17291. if (!makeItUnique) {
  17292. this._geometry.updateVerticesData(kind, data, updateExtends);
  17293. }
  17294. else {
  17295. this.makeGeometryUnique();
  17296. this.updateVerticesData(kind, data, updateExtends, false);
  17297. }
  17298. };
  17299. /**
  17300. * Deprecated since BabylonJS v2.3
  17301. */
  17302. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  17303. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  17304. if (!this._geometry) {
  17305. return;
  17306. }
  17307. if (!makeItUnique) {
  17308. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  17309. }
  17310. else {
  17311. this.makeGeometryUnique();
  17312. this.updateVerticesDataDirectly(kind, data, offset, false);
  17313. }
  17314. };
  17315. /**
  17316. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  17317. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  17318. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  17319. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  17320. */
  17321. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  17322. if (computeNormals === void 0) { computeNormals = true; }
  17323. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17324. positionFunction(positions);
  17325. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  17326. if (computeNormals) {
  17327. var indices = this.getIndices();
  17328. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17329. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  17330. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  17331. }
  17332. };
  17333. Mesh.prototype.makeGeometryUnique = function () {
  17334. if (!this._geometry) {
  17335. return;
  17336. }
  17337. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  17338. geometry.applyToMesh(this);
  17339. };
  17340. /**
  17341. * Sets the mesh indices.
  17342. * Expects an array populated with integers or a Int32Array.
  17343. * If the mesh has no geometry, a new `Geometry` object is created and set to the mesh.
  17344. * This method creates a new index buffer each call.
  17345. */
  17346. Mesh.prototype.setIndices = function (indices, totalVertices) {
  17347. if (!this._geometry) {
  17348. var vertexData = new BABYLON.VertexData();
  17349. vertexData.indices = indices;
  17350. var scene = this.getScene();
  17351. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  17352. }
  17353. else {
  17354. this._geometry.setIndices(indices, totalVertices);
  17355. }
  17356. };
  17357. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  17358. var engine = this.getScene().getEngine();
  17359. // Wireframe
  17360. var indexToBind;
  17361. if (this._unIndexed) {
  17362. indexToBind = null;
  17363. }
  17364. else {
  17365. switch (fillMode) {
  17366. case BABYLON.Material.PointFillMode:
  17367. indexToBind = null;
  17368. break;
  17369. case BABYLON.Material.WireFrameFillMode:
  17370. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  17371. break;
  17372. default:
  17373. case BABYLON.Material.TriangleFillMode:
  17374. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  17375. break;
  17376. }
  17377. }
  17378. // VBOs
  17379. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  17380. };
  17381. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  17382. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  17383. return;
  17384. }
  17385. this.onBeforeDrawObservable.notifyObservers(this);
  17386. var engine = this.getScene().getEngine();
  17387. // Draw order
  17388. switch (fillMode) {
  17389. case BABYLON.Material.PointFillMode:
  17390. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17391. break;
  17392. case BABYLON.Material.WireFrameFillMode:
  17393. if (this._unIndexed) {
  17394. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17395. }
  17396. else {
  17397. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  17398. }
  17399. break;
  17400. default:
  17401. if (this._unIndexed) {
  17402. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  17403. }
  17404. else {
  17405. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  17406. }
  17407. }
  17408. };
  17409. /**
  17410. * Registers a javascript function for this mesh that will be called just before the rendering process.
  17411. * This function is passed the current mesh and doesn't return anything.
  17412. */
  17413. Mesh.prototype.registerBeforeRender = function (func) {
  17414. this.onBeforeRenderObservable.add(func);
  17415. };
  17416. /**
  17417. * Disposes a previously registered javascript function called before the rendering.
  17418. * This function is passed the current mesh and doesn't return anything.
  17419. */
  17420. Mesh.prototype.unregisterBeforeRender = function (func) {
  17421. this.onBeforeRenderObservable.removeCallback(func);
  17422. };
  17423. /**
  17424. * Registers a javascript function for this mesh that will be called just after the rendering is complete.
  17425. * This function is passed the current mesh and doesn't return anything.
  17426. */
  17427. Mesh.prototype.registerAfterRender = function (func) {
  17428. this.onAfterRenderObservable.add(func);
  17429. };
  17430. /**
  17431. * Disposes a previously registered javascript function called after the rendering.
  17432. * This function is passed the current mesh and doesn't return anything.
  17433. */
  17434. Mesh.prototype.unregisterAfterRender = function (func) {
  17435. this.onAfterRenderObservable.removeCallback(func);
  17436. };
  17437. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  17438. var scene = this.getScene();
  17439. this._batchCache.mustReturn = false;
  17440. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  17441. this._batchCache.visibleInstances[subMeshId] = null;
  17442. if (this._visibleInstances) {
  17443. var currentRenderId = scene.getRenderId();
  17444. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  17445. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  17446. var selfRenderId = this._renderId;
  17447. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  17448. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  17449. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  17450. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  17451. }
  17452. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  17453. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  17454. this._batchCache.mustReturn = true;
  17455. return this._batchCache;
  17456. }
  17457. if (currentRenderId !== selfRenderId) {
  17458. this._batchCache.renderSelf[subMeshId] = false;
  17459. }
  17460. }
  17461. this._renderIdForInstances[subMeshId] = currentRenderId;
  17462. }
  17463. return this._batchCache;
  17464. };
  17465. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  17466. var visibleInstances = batch.visibleInstances[subMesh._id];
  17467. var matricesCount = visibleInstances.length + 1;
  17468. var bufferSize = matricesCount * 16 * 4;
  17469. while (this._instancesBufferSize < bufferSize) {
  17470. this._instancesBufferSize *= 2;
  17471. }
  17472. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  17473. if (this._worldMatricesInstancesBuffer) {
  17474. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  17475. }
  17476. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  17477. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  17478. }
  17479. var offset = 0;
  17480. var instancesCount = 0;
  17481. var world = this.getWorldMatrix();
  17482. if (batch.renderSelf[subMesh._id]) {
  17483. world.copyToArray(this._worldMatricesInstancesArray, offset);
  17484. offset += 16;
  17485. instancesCount++;
  17486. }
  17487. if (visibleInstances) {
  17488. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  17489. var instance = visibleInstances[instanceIndex];
  17490. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  17491. offset += 16;
  17492. instancesCount++;
  17493. }
  17494. }
  17495. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  17496. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  17497. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  17498. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  17499. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  17500. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  17501. this._draw(subMesh, fillMode, instancesCount);
  17502. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  17503. };
  17504. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  17505. var scene = this.getScene();
  17506. var engine = scene.getEngine();
  17507. if (hardwareInstancedRendering) {
  17508. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  17509. }
  17510. else {
  17511. if (batch.renderSelf[subMesh._id]) {
  17512. // Draw
  17513. if (onBeforeDraw) {
  17514. onBeforeDraw(false, this.getWorldMatrix());
  17515. }
  17516. this._draw(subMesh, fillMode);
  17517. }
  17518. if (batch.visibleInstances[subMesh._id]) {
  17519. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  17520. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  17521. // World
  17522. var world = instance.getWorldMatrix();
  17523. if (onBeforeDraw) {
  17524. onBeforeDraw(true, world);
  17525. }
  17526. // Draw
  17527. this._draw(subMesh, fillMode);
  17528. }
  17529. }
  17530. }
  17531. };
  17532. /**
  17533. * Triggers the draw call for the mesh.
  17534. * You don't need to call this method by your own usually because the mesh rendering is handled by the scene rendering manager.
  17535. */
  17536. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  17537. var scene = this.getScene();
  17538. // Managing instances
  17539. var batch = this._getInstancesRenderList(subMesh._id);
  17540. if (batch.mustReturn) {
  17541. return;
  17542. }
  17543. // Checking geometry state
  17544. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  17545. return;
  17546. }
  17547. var callbackIndex;
  17548. this.onBeforeRenderObservable.notifyObservers(this);
  17549. var engine = scene.getEngine();
  17550. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  17551. // Material
  17552. var effectiveMaterial = subMesh.getMaterial();
  17553. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  17554. return;
  17555. }
  17556. // Outline - step 1
  17557. var savedDepthWrite = engine.getDepthWrite();
  17558. if (this.renderOutline) {
  17559. engine.setDepthWrite(false);
  17560. scene.getOutlineRenderer().render(subMesh, batch);
  17561. engine.setDepthWrite(savedDepthWrite);
  17562. }
  17563. effectiveMaterial._preBind();
  17564. var effect = effectiveMaterial.getEffect();
  17565. // Bind
  17566. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  17567. this._bind(subMesh, effect, fillMode);
  17568. var world = this.getWorldMatrix();
  17569. effectiveMaterial.bind(world, this);
  17570. // Alpha mode
  17571. if (enableAlphaMode) {
  17572. engine.setAlphaMode(effectiveMaterial.alphaMode);
  17573. }
  17574. // Draw
  17575. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  17576. if (isInstance) {
  17577. effectiveMaterial.bindOnlyWorldMatrix(world);
  17578. }
  17579. });
  17580. // Unbind
  17581. effectiveMaterial.unbind();
  17582. // Outline - step 2
  17583. if (this.renderOutline && savedDepthWrite) {
  17584. engine.setDepthWrite(true);
  17585. engine.setColorWrite(false);
  17586. scene.getOutlineRenderer().render(subMesh, batch);
  17587. engine.setColorWrite(true);
  17588. }
  17589. // Overlay
  17590. if (this.renderOverlay) {
  17591. var currentMode = engine.getAlphaMode();
  17592. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  17593. scene.getOutlineRenderer().render(subMesh, batch, true);
  17594. engine.setAlphaMode(currentMode);
  17595. }
  17596. this.onAfterRenderObservable.notifyObservers(this);
  17597. };
  17598. /**
  17599. * Returns an array populated with `ParticleSystem` objects whose the mesh is the emitter.
  17600. */
  17601. Mesh.prototype.getEmittedParticleSystems = function () {
  17602. var results = new Array();
  17603. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  17604. var particleSystem = this.getScene().particleSystems[index];
  17605. if (particleSystem.emitter === this) {
  17606. results.push(particleSystem);
  17607. }
  17608. }
  17609. return results;
  17610. };
  17611. /**
  17612. * Returns an array populated with `ParticleSystem` objects whose the mesh or its children are the emitter.
  17613. */
  17614. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  17615. var results = new Array();
  17616. var descendants = this.getDescendants();
  17617. descendants.push(this);
  17618. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  17619. var particleSystem = this.getScene().particleSystems[index];
  17620. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  17621. results.push(particleSystem);
  17622. }
  17623. }
  17624. return results;
  17625. };
  17626. Mesh.prototype._checkDelayState = function () {
  17627. var _this = this;
  17628. var that = this;
  17629. var scene = this.getScene();
  17630. if (this._geometry) {
  17631. this._geometry.load(scene);
  17632. }
  17633. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17634. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  17635. scene._addPendingData(that);
  17636. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  17637. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  17638. if (data instanceof ArrayBuffer) {
  17639. _this._delayLoadingFunction(data, _this);
  17640. }
  17641. else {
  17642. _this._delayLoadingFunction(JSON.parse(data), _this);
  17643. }
  17644. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  17645. scene._removePendingData(_this);
  17646. }, function () { }, scene.database, getBinaryData);
  17647. }
  17648. };
  17649. /**
  17650. * Boolean, true is the mesh in the frustum defined by the `Plane` objects from the `frustumPlanes` array parameter.
  17651. */
  17652. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  17653. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17654. return false;
  17655. }
  17656. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  17657. return false;
  17658. }
  17659. this._checkDelayState();
  17660. return true;
  17661. };
  17662. Mesh.prototype.setMaterialByID = function (id) {
  17663. var materials = this.getScene().materials;
  17664. var index;
  17665. for (index = 0; index < materials.length; index++) {
  17666. if (materials[index].id === id) {
  17667. this.material = materials[index];
  17668. return;
  17669. }
  17670. }
  17671. // Multi
  17672. var multiMaterials = this.getScene().multiMaterials;
  17673. for (index = 0; index < multiMaterials.length; index++) {
  17674. if (multiMaterials[index].id === id) {
  17675. this.material = multiMaterials[index];
  17676. return;
  17677. }
  17678. }
  17679. };
  17680. Mesh.prototype.getAnimatables = function () {
  17681. var results = [];
  17682. if (this.material) {
  17683. results.push(this.material);
  17684. }
  17685. if (this.skeleton) {
  17686. results.push(this.skeleton);
  17687. }
  17688. return results;
  17689. };
  17690. // Geometry
  17691. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  17692. // Position
  17693. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17694. return;
  17695. }
  17696. this._resetPointsArrayCache();
  17697. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17698. var temp = [];
  17699. var index;
  17700. for (index = 0; index < data.length; index += 3) {
  17701. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  17702. }
  17703. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  17704. // Normals
  17705. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17706. return;
  17707. }
  17708. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17709. temp = [];
  17710. for (index = 0; index < data.length; index += 3) {
  17711. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  17712. }
  17713. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  17714. // flip faces?
  17715. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  17716. this.flipFaces();
  17717. }
  17718. };
  17719. // Will apply current transform to mesh and reset world matrix
  17720. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  17721. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  17722. this.scaling.copyFromFloats(1, 1, 1);
  17723. this.position.copyFromFloats(0, 0, 0);
  17724. this.rotation.copyFromFloats(0, 0, 0);
  17725. //only if quaternion is already set
  17726. if (this.rotationQuaternion) {
  17727. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  17728. }
  17729. this._worldMatrix = BABYLON.Matrix.Identity();
  17730. };
  17731. // Cache
  17732. Mesh.prototype._resetPointsArrayCache = function () {
  17733. this._positions = null;
  17734. };
  17735. Mesh.prototype._generatePointsArray = function () {
  17736. if (this._positions)
  17737. return true;
  17738. this._positions = [];
  17739. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17740. if (!data) {
  17741. return false;
  17742. }
  17743. for (var index = 0; index < data.length; index += 3) {
  17744. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  17745. }
  17746. return true;
  17747. };
  17748. // Clone
  17749. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  17750. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  17751. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  17752. };
  17753. // Dispose
  17754. Mesh.prototype.dispose = function (doNotRecurse) {
  17755. if (this._geometry) {
  17756. this._geometry.releaseForMesh(this, true);
  17757. }
  17758. // Instances
  17759. if (this._worldMatricesInstancesBuffer) {
  17760. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  17761. this._worldMatricesInstancesBuffer = null;
  17762. }
  17763. while (this.instances.length) {
  17764. this.instances[0].dispose();
  17765. }
  17766. _super.prototype.dispose.call(this, doNotRecurse);
  17767. };
  17768. // Geometric tools
  17769. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  17770. var _this = this;
  17771. var scene = this.getScene();
  17772. var onload = function (img) {
  17773. // Getting height map data
  17774. var canvas = document.createElement("canvas");
  17775. var context = canvas.getContext("2d");
  17776. var heightMapWidth = img.width;
  17777. var heightMapHeight = img.height;
  17778. canvas.width = heightMapWidth;
  17779. canvas.height = heightMapHeight;
  17780. context.drawImage(img, 0, 0);
  17781. // Create VertexData from map data
  17782. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  17783. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  17784. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  17785. //execute success callback, if set
  17786. if (onSuccess) {
  17787. onSuccess(_this);
  17788. }
  17789. };
  17790. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  17791. };
  17792. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  17793. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  17794. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  17795. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17796. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  17797. return;
  17798. }
  17799. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17800. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17801. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17802. var position = BABYLON.Vector3.Zero();
  17803. var normal = BABYLON.Vector3.Zero();
  17804. var uv = BABYLON.Vector2.Zero();
  17805. for (var index = 0; index < positions.length; index += 3) {
  17806. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  17807. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  17808. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  17809. // Compute height
  17810. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  17811. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  17812. var pos = (u + v * heightMapWidth) * 4;
  17813. var r = buffer[pos] / 255.0;
  17814. var g = buffer[pos + 1] / 255.0;
  17815. var b = buffer[pos + 2] / 255.0;
  17816. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  17817. normal.normalize();
  17818. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  17819. position = position.add(normal);
  17820. position.toArray(positions, index);
  17821. }
  17822. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  17823. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  17824. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  17825. };
  17826. /**
  17827. * Modify the mesh to get a flat shading rendering.
  17828. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  17829. * Warning : the mesh is really modified.
  17830. */
  17831. Mesh.prototype.convertToFlatShadedMesh = function () {
  17832. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  17833. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  17834. var kinds = this.getVerticesDataKinds();
  17835. var vbs = [];
  17836. var data = [];
  17837. var newdata = [];
  17838. var updatableNormals = false;
  17839. var kindIndex;
  17840. var kind;
  17841. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17842. kind = kinds[kindIndex];
  17843. var vertexBuffer = this.getVertexBuffer(kind);
  17844. if (kind === BABYLON.VertexBuffer.NormalKind) {
  17845. updatableNormals = vertexBuffer.isUpdatable();
  17846. kinds.splice(kindIndex, 1);
  17847. kindIndex--;
  17848. continue;
  17849. }
  17850. vbs[kind] = vertexBuffer;
  17851. data[kind] = vbs[kind].getData();
  17852. newdata[kind] = [];
  17853. }
  17854. // Save previous submeshes
  17855. var previousSubmeshes = this.subMeshes.slice(0);
  17856. var indices = this.getIndices();
  17857. var totalIndices = this.getTotalIndices();
  17858. // Generating unique vertices per face
  17859. var index;
  17860. for (index = 0; index < totalIndices; index++) {
  17861. var vertexIndex = indices[index];
  17862. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17863. kind = kinds[kindIndex];
  17864. var stride = vbs[kind].getStrideSize();
  17865. for (var offset = 0; offset < stride; offset++) {
  17866. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  17867. }
  17868. }
  17869. }
  17870. // Updating faces & normal
  17871. var normals = [];
  17872. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  17873. for (index = 0; index < totalIndices; index += 3) {
  17874. indices[index] = index;
  17875. indices[index + 1] = index + 1;
  17876. indices[index + 2] = index + 2;
  17877. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  17878. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  17879. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  17880. var p1p2 = p1.subtract(p2);
  17881. var p3p2 = p3.subtract(p2);
  17882. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  17883. // Store same normals for every vertex
  17884. for (var localIndex = 0; localIndex < 3; localIndex++) {
  17885. normals.push(normal.x);
  17886. normals.push(normal.y);
  17887. normals.push(normal.z);
  17888. }
  17889. }
  17890. this.setIndices(indices);
  17891. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  17892. // Updating vertex buffers
  17893. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17894. kind = kinds[kindIndex];
  17895. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  17896. }
  17897. // Updating submeshes
  17898. this.releaseSubMeshes();
  17899. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  17900. var previousOne = previousSubmeshes[submeshIndex];
  17901. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  17902. }
  17903. this.synchronizeInstances();
  17904. };
  17905. /**
  17906. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  17907. * In other words, more vertices, no more indices and a single bigger VBO.
  17908. */
  17909. Mesh.prototype.convertToUnIndexedMesh = function () {
  17910. /// <summary>Remove indices by unfolding faces into buffers</summary>
  17911. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  17912. var kinds = this.getVerticesDataKinds();
  17913. var vbs = [];
  17914. var data = [];
  17915. var newdata = [];
  17916. var updatableNormals = false;
  17917. var kindIndex;
  17918. var kind;
  17919. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17920. kind = kinds[kindIndex];
  17921. var vertexBuffer = this.getVertexBuffer(kind);
  17922. vbs[kind] = vertexBuffer;
  17923. data[kind] = vbs[kind].getData();
  17924. newdata[kind] = [];
  17925. }
  17926. // Save previous submeshes
  17927. var previousSubmeshes = this.subMeshes.slice(0);
  17928. var indices = this.getIndices();
  17929. var totalIndices = this.getTotalIndices();
  17930. // Generating unique vertices per face
  17931. var index;
  17932. for (index = 0; index < totalIndices; index++) {
  17933. var vertexIndex = indices[index];
  17934. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17935. kind = kinds[kindIndex];
  17936. var stride = vbs[kind].getStrideSize();
  17937. for (var offset = 0; offset < stride; offset++) {
  17938. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  17939. }
  17940. }
  17941. }
  17942. // Updating indices
  17943. for (index = 0; index < totalIndices; index += 3) {
  17944. indices[index] = index;
  17945. indices[index + 1] = index + 1;
  17946. indices[index + 2] = index + 2;
  17947. }
  17948. this.setIndices(indices);
  17949. // Updating vertex buffers
  17950. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  17951. kind = kinds[kindIndex];
  17952. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  17953. }
  17954. // Updating submeshes
  17955. this.releaseSubMeshes();
  17956. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  17957. var previousOne = previousSubmeshes[submeshIndex];
  17958. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  17959. }
  17960. this._unIndexed = true;
  17961. this.synchronizeInstances();
  17962. };
  17963. /**
  17964. * Inverses facet orientations and inverts also the normals with `flipNormals` (default false) if true.
  17965. * Warning : the mesh is really modified.
  17966. */
  17967. Mesh.prototype.flipFaces = function (flipNormals) {
  17968. if (flipNormals === void 0) { flipNormals = false; }
  17969. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  17970. var i;
  17971. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17972. for (i = 0; i < vertex_data.normals.length; i++) {
  17973. vertex_data.normals[i] *= -1;
  17974. }
  17975. }
  17976. var temp;
  17977. for (i = 0; i < vertex_data.indices.length; i += 3) {
  17978. // reassign indices
  17979. temp = vertex_data.indices[i + 1];
  17980. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  17981. vertex_data.indices[i + 2] = temp;
  17982. }
  17983. vertex_data.applyToMesh(this);
  17984. };
  17985. // Instances
  17986. /**
  17987. * Creates a new `InstancedMesh` object from the mesh model.
  17988. */
  17989. Mesh.prototype.createInstance = function (name) {
  17990. return new BABYLON.InstancedMesh(name, this);
  17991. };
  17992. Mesh.prototype.synchronizeInstances = function () {
  17993. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  17994. var instance = this.instances[instanceIndex];
  17995. instance._syncSubMeshes();
  17996. }
  17997. };
  17998. /**
  17999. * Simplify the mesh according to the given array of settings.
  18000. * Function will return immediately and will simplify async.
  18001. * @param settings a collection of simplification settings.
  18002. * @param parallelProcessing should all levels calculate parallel or one after the other.
  18003. * @param type the type of simplification to run.
  18004. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  18005. */
  18006. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  18007. if (parallelProcessing === void 0) { parallelProcessing = true; }
  18008. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  18009. this.getScene().simplificationQueue.addTask({
  18010. settings: settings,
  18011. parallelProcessing: parallelProcessing,
  18012. mesh: this,
  18013. simplificationType: simplificationType,
  18014. successCallback: successCallback
  18015. });
  18016. };
  18017. /**
  18018. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  18019. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  18020. * This should be used together with the simplification to avoid disappearing triangles.
  18021. * @param successCallback an optional success callback to be called after the optimization finished.
  18022. */
  18023. Mesh.prototype.optimizeIndices = function (successCallback) {
  18024. var _this = this;
  18025. var indices = this.getIndices();
  18026. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18027. var vectorPositions = [];
  18028. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  18029. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  18030. }
  18031. var dupes = [];
  18032. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  18033. var realPos = vectorPositions.length - 1 - iteration;
  18034. var testedPosition = vectorPositions[realPos];
  18035. for (var j = 0; j < realPos; ++j) {
  18036. var againstPosition = vectorPositions[j];
  18037. if (testedPosition.equals(againstPosition)) {
  18038. dupes[realPos] = j;
  18039. break;
  18040. }
  18041. }
  18042. }, function () {
  18043. for (var i = 0; i < indices.length; ++i) {
  18044. indices[i] = dupes[indices[i]] || indices[i];
  18045. }
  18046. //indices are now reordered
  18047. var originalSubMeshes = _this.subMeshes.slice(0);
  18048. _this.setIndices(indices);
  18049. _this.subMeshes = originalSubMeshes;
  18050. if (successCallback) {
  18051. successCallback(_this);
  18052. }
  18053. });
  18054. };
  18055. // Statics
  18056. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  18057. var mesh = new Mesh(parsedMesh.name, scene);
  18058. mesh.id = parsedMesh.id;
  18059. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18060. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18061. if (parsedMesh.rotationQuaternion) {
  18062. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18063. }
  18064. else if (parsedMesh.rotation) {
  18065. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18066. }
  18067. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18068. if (parsedMesh.localMatrix) {
  18069. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18070. }
  18071. else if (parsedMesh.pivotMatrix) {
  18072. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18073. }
  18074. mesh.setEnabled(parsedMesh.isEnabled);
  18075. mesh.isVisible = parsedMesh.isVisible;
  18076. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18077. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18078. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18079. if (parsedMesh.applyFog !== undefined) {
  18080. mesh.applyFog = parsedMesh.applyFog;
  18081. }
  18082. if (parsedMesh.pickable !== undefined) {
  18083. mesh.isPickable = parsedMesh.pickable;
  18084. }
  18085. if (parsedMesh.alphaIndex !== undefined) {
  18086. mesh.alphaIndex = parsedMesh.alphaIndex;
  18087. }
  18088. mesh.receiveShadows = parsedMesh.receiveShadows;
  18089. mesh.billboardMode = parsedMesh.billboardMode;
  18090. if (parsedMesh.visibility !== undefined) {
  18091. mesh.visibility = parsedMesh.visibility;
  18092. }
  18093. mesh.checkCollisions = parsedMesh.checkCollisions;
  18094. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18095. // freezeWorldMatrix
  18096. if (parsedMesh.freezeWorldMatrix) {
  18097. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  18098. }
  18099. // Parent
  18100. if (parsedMesh.parentId) {
  18101. mesh._waitingParentId = parsedMesh.parentId;
  18102. }
  18103. // Actions
  18104. if (parsedMesh.actions !== undefined) {
  18105. mesh._waitingActions = parsedMesh.actions;
  18106. }
  18107. // Geometry
  18108. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18109. if (parsedMesh.delayLoadingFile) {
  18110. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18111. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18112. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18113. if (parsedMesh._binaryInfo) {
  18114. mesh._binaryInfo = parsedMesh._binaryInfo;
  18115. }
  18116. mesh._delayInfo = [];
  18117. if (parsedMesh.hasUVs) {
  18118. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18119. }
  18120. if (parsedMesh.hasUVs2) {
  18121. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18122. }
  18123. if (parsedMesh.hasUVs3) {
  18124. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  18125. }
  18126. if (parsedMesh.hasUVs4) {
  18127. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  18128. }
  18129. if (parsedMesh.hasUVs5) {
  18130. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  18131. }
  18132. if (parsedMesh.hasUVs6) {
  18133. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  18134. }
  18135. if (parsedMesh.hasColors) {
  18136. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18137. }
  18138. if (parsedMesh.hasMatricesIndices) {
  18139. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18140. }
  18141. if (parsedMesh.hasMatricesWeights) {
  18142. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18143. }
  18144. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  18145. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18146. mesh._checkDelayState();
  18147. }
  18148. }
  18149. else {
  18150. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  18151. }
  18152. // Material
  18153. if (parsedMesh.materialId) {
  18154. mesh.setMaterialByID(parsedMesh.materialId);
  18155. }
  18156. else {
  18157. mesh.material = null;
  18158. }
  18159. // Skeleton
  18160. if (parsedMesh.skeletonId > -1) {
  18161. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18162. if (parsedMesh.numBoneInfluencers) {
  18163. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  18164. }
  18165. }
  18166. // Animations
  18167. if (parsedMesh.animations) {
  18168. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18169. var parsedAnimation = parsedMesh.animations[animationIndex];
  18170. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18171. }
  18172. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  18173. }
  18174. if (parsedMesh.autoAnimate) {
  18175. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  18176. }
  18177. // Layer Mask
  18178. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18179. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18180. }
  18181. else {
  18182. mesh.layerMask = 0x0FFFFFFF;
  18183. }
  18184. //(Deprecated) physics
  18185. if (parsedMesh.physicsImpostor) {
  18186. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  18187. mass: parsedMesh.physicsMass,
  18188. friction: parsedMesh.physicsFriction,
  18189. restitution: parsedMesh.physicsRestitution
  18190. }, scene);
  18191. }
  18192. // Instances
  18193. if (parsedMesh.instances) {
  18194. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18195. var parsedInstance = parsedMesh.instances[index];
  18196. var instance = mesh.createInstance(parsedInstance.name);
  18197. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18198. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18199. if (parsedInstance.rotationQuaternion) {
  18200. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18201. }
  18202. else if (parsedInstance.rotation) {
  18203. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18204. }
  18205. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18206. instance.checkCollisions = mesh.checkCollisions;
  18207. if (parsedMesh.animations) {
  18208. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18209. parsedAnimation = parsedMesh.animations[animationIndex];
  18210. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18211. }
  18212. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  18213. }
  18214. }
  18215. }
  18216. return mesh;
  18217. };
  18218. /**
  18219. * Creates a ribbon mesh.
  18220. * Please consider using the same method from the `MeshBuilder` class instead.
  18221. * 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.
  18222. *
  18223. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  18224. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  18225. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  18226. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  18227. * 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.
  18228. * 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.
  18229. * 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
  18230. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18231. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18232. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18233. */
  18234. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  18235. return BABYLON.MeshBuilder.CreateRibbon(name, {
  18236. pathArray: pathArray,
  18237. closeArray: closeArray,
  18238. closePath: closePath,
  18239. offset: offset,
  18240. updatable: updatable,
  18241. sideOrientation: sideOrientation,
  18242. instance: instance
  18243. }, scene);
  18244. };
  18245. /**
  18246. * Creates a plane polygonal mesh. By default, this is a disc.
  18247. * Please consider using the same method from the `MeshBuilder` class instead.
  18248. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  18249. * 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.
  18250. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18251. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18252. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18253. */
  18254. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  18255. var options = {
  18256. radius: radius,
  18257. tessellation: tessellation,
  18258. sideOrientation: sideOrientation,
  18259. updatable: updatable
  18260. };
  18261. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  18262. };
  18263. /**
  18264. * Creates a box mesh.
  18265. * Please consider using the same method from the `MeshBuilder` class instead.
  18266. * The parameter `size` sets the size (float) of each box side (default 1).
  18267. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18268. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18269. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18270. */
  18271. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  18272. var options = {
  18273. size: size,
  18274. sideOrientation: sideOrientation,
  18275. updatable: updatable
  18276. };
  18277. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  18278. };
  18279. /**
  18280. * Creates a sphere mesh.
  18281. * Please consider using the same method from the `MeshBuilder` class instead.
  18282. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  18283. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  18284. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18285. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18286. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18287. */
  18288. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  18289. var options = {
  18290. segments: segments,
  18291. diameterX: diameter,
  18292. diameterY: diameter,
  18293. diameterZ: diameter,
  18294. sideOrientation: sideOrientation,
  18295. updatable: updatable
  18296. };
  18297. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  18298. };
  18299. /**
  18300. * Creates a cylinder or a cone mesh.
  18301. * Please consider using the same method from the `MeshBuilder` class instead.
  18302. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  18303. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  18304. * 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.
  18305. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  18306. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  18307. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18308. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18309. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18310. */
  18311. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  18312. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  18313. if (scene !== undefined) {
  18314. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  18315. updatable = scene;
  18316. }
  18317. scene = subdivisions;
  18318. subdivisions = 1;
  18319. }
  18320. var options = {
  18321. height: height,
  18322. diameterTop: diameterTop,
  18323. diameterBottom: diameterBottom,
  18324. tessellation: tessellation,
  18325. subdivisions: subdivisions,
  18326. sideOrientation: sideOrientation,
  18327. updatable: updatable
  18328. };
  18329. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  18330. };
  18331. // Torus (Code from SharpDX.org)
  18332. /**
  18333. * Creates a torus mesh.
  18334. * Please consider using the same method from the `MeshBuilder` class instead.
  18335. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  18336. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  18337. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  18338. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18339. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18340. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18341. */
  18342. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  18343. var options = {
  18344. diameter: diameter,
  18345. thickness: thickness,
  18346. tessellation: tessellation,
  18347. sideOrientation: sideOrientation,
  18348. updatable: updatable
  18349. };
  18350. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  18351. };
  18352. /**
  18353. * Creates a torus knot mesh.
  18354. * Please consider using the same method from the `MeshBuilder` class instead.
  18355. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  18356. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  18357. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  18358. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  18359. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18360. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18361. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18362. */
  18363. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  18364. var options = {
  18365. radius: radius,
  18366. tube: tube,
  18367. radialSegments: radialSegments,
  18368. tubularSegments: tubularSegments,
  18369. p: p,
  18370. q: q,
  18371. sideOrientation: sideOrientation,
  18372. updatable: updatable
  18373. };
  18374. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  18375. };
  18376. /**
  18377. * Creates a line mesh.
  18378. * Please consider using the same method from the `MeshBuilder` class instead.
  18379. * 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.
  18380. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18381. * The parameter `points` is an array successive Vector3.
  18382. * 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
  18383. * When updating an instance, remember that only point positions can change, not the number of points.
  18384. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18385. */
  18386. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  18387. var options = {
  18388. points: points,
  18389. updatable: updatable,
  18390. instance: instance
  18391. };
  18392. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  18393. };
  18394. /**
  18395. * Creates a dashed line mesh.
  18396. * Please consider using the same method from the `MeshBuilder` class instead.
  18397. * 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.
  18398. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  18399. * The parameter `points` is an array successive Vector3.
  18400. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  18401. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  18402. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  18403. * 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
  18404. * When updating an instance, remember that only point positions can change, not the number of points.
  18405. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18406. */
  18407. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  18408. var options = {
  18409. points: points,
  18410. dashSize: dashSize,
  18411. gapSize: gapSize,
  18412. dashNb: dashNb,
  18413. updatable: updatable
  18414. };
  18415. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  18416. };
  18417. /**
  18418. * Creates an extruded shape mesh.
  18419. * 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.
  18420. * Please consider using the same method from the `MeshBuilder` class instead.
  18421. *
  18422. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18423. * 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
  18424. * extruded along the Z axis.
  18425. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18426. * 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.
  18427. * The parameter `scale` (float, default 1) is the value to scale the shape.
  18428. * 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
  18429. * 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
  18430. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18431. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18432. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18433. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18434. */
  18435. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  18436. var options = {
  18437. shape: shape,
  18438. path: path,
  18439. scale: scale,
  18440. rotation: rotation,
  18441. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  18442. sideOrientation: sideOrientation,
  18443. instance: instance,
  18444. updatable: updatable
  18445. };
  18446. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  18447. };
  18448. /**
  18449. * Creates an custom extruded shape mesh.
  18450. * 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.
  18451. * Please consider using the same method from the `MeshBuilder` class instead.
  18452. *
  18453. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  18454. * 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
  18455. * extruded along the Z axis.
  18456. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  18457. * 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
  18458. * and the distance of this point from the begining of the path :
  18459. * ```rotationFunction = function(i, distance) {
  18460. * // do things
  18461. * return rotationValue; }```
  18462. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  18463. * 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
  18464. * and the distance of this point from the begining of the path :
  18465. * ````scaleFunction = function(i, distance) {
  18466. * // do things
  18467. * return scaleValue;}```
  18468. * It must returns a float value that will be the scale value applied to the shape on each path point.
  18469. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  18470. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  18471. * 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
  18472. * 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
  18473. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  18474. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18475. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18476. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18477. */
  18478. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  18479. var options = {
  18480. shape: shape,
  18481. path: path,
  18482. scaleFunction: scaleFunction,
  18483. rotationFunction: rotationFunction,
  18484. ribbonCloseArray: ribbonCloseArray,
  18485. ribbonClosePath: ribbonClosePath,
  18486. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  18487. sideOrientation: sideOrientation,
  18488. instance: instance,
  18489. updatable: updatable
  18490. };
  18491. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  18492. };
  18493. /**
  18494. * Creates lathe mesh.
  18495. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  18496. * Please consider using the same method from the `MeshBuilder` class instead.
  18497. *
  18498. * 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
  18499. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  18500. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  18501. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  18502. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18503. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18504. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18505. */
  18506. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  18507. var options = {
  18508. shape: shape,
  18509. radius: radius,
  18510. tessellation: tessellation,
  18511. sideOrientation: sideOrientation,
  18512. updatable: updatable
  18513. };
  18514. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  18515. };
  18516. /**
  18517. * Creates a plane mesh.
  18518. * Please consider using the same method from the `MeshBuilder` class instead.
  18519. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  18520. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18521. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18522. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18523. */
  18524. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  18525. var options = {
  18526. size: size,
  18527. width: size,
  18528. height: size,
  18529. sideOrientation: sideOrientation,
  18530. updatable: updatable
  18531. };
  18532. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  18533. };
  18534. /**
  18535. * Creates a ground mesh.
  18536. * Please consider using the same method from the `MeshBuilder` class instead.
  18537. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  18538. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  18539. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18540. */
  18541. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  18542. var options = {
  18543. width: width,
  18544. height: height,
  18545. subdivisions: subdivisions,
  18546. updatable: updatable
  18547. };
  18548. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  18549. };
  18550. /**
  18551. * Creates a tiled ground mesh.
  18552. * Please consider using the same method from the `MeshBuilder` class instead.
  18553. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  18554. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  18555. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  18556. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  18557. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  18558. * numbers of subdivisions on the ground width and height of each tile.
  18559. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18560. */
  18561. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  18562. var options = {
  18563. xmin: xmin,
  18564. zmin: zmin,
  18565. xmax: xmax,
  18566. zmax: zmax,
  18567. subdivisions: subdivisions,
  18568. precision: precision,
  18569. updatable: updatable
  18570. };
  18571. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  18572. };
  18573. /**
  18574. * Creates a ground mesh from a height map.
  18575. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  18576. * Please consider using the same method from the `MeshBuilder` class instead.
  18577. * The parameter `url` sets the URL of the height map image resource.
  18578. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  18579. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  18580. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  18581. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  18582. * 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).
  18583. * This function is passed the newly built mesh : ```function(mesh) { // do things
  18584. * return; }```
  18585. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18586. */
  18587. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  18588. var options = {
  18589. width: width,
  18590. height: height,
  18591. subdivisions: subdivisions,
  18592. minHeight: minHeight,
  18593. maxHeight: maxHeight,
  18594. updatable: updatable,
  18595. onReady: onReady
  18596. };
  18597. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  18598. };
  18599. /**
  18600. * Creates a tube mesh.
  18601. * 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.
  18602. *
  18603. * Please consider using the same method from the `MeshBuilder` class instead.
  18604. * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
  18605. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  18606. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  18607. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  18608. * 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.
  18609. * It must return a radius value (positive float) :
  18610. * ```var radiusFunction = function(i, distance) {
  18611. * // do things
  18612. * return radius; }```
  18613. * 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
  18614. * 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
  18615. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18616. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18617. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18618. */
  18619. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  18620. var options = {
  18621. path: path,
  18622. radius: radius,
  18623. tessellation: tessellation,
  18624. radiusFunction: radiusFunction,
  18625. arc: 1,
  18626. cap: cap,
  18627. updatable: updatable,
  18628. sideOrientation: sideOrientation,
  18629. instance: instance
  18630. };
  18631. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  18632. };
  18633. /**
  18634. * Creates a polyhedron mesh.
  18635. *
  18636. * Please consider using the same method from the `MeshBuilder` class instead.
  18637. * 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
  18638. * to choose the wanted type.
  18639. * The parameter `size` (positive float, default 1) sets the polygon size.
  18640. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  18641. * 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`.
  18642. * 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
  18643. * 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)`).
  18644. * 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
  18645. * 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.
  18646. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18647. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18648. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18649. */
  18650. Mesh.CreatePolyhedron = function (name, options, scene) {
  18651. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  18652. };
  18653. /**
  18654. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  18655. * Please consider using the same method from the `MeshBuilder` class instead.
  18656. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  18657. * 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`).
  18658. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  18659. * 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.
  18660. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  18661. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  18662. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  18663. */
  18664. Mesh.CreateIcoSphere = function (name, options, scene) {
  18665. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  18666. };
  18667. /**
  18668. * Creates a decal mesh.
  18669. * Please consider using the same method from the `MeshBuilder` class instead.
  18670. * 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.
  18671. * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  18672. * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  18673. * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
  18674. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  18675. */
  18676. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  18677. var options = {
  18678. position: position,
  18679. normal: normal,
  18680. size: size,
  18681. angle: angle
  18682. };
  18683. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  18684. };
  18685. // Skeletons
  18686. /**
  18687. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  18688. */
  18689. Mesh.prototype.setPositionsForCPUSkinning = function () {
  18690. var source;
  18691. if (!this._sourcePositions) {
  18692. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18693. this._sourcePositions = new Float32Array(source);
  18694. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  18695. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  18696. }
  18697. }
  18698. return this._sourcePositions;
  18699. };
  18700. /**
  18701. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  18702. */
  18703. Mesh.prototype.setNormalsForCPUSkinning = function () {
  18704. var source;
  18705. if (!this._sourceNormals) {
  18706. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18707. this._sourceNormals = new Float32Array(source);
  18708. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  18709. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  18710. }
  18711. }
  18712. return this._sourceNormals;
  18713. };
  18714. /**
  18715. * Update the vertex buffers by applying transformation from the bones
  18716. * @param {skeleton} skeleton to apply
  18717. */
  18718. Mesh.prototype.applySkeleton = function (skeleton) {
  18719. if (!this.geometry) {
  18720. return;
  18721. }
  18722. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  18723. return;
  18724. }
  18725. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  18726. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18727. return this;
  18728. }
  18729. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18730. return this;
  18731. }
  18732. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  18733. return this;
  18734. }
  18735. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  18736. return this;
  18737. }
  18738. if (!this._sourcePositions) {
  18739. this.setPositionsForCPUSkinning();
  18740. }
  18741. if (!this._sourceNormals) {
  18742. this.setNormalsForCPUSkinning();
  18743. }
  18744. // positionsData checks for not being Float32Array will only pass at most once
  18745. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18746. if (!(positionsData instanceof Float32Array)) {
  18747. positionsData = new Float32Array(positionsData);
  18748. }
  18749. // normalsData checks for not being Float32Array will only pass at most once
  18750. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18751. if (!(normalsData instanceof Float32Array)) {
  18752. normalsData = new Float32Array(normalsData);
  18753. }
  18754. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  18755. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  18756. var needExtras = this.numBoneInfluencers > 4;
  18757. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  18758. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  18759. var skeletonMatrices = skeleton.getTransformMatrices(this);
  18760. var tempVector3 = BABYLON.Vector3.Zero();
  18761. var finalMatrix = new BABYLON.Matrix();
  18762. var tempMatrix = new BABYLON.Matrix();
  18763. var matWeightIdx = 0;
  18764. var inf;
  18765. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  18766. var weight;
  18767. for (inf = 0; inf < 4; inf++) {
  18768. weight = matricesWeightsData[matWeightIdx + inf];
  18769. if (weight > 0) {
  18770. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  18771. finalMatrix.addToSelf(tempMatrix);
  18772. }
  18773. else
  18774. break;
  18775. }
  18776. if (needExtras) {
  18777. for (inf = 0; inf < 4; inf++) {
  18778. weight = matricesWeightsExtraData[matWeightIdx + inf];
  18779. if (weight > 0) {
  18780. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  18781. finalMatrix.addToSelf(tempMatrix);
  18782. }
  18783. else
  18784. break;
  18785. }
  18786. }
  18787. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  18788. tempVector3.toArray(positionsData, index);
  18789. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  18790. tempVector3.toArray(normalsData, index);
  18791. finalMatrix.reset();
  18792. }
  18793. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  18794. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  18795. return this;
  18796. };
  18797. // Tools
  18798. Mesh.MinMax = function (meshes) {
  18799. var minVector = null;
  18800. var maxVector = null;
  18801. for (var i in meshes) {
  18802. var mesh = meshes[i];
  18803. var boundingBox = mesh.getBoundingInfo().boundingBox;
  18804. if (!minVector) {
  18805. minVector = boundingBox.minimumWorld;
  18806. maxVector = boundingBox.maximumWorld;
  18807. continue;
  18808. }
  18809. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  18810. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  18811. }
  18812. return {
  18813. min: minVector,
  18814. max: maxVector
  18815. };
  18816. };
  18817. Mesh.Center = function (meshesOrMinMaxVector) {
  18818. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  18819. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  18820. };
  18821. /**
  18822. * Merge the array of meshes into a single mesh for performance reasons.
  18823. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  18824. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  18825. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  18826. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  18827. */
  18828. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  18829. if (disposeSource === void 0) { disposeSource = true; }
  18830. var index;
  18831. if (!allow32BitsIndices) {
  18832. var totalVertices = 0;
  18833. // Counting vertices
  18834. for (index = 0; index < meshes.length; index++) {
  18835. if (meshes[index]) {
  18836. totalVertices += meshes[index].getTotalVertices();
  18837. if (totalVertices > 65536) {
  18838. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  18839. return null;
  18840. }
  18841. }
  18842. }
  18843. }
  18844. // Merge
  18845. var vertexData;
  18846. var otherVertexData;
  18847. var source;
  18848. for (index = 0; index < meshes.length; index++) {
  18849. if (meshes[index]) {
  18850. meshes[index].computeWorldMatrix(true);
  18851. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  18852. otherVertexData.transform(meshes[index].getWorldMatrix());
  18853. if (vertexData) {
  18854. vertexData.merge(otherVertexData);
  18855. }
  18856. else {
  18857. vertexData = otherVertexData;
  18858. source = meshes[index];
  18859. }
  18860. }
  18861. }
  18862. if (!meshSubclass) {
  18863. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  18864. }
  18865. vertexData.applyToMesh(meshSubclass);
  18866. // Setting properties
  18867. meshSubclass.material = source.material;
  18868. meshSubclass.checkCollisions = source.checkCollisions;
  18869. // Cleaning
  18870. if (disposeSource) {
  18871. for (index = 0; index < meshes.length; index++) {
  18872. if (meshes[index]) {
  18873. meshes[index].dispose();
  18874. }
  18875. }
  18876. }
  18877. return meshSubclass;
  18878. };
  18879. // Consts
  18880. Mesh._FRONTSIDE = 0;
  18881. Mesh._BACKSIDE = 1;
  18882. Mesh._DOUBLESIDE = 2;
  18883. Mesh._DEFAULTSIDE = 0;
  18884. Mesh._NO_CAP = 0;
  18885. Mesh._CAP_START = 1;
  18886. Mesh._CAP_END = 2;
  18887. Mesh._CAP_ALL = 3;
  18888. return Mesh;
  18889. })(BABYLON.AbstractMesh);
  18890. BABYLON.Mesh = Mesh;
  18891. })(BABYLON || (BABYLON = {}));
  18892. var BABYLON;
  18893. (function (BABYLON) {
  18894. var SubMesh = (function () {
  18895. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  18896. if (createBoundingBox === void 0) { createBoundingBox = true; }
  18897. this.materialIndex = materialIndex;
  18898. this.verticesStart = verticesStart;
  18899. this.verticesCount = verticesCount;
  18900. this.indexStart = indexStart;
  18901. this.indexCount = indexCount;
  18902. this._renderId = 0;
  18903. this._mesh = mesh;
  18904. this._renderingMesh = renderingMesh || mesh;
  18905. mesh.subMeshes.push(this);
  18906. this._trianglePlanes = [];
  18907. this._id = mesh.subMeshes.length - 1;
  18908. if (createBoundingBox) {
  18909. this.refreshBoundingInfo();
  18910. mesh.computeWorldMatrix(true);
  18911. }
  18912. }
  18913. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  18914. get: function () {
  18915. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  18916. },
  18917. enumerable: true,
  18918. configurable: true
  18919. });
  18920. SubMesh.prototype.getBoundingInfo = function () {
  18921. if (this.IsGlobal) {
  18922. return this._mesh.getBoundingInfo();
  18923. }
  18924. return this._boundingInfo;
  18925. };
  18926. SubMesh.prototype.getMesh = function () {
  18927. return this._mesh;
  18928. };
  18929. SubMesh.prototype.getRenderingMesh = function () {
  18930. return this._renderingMesh;
  18931. };
  18932. SubMesh.prototype.getMaterial = function () {
  18933. var rootMaterial = this._renderingMesh.material;
  18934. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  18935. var multiMaterial = rootMaterial;
  18936. return multiMaterial.getSubMaterial(this.materialIndex);
  18937. }
  18938. if (!rootMaterial) {
  18939. return this._mesh.getScene().defaultMaterial;
  18940. }
  18941. return rootMaterial;
  18942. };
  18943. // Methods
  18944. SubMesh.prototype.refreshBoundingInfo = function () {
  18945. this._lastColliderWorldVertices = null;
  18946. if (this.IsGlobal) {
  18947. return;
  18948. }
  18949. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18950. if (!data) {
  18951. this._boundingInfo = this._mesh._boundingInfo;
  18952. return;
  18953. }
  18954. var indices = this._renderingMesh.getIndices();
  18955. var extend;
  18956. //is this the only submesh?
  18957. if (this.indexStart === 0 && this.indexCount === indices.length) {
  18958. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  18959. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  18960. }
  18961. else {
  18962. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  18963. }
  18964. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18965. };
  18966. SubMesh.prototype._checkCollision = function (collider) {
  18967. return this.getBoundingInfo()._checkCollision(collider);
  18968. };
  18969. SubMesh.prototype.updateBoundingInfo = function (world) {
  18970. if (!this.getBoundingInfo()) {
  18971. this.refreshBoundingInfo();
  18972. }
  18973. this.getBoundingInfo().update(world);
  18974. };
  18975. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  18976. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  18977. };
  18978. SubMesh.prototype.render = function (enableAlphaMode) {
  18979. this._renderingMesh.render(this, enableAlphaMode);
  18980. };
  18981. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  18982. if (!this._linesIndexBuffer) {
  18983. var linesIndices = [];
  18984. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  18985. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  18986. }
  18987. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  18988. this.linesIndexCount = linesIndices.length;
  18989. }
  18990. return this._linesIndexBuffer;
  18991. };
  18992. SubMesh.prototype.canIntersects = function (ray) {
  18993. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  18994. };
  18995. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  18996. var intersectInfo = null;
  18997. // LineMesh first as it's also a Mesh...
  18998. if (this._mesh instanceof BABYLON.LinesMesh) {
  18999. var lineMesh = this._mesh;
  19000. // Line test
  19001. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  19002. var p0 = positions[indices[index]];
  19003. var p1 = positions[indices[index + 1]];
  19004. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  19005. if (length < 0) {
  19006. continue;
  19007. }
  19008. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  19009. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  19010. if (fastCheck) {
  19011. break;
  19012. }
  19013. }
  19014. }
  19015. }
  19016. else {
  19017. // Triangles test
  19018. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  19019. var p0 = positions[indices[index]];
  19020. var p1 = positions[indices[index + 1]];
  19021. var p2 = positions[indices[index + 2]];
  19022. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  19023. if (currentIntersectInfo) {
  19024. if (currentIntersectInfo.distance < 0) {
  19025. continue;
  19026. }
  19027. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  19028. intersectInfo = currentIntersectInfo;
  19029. intersectInfo.faceId = index / 3;
  19030. if (fastCheck) {
  19031. break;
  19032. }
  19033. }
  19034. }
  19035. }
  19036. }
  19037. return intersectInfo;
  19038. };
  19039. // Clone
  19040. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  19041. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  19042. if (!this.IsGlobal) {
  19043. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  19044. }
  19045. return result;
  19046. };
  19047. // Dispose
  19048. SubMesh.prototype.dispose = function () {
  19049. if (this._linesIndexBuffer) {
  19050. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  19051. this._linesIndexBuffer = null;
  19052. }
  19053. // Remove from mesh
  19054. var index = this._mesh.subMeshes.indexOf(this);
  19055. this._mesh.subMeshes.splice(index, 1);
  19056. };
  19057. // Statics
  19058. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  19059. var minVertexIndex = Number.MAX_VALUE;
  19060. var maxVertexIndex = -Number.MAX_VALUE;
  19061. renderingMesh = renderingMesh || mesh;
  19062. var indices = renderingMesh.getIndices();
  19063. for (var index = startIndex; index < startIndex + indexCount; index++) {
  19064. var vertexIndex = indices[index];
  19065. if (vertexIndex < minVertexIndex)
  19066. minVertexIndex = vertexIndex;
  19067. if (vertexIndex > maxVertexIndex)
  19068. maxVertexIndex = vertexIndex;
  19069. }
  19070. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  19071. };
  19072. return SubMesh;
  19073. })();
  19074. BABYLON.SubMesh = SubMesh;
  19075. })(BABYLON || (BABYLON = {}));
  19076. var BABYLON;
  19077. (function (BABYLON) {
  19078. var MeshBuilder = (function () {
  19079. function MeshBuilder() {
  19080. }
  19081. /**
  19082. * Creates a box mesh.
  19083. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  19084. * The parameter `size` sets the size (float) of each box side (default 1).
  19085. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  19086. * 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).
  19087. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  19088. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19089. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19090. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19091. */
  19092. MeshBuilder.CreateBox = function (name, options, scene) {
  19093. var box = new BABYLON.Mesh(name, scene);
  19094. var vertexData = BABYLON.VertexData.CreateBox(options);
  19095. vertexData.applyToMesh(box, options.updatable);
  19096. return box;
  19097. };
  19098. /**
  19099. * Creates a sphere mesh.
  19100. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  19101. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  19102. * 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`).
  19103. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  19104. * 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
  19105. * 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).
  19106. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19107. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19108. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19109. */
  19110. MeshBuilder.CreateSphere = function (name, options, scene) {
  19111. var sphere = new BABYLON.Mesh(name, scene);
  19112. var vertexData = BABYLON.VertexData.CreateSphere(options);
  19113. vertexData.applyToMesh(sphere, options.updatable);
  19114. return sphere;
  19115. };
  19116. /**
  19117. * Creates a plane polygonal mesh. By default, this is a disc.
  19118. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  19119. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  19120. * 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.
  19121. * 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
  19122. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19123. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19124. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19125. */
  19126. MeshBuilder.CreateDisc = function (name, options, scene) {
  19127. var disc = new BABYLON.Mesh(name, scene);
  19128. var vertexData = BABYLON.VertexData.CreateDisc(options);
  19129. vertexData.applyToMesh(disc, options.updatable);
  19130. return disc;
  19131. };
  19132. /**
  19133. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  19134. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  19135. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  19136. * 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`).
  19137. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  19138. * 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.
  19139. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19140. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19141. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19142. */
  19143. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  19144. var sphere = new BABYLON.Mesh(name, scene);
  19145. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  19146. vertexData.applyToMesh(sphere, options.updatable);
  19147. return sphere;
  19148. };
  19149. ;
  19150. /**
  19151. * Creates a ribbon mesh.
  19152. * 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.
  19153. *
  19154. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  19155. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  19156. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  19157. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  19158. * 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.
  19159. * 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.
  19160. * 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
  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.CreateRibbon = function (name, options, scene) {
  19166. var pathArray = options.pathArray;
  19167. var closeArray = options.closeArray;
  19168. var closePath = options.closePath;
  19169. var offset = options.offset;
  19170. var sideOrientation = options.sideOrientation;
  19171. var instance = options.instance;
  19172. var updatable = options.updatable;
  19173. if (instance) {
  19174. // positionFunction : ribbon case
  19175. // only pathArray and sideOrientation parameters are taken into account for positions update
  19176. var positionFunction = function (positions) {
  19177. var minlg = pathArray[0].length;
  19178. var i = 0;
  19179. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  19180. for (var si = 1; si <= ns; si++) {
  19181. for (var p = 0; p < pathArray.length; p++) {
  19182. var path = pathArray[p];
  19183. var l = path.length;
  19184. minlg = (minlg < l) ? minlg : l;
  19185. var j = 0;
  19186. while (j < minlg) {
  19187. positions[i] = path[j].x;
  19188. positions[i + 1] = path[j].y;
  19189. positions[i + 2] = path[j].z;
  19190. j++;
  19191. i += 3;
  19192. }
  19193. if (instance._closePath) {
  19194. positions[i] = path[0].x;
  19195. positions[i + 1] = path[0].y;
  19196. positions[i + 2] = path[0].z;
  19197. i += 3;
  19198. }
  19199. }
  19200. }
  19201. };
  19202. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19203. positionFunction(positions);
  19204. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19205. if (!(instance.areNormalsFrozen)) {
  19206. var indices = instance.getIndices();
  19207. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19208. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19209. if (instance._closePath) {
  19210. var indexFirst = 0;
  19211. var indexLast = 0;
  19212. for (var p = 0; p < pathArray.length; p++) {
  19213. indexFirst = instance._idx[p] * 3;
  19214. if (p + 1 < pathArray.length) {
  19215. indexLast = (instance._idx[p + 1] - 1) * 3;
  19216. }
  19217. else {
  19218. indexLast = normals.length - 3;
  19219. }
  19220. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  19221. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  19222. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  19223. normals[indexLast] = normals[indexFirst];
  19224. normals[indexLast + 1] = normals[indexFirst + 1];
  19225. normals[indexLast + 2] = normals[indexFirst + 2];
  19226. }
  19227. }
  19228. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19229. }
  19230. return instance;
  19231. }
  19232. else {
  19233. var ribbon = new BABYLON.Mesh(name, scene);
  19234. ribbon.sideOrientation = sideOrientation;
  19235. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  19236. if (closePath) {
  19237. ribbon._idx = vertexData._idx;
  19238. }
  19239. ribbon._closePath = closePath;
  19240. ribbon._closeArray = closeArray;
  19241. vertexData.applyToMesh(ribbon, updatable);
  19242. return ribbon;
  19243. }
  19244. };
  19245. /**
  19246. * Creates a cylinder or a cone mesh.
  19247. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  19248. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  19249. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  19250. * 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.
  19251. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  19252. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  19253. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  19254. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  19255. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  19256. * 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).
  19257. * 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
  19258. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  19259. * 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
  19260. * 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.
  19261. * If `enclose` is false, a ring surface is one element.
  19262. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  19263. * 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
  19264. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19265. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19266. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19267. */
  19268. MeshBuilder.CreateCylinder = function (name, options, scene) {
  19269. var cylinder = new BABYLON.Mesh(name, scene);
  19270. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  19271. vertexData.applyToMesh(cylinder, options.updatable);
  19272. return cylinder;
  19273. };
  19274. /**
  19275. * Creates a torus mesh.
  19276. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  19277. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  19278. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  19279. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  19280. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19281. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19282. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19283. */
  19284. MeshBuilder.CreateTorus = function (name, options, scene) {
  19285. var torus = new BABYLON.Mesh(name, scene);
  19286. var vertexData = BABYLON.VertexData.CreateTorus(options);
  19287. vertexData.applyToMesh(torus, options.updatable);
  19288. return torus;
  19289. };
  19290. /**
  19291. * Creates a torus knot mesh.
  19292. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  19293. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  19294. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  19295. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  19296. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  19297. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19298. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19299. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19300. */
  19301. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  19302. var torusKnot = new BABYLON.Mesh(name, scene);
  19303. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  19304. vertexData.applyToMesh(torusKnot, options.updatable);
  19305. return torusKnot;
  19306. };
  19307. /**
  19308. * Creates a line system mesh.
  19309. * A line system is a pool of many lines gathered in a single mesh.
  19310. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  19311. * 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.
  19312. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  19313. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  19314. * 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
  19315. * 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
  19316. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  19317. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19318. */
  19319. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  19320. var instance = options.instance;
  19321. var lines = options.lines;
  19322. if (instance) {
  19323. var positionFunction = function (positions) {
  19324. var i = 0;
  19325. for (var l = 0; l < lines.length; l++) {
  19326. var points = lines[l];
  19327. for (var p = 0; p < points.length; p++) {
  19328. positions[i] = points[p].x;
  19329. positions[i + 1] = points[p].y;
  19330. positions[i + 2] = points[p].z;
  19331. i += 3;
  19332. }
  19333. }
  19334. };
  19335. instance.updateMeshPositions(positionFunction, false);
  19336. return instance;
  19337. }
  19338. // line system creation
  19339. var lineSystem = new BABYLON.LinesMesh(name, scene);
  19340. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  19341. vertexData.applyToMesh(lineSystem, options.updatable);
  19342. return lineSystem;
  19343. };
  19344. /**
  19345. * Creates a line mesh.
  19346. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  19347. * 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.
  19348. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19349. * The parameter `points` is an array successive Vector3.
  19350. * 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
  19351. * When updating an instance, remember that only point positions can change, not the number of points.
  19352. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19353. */
  19354. MeshBuilder.CreateLines = function (name, options, scene) {
  19355. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  19356. return lines;
  19357. };
  19358. /**
  19359. * Creates a dashed line mesh.
  19360. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  19361. * 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.
  19362. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  19363. * The parameter `points` is an array successive Vector3.
  19364. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  19365. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  19366. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  19367. * 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
  19368. * When updating an instance, remember that only point positions can change, not the number of points.
  19369. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19370. */
  19371. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  19372. var points = options.points;
  19373. var instance = options.instance;
  19374. var gapSize = options.gapSize;
  19375. var dashNb = options.dashNb;
  19376. var dashSize = options.dashSize;
  19377. if (instance) {
  19378. var positionFunction = function (positions) {
  19379. var curvect = BABYLON.Vector3.Zero();
  19380. var nbSeg = positions.length / 6;
  19381. var lg = 0;
  19382. var nb = 0;
  19383. var shft = 0;
  19384. var dashshft = 0;
  19385. var curshft = 0;
  19386. var p = 0;
  19387. var i = 0;
  19388. var j = 0;
  19389. for (i = 0; i < points.length - 1; i++) {
  19390. points[i + 1].subtractToRef(points[i], curvect);
  19391. lg += curvect.length();
  19392. }
  19393. shft = lg / nbSeg;
  19394. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  19395. for (i = 0; i < points.length - 1; i++) {
  19396. points[i + 1].subtractToRef(points[i], curvect);
  19397. nb = Math.floor(curvect.length() / shft);
  19398. curvect.normalize();
  19399. j = 0;
  19400. while (j < nb && p < positions.length) {
  19401. curshft = shft * j;
  19402. positions[p] = points[i].x + curshft * curvect.x;
  19403. positions[p + 1] = points[i].y + curshft * curvect.y;
  19404. positions[p + 2] = points[i].z + curshft * curvect.z;
  19405. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  19406. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  19407. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  19408. p += 6;
  19409. j++;
  19410. }
  19411. }
  19412. while (p < positions.length) {
  19413. positions[p] = points[i].x;
  19414. positions[p + 1] = points[i].y;
  19415. positions[p + 2] = points[i].z;
  19416. p += 3;
  19417. }
  19418. };
  19419. instance.updateMeshPositions(positionFunction, false);
  19420. return instance;
  19421. }
  19422. // dashed lines creation
  19423. var dashedLines = new BABYLON.LinesMesh(name, scene);
  19424. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  19425. vertexData.applyToMesh(dashedLines, options.updatable);
  19426. dashedLines.dashSize = dashSize;
  19427. dashedLines.gapSize = gapSize;
  19428. return dashedLines;
  19429. };
  19430. /**
  19431. * Creates an extruded shape mesh.
  19432. * 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.
  19433. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  19434. *
  19435. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19436. * 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
  19437. * extruded along the Z axis.
  19438. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19439. * 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.
  19440. * The parameter `scale` (float, default 1) is the value to scale the shape.
  19441. * 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
  19442. * 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
  19443. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19444. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19445. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19446. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19447. */
  19448. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  19449. var path = options.path;
  19450. var shape = options.shape;
  19451. var scale = options.scale || 1;
  19452. var rotation = options.rotation || 0;
  19453. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  19454. var updatable = options.updatable;
  19455. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19456. var instance = options.instance;
  19457. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance);
  19458. };
  19459. /**
  19460. * Creates an custom extruded shape mesh.
  19461. * 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.
  19462. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  19463. *
  19464. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  19465. * 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
  19466. * extruded along the Z axis.
  19467. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  19468. * 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
  19469. * and the distance of this point from the begining of the path :
  19470. * ```rotationFunction = function(i, distance) {
  19471. * // do things
  19472. * return rotationValue; }```
  19473. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  19474. * 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
  19475. * and the distance of this point from the begining of the path :
  19476. * ````scaleFunction = function(i, distance) {
  19477. * // do things
  19478. * return scaleValue;}```
  19479. * It must returns a float value that will be the scale value applied to the shape on each path point.
  19480. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  19481. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  19482. * 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
  19483. * 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
  19484. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  19485. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19486. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19487. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19488. */
  19489. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  19490. var path = options.path;
  19491. var shape = options.shape;
  19492. var scaleFunction = options.scaleFunction || (function () { return 1; });
  19493. var rotationFunction = options.rotationFunction || (function () { return 0; });
  19494. var ribbonCloseArray = options.ribbonCloseArray || false;
  19495. var ribbonClosePath = options.ribbonClosePath || false;
  19496. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  19497. var updatable = options.updatable;
  19498. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19499. var instance = options.instance;
  19500. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance);
  19501. };
  19502. /**
  19503. * Creates lathe mesh.
  19504. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  19505. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  19506. *
  19507. * 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
  19508. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  19509. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  19510. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  19511. * 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.
  19512. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  19513. * 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
  19514. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19515. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19516. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19517. */
  19518. MeshBuilder.CreateLathe = function (name, options, scene) {
  19519. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  19520. var closed = (options.closed === undefined) ? true : options.closed;
  19521. var shape = options.shape;
  19522. var radius = options.radius || 1;
  19523. var tessellation = options.tessellation || 64;
  19524. var updatable = options.updatable;
  19525. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19526. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  19527. var pi2 = Math.PI * 2;
  19528. var paths = new Array();
  19529. var i = 0;
  19530. var p = 0;
  19531. var step = pi2 / tessellation * arc;
  19532. var rotated;
  19533. var path = new Array();
  19534. ;
  19535. for (i = 0; i <= tessellation; i++) {
  19536. var path = [];
  19537. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  19538. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  19539. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  19540. }
  19541. for (p = 0; p < shape.length; p++) {
  19542. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  19543. path.push(rotated);
  19544. }
  19545. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  19546. 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));
  19547. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  19548. }
  19549. paths.push(path);
  19550. }
  19551. // lathe ribbon
  19552. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable }, scene);
  19553. return lathe;
  19554. };
  19555. /**
  19556. * Creates a plane mesh.
  19557. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  19558. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  19559. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  19560. * The parameter `sourcePlane` is a `Plane` instance. It builds a mesh plane from a Math plane.
  19561. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19562. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19563. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19564. */
  19565. MeshBuilder.CreatePlane = function (name, options, scene) {
  19566. var plane = new BABYLON.Mesh(name, scene);
  19567. var vertexData = BABYLON.VertexData.CreatePlane(options);
  19568. vertexData.applyToMesh(plane, options.updatable);
  19569. if (options.sourcePlane) {
  19570. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  19571. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  19572. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  19573. plane.rotate(vectorProduct, product);
  19574. }
  19575. return plane;
  19576. };
  19577. /**
  19578. * Creates a ground mesh.
  19579. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  19580. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  19581. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  19582. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19583. */
  19584. MeshBuilder.CreateGround = function (name, options, scene) {
  19585. var ground = new BABYLON.GroundMesh(name, scene);
  19586. ground._setReady(false);
  19587. ground._subdivisions = options.subdivisions || 1;
  19588. ground._width = options.width || 1;
  19589. ground._height = options.height || 1;
  19590. ground._maxX = ground._width / 2;
  19591. ground._maxZ = ground._height / 2;
  19592. ground._minX = -ground._maxX;
  19593. ground._minZ = -ground._maxZ;
  19594. var vertexData = BABYLON.VertexData.CreateGround(options);
  19595. vertexData.applyToMesh(ground, options.updatable);
  19596. ground._setReady(true);
  19597. return ground;
  19598. };
  19599. /**
  19600. * Creates a tiled ground mesh.
  19601. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  19602. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  19603. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  19604. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  19605. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  19606. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  19607. * numbers of subdivisions on the ground width and height of each tile.
  19608. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19609. */
  19610. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  19611. var tiledGround = new BABYLON.Mesh(name, scene);
  19612. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  19613. vertexData.applyToMesh(tiledGround, options.updatable);
  19614. return tiledGround;
  19615. };
  19616. /**
  19617. * Creates a ground mesh from a height map.
  19618. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  19619. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  19620. * The parameter `url` sets the URL of the height map image resource.
  19621. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  19622. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  19623. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  19624. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  19625. * 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).
  19626. * This function is passed the newly built mesh : ```function(mesh) { // do things
  19627. * return; }```
  19628. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19629. */
  19630. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  19631. var width = options.width || 10;
  19632. var height = options.height || 10;
  19633. var subdivisions = options.subdivisions || 1;
  19634. var minHeight = options.minHeight;
  19635. var maxHeight = options.maxHeight || 10;
  19636. var updatable = options.updatable;
  19637. var onReady = options.onReady;
  19638. var ground = new BABYLON.GroundMesh(name, scene);
  19639. ground._subdivisions = subdivisions;
  19640. ground._width = width;
  19641. ground._height = height;
  19642. ground._maxX = ground._width / 2;
  19643. ground._maxZ = ground._height / 2;
  19644. ground._minX = -ground._maxX;
  19645. ground._minZ = -ground._maxZ;
  19646. ground._setReady(false);
  19647. var onload = function (img) {
  19648. // Getting height map data
  19649. var canvas = document.createElement("canvas");
  19650. var context = canvas.getContext("2d");
  19651. var bufferWidth = img.width;
  19652. var bufferHeight = img.height;
  19653. canvas.width = bufferWidth;
  19654. canvas.height = bufferHeight;
  19655. context.drawImage(img, 0, 0);
  19656. // Create VertexData from map data
  19657. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  19658. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  19659. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  19660. width: width, height: height,
  19661. subdivisions: subdivisions,
  19662. minHeight: minHeight, maxHeight: maxHeight,
  19663. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  19664. });
  19665. vertexData.applyToMesh(ground, updatable);
  19666. ground._setReady(true);
  19667. //execute ready callback, if set
  19668. if (onReady) {
  19669. onReady(ground);
  19670. }
  19671. };
  19672. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  19673. return ground;
  19674. };
  19675. /**
  19676. * Creates a tube mesh.
  19677. * 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.
  19678. *
  19679. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  19680. * The parameter `path` is a required array of successive `Vector3`. It is the curve used as the axis of the tube.
  19681. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  19682. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  19683. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  19684. * 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.
  19685. * It must return a radius value (positive float) :
  19686. * ```var radiusFunction = function(i, distance) {
  19687. * // do things
  19688. * return radius; }```
  19689. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  19690. * 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
  19691. * 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
  19692. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19693. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19694. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19695. */
  19696. MeshBuilder.CreateTube = function (name, options, scene) {
  19697. var path = options.path;
  19698. var radius = options.radius || 1;
  19699. var tessellation = options.tessellation || 64;
  19700. var radiusFunction = options.radiusFunction;
  19701. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  19702. var updatable = options.updatable;
  19703. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  19704. var instance = options.instance;
  19705. options.arc = (options.arc <= 0 || options.arc > 1) ? 1 : options.arc || 1;
  19706. // tube geometry
  19707. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  19708. var tangents = path3D.getTangents();
  19709. var normals = path3D.getNormals();
  19710. var distances = path3D.getDistances();
  19711. var pi2 = Math.PI * 2;
  19712. var step = pi2 / tessellation * arc;
  19713. var returnRadius = function () { return radius; };
  19714. var radiusFunctionFinal = radiusFunction || returnRadius;
  19715. var circlePath;
  19716. var rad;
  19717. var normal;
  19718. var rotated;
  19719. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  19720. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  19721. for (var i = 0; i < path.length; i++) {
  19722. rad = radiusFunctionFinal(i, distances[i]); // current radius
  19723. circlePath = Array(); // current circle array
  19724. normal = normals[i]; // current normal
  19725. for (var t = 0; t < tessellation; t++) {
  19726. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  19727. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  19728. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  19729. rotated.scaleInPlace(rad).addInPlace(path[i]);
  19730. circlePath[t] = rotated;
  19731. }
  19732. circlePaths[index] = circlePath;
  19733. index++;
  19734. }
  19735. // cap
  19736. var capPath = function (nbPoints, pathIndex) {
  19737. var pointCap = Array();
  19738. for (var i = 0; i < nbPoints; i++) {
  19739. pointCap.push(path[pathIndex]);
  19740. }
  19741. return pointCap;
  19742. };
  19743. switch (cap) {
  19744. case BABYLON.Mesh.NO_CAP:
  19745. break;
  19746. case BABYLON.Mesh.CAP_START:
  19747. circlePaths[0] = capPath(tessellation, 0);
  19748. circlePaths[1] = circlePaths[2].slice(0);
  19749. break;
  19750. case BABYLON.Mesh.CAP_END:
  19751. circlePaths[index] = circlePaths[index - 1].slice(0);
  19752. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  19753. break;
  19754. case BABYLON.Mesh.CAP_ALL:
  19755. circlePaths[0] = capPath(tessellation, 0);
  19756. circlePaths[1] = circlePaths[2].slice(0);
  19757. circlePaths[index] = circlePaths[index - 1].slice(0);
  19758. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  19759. break;
  19760. default:
  19761. break;
  19762. }
  19763. return circlePaths;
  19764. };
  19765. var path3D;
  19766. var pathArray;
  19767. if (instance) {
  19768. var arc = options.arc || instance.arc;
  19769. path3D = (instance.path3D).update(path);
  19770. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  19771. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  19772. instance.path3D = path3D;
  19773. instance.pathArray = pathArray;
  19774. instance.arc = arc;
  19775. return instance;
  19776. }
  19777. // tube creation
  19778. path3D = new BABYLON.Path3D(path);
  19779. var newPathArray = new Array();
  19780. cap = (cap < 0 || cap > 3) ? 0 : cap;
  19781. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  19782. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation }, scene);
  19783. tube.pathArray = pathArray;
  19784. tube.path3D = path3D;
  19785. tube.tessellation = tessellation;
  19786. tube.cap = cap;
  19787. tube.arc = options.arc;
  19788. return tube;
  19789. };
  19790. /**
  19791. * Creates a polyhedron mesh.
  19792. *
  19793. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  19794. * 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
  19795. * to choose the wanted type.
  19796. * The parameter `size` (positive float, default 1) sets the polygon size.
  19797. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  19798. * 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`.
  19799. * 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
  19800. * 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)`).
  19801. * 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
  19802. * 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.
  19803. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  19804. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  19805. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  19806. */
  19807. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  19808. var polyhedron = new BABYLON.Mesh(name, scene);
  19809. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  19810. vertexData.applyToMesh(polyhedron, options.updatable);
  19811. return polyhedron;
  19812. };
  19813. /**
  19814. * Creates a decal mesh.
  19815. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  19816. * 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.
  19817. * The parameter `position` (`Vector3`, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  19818. * The parameter `normal` (`Vector3`, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  19819. * The parameter `size` (`Vector3`, default `(1, 1, 1)`) sets the decal scaling.
  19820. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  19821. */
  19822. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  19823. var indices = sourceMesh.getIndices();
  19824. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19825. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19826. var position = options.position || BABYLON.Vector3.Zero();
  19827. var normal = options.normal || BABYLON.Vector3.Up();
  19828. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  19829. var angle = options.angle || 0;
  19830. // Getting correct rotation
  19831. if (!normal) {
  19832. var target = new BABYLON.Vector3(0, 0, 1);
  19833. var camera = sourceMesh.getScene().activeCamera;
  19834. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  19835. normal = camera.globalPosition.subtract(cameraWorldTarget);
  19836. }
  19837. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  19838. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  19839. var pitch = Math.atan2(normal.y, len);
  19840. // Matrix
  19841. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  19842. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  19843. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  19844. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  19845. var vertexData = new BABYLON.VertexData();
  19846. vertexData.indices = [];
  19847. vertexData.positions = [];
  19848. vertexData.normals = [];
  19849. vertexData.uvs = [];
  19850. var currentVertexDataIndex = 0;
  19851. var extractDecalVector3 = function (indexId) {
  19852. var vertexId = indices[indexId];
  19853. var result = new BABYLON.PositionNormalVertex();
  19854. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  19855. // Send vector to decal local world
  19856. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  19857. // Get normal
  19858. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  19859. return result;
  19860. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  19861. var clip = function (vertices, axis) {
  19862. if (vertices.length === 0) {
  19863. return vertices;
  19864. }
  19865. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  19866. var clipVertices = function (v0, v1) {
  19867. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  19868. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  19869. };
  19870. var result = new Array();
  19871. for (var index = 0; index < vertices.length; index += 3) {
  19872. var v1Out;
  19873. var v2Out;
  19874. var v3Out;
  19875. var total = 0;
  19876. var nV1, nV2, nV3, nV4;
  19877. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  19878. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  19879. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  19880. v1Out = d1 > 0;
  19881. v2Out = d2 > 0;
  19882. v3Out = d3 > 0;
  19883. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  19884. switch (total) {
  19885. case 0:
  19886. result.push(vertices[index]);
  19887. result.push(vertices[index + 1]);
  19888. result.push(vertices[index + 2]);
  19889. break;
  19890. case 1:
  19891. if (v1Out) {
  19892. nV1 = vertices[index + 1];
  19893. nV2 = vertices[index + 2];
  19894. nV3 = clipVertices(vertices[index], nV1);
  19895. nV4 = clipVertices(vertices[index], nV2);
  19896. }
  19897. if (v2Out) {
  19898. nV1 = vertices[index];
  19899. nV2 = vertices[index + 2];
  19900. nV3 = clipVertices(vertices[index + 1], nV1);
  19901. nV4 = clipVertices(vertices[index + 1], nV2);
  19902. result.push(nV3);
  19903. result.push(nV2.clone());
  19904. result.push(nV1.clone());
  19905. result.push(nV2.clone());
  19906. result.push(nV3.clone());
  19907. result.push(nV4);
  19908. break;
  19909. }
  19910. if (v3Out) {
  19911. nV1 = vertices[index];
  19912. nV2 = vertices[index + 1];
  19913. nV3 = clipVertices(vertices[index + 2], nV1);
  19914. nV4 = clipVertices(vertices[index + 2], nV2);
  19915. }
  19916. result.push(nV1.clone());
  19917. result.push(nV2.clone());
  19918. result.push(nV3);
  19919. result.push(nV4);
  19920. result.push(nV3.clone());
  19921. result.push(nV2.clone());
  19922. break;
  19923. case 2:
  19924. if (!v1Out) {
  19925. nV1 = vertices[index].clone();
  19926. nV2 = clipVertices(nV1, vertices[index + 1]);
  19927. nV3 = clipVertices(nV1, vertices[index + 2]);
  19928. result.push(nV1);
  19929. result.push(nV2);
  19930. result.push(nV3);
  19931. }
  19932. if (!v2Out) {
  19933. nV1 = vertices[index + 1].clone();
  19934. nV2 = clipVertices(nV1, vertices[index + 2]);
  19935. nV3 = clipVertices(nV1, vertices[index]);
  19936. result.push(nV1);
  19937. result.push(nV2);
  19938. result.push(nV3);
  19939. }
  19940. if (!v3Out) {
  19941. nV1 = vertices[index + 2].clone();
  19942. nV2 = clipVertices(nV1, vertices[index]);
  19943. nV3 = clipVertices(nV1, vertices[index + 1]);
  19944. result.push(nV1);
  19945. result.push(nV2);
  19946. result.push(nV3);
  19947. }
  19948. break;
  19949. case 3:
  19950. break;
  19951. }
  19952. }
  19953. return result;
  19954. };
  19955. for (var index = 0; index < indices.length; index += 3) {
  19956. var faceVertices = new Array();
  19957. faceVertices.push(extractDecalVector3(index));
  19958. faceVertices.push(extractDecalVector3(index + 1));
  19959. faceVertices.push(extractDecalVector3(index + 2));
  19960. // Clip
  19961. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  19962. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  19963. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  19964. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  19965. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  19966. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  19967. if (faceVertices.length === 0) {
  19968. continue;
  19969. }
  19970. // Add UVs and get back to world
  19971. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  19972. var vertex = faceVertices[vIndex];
  19973. //TODO check for Int32Array
  19974. vertexData.indices.push(currentVertexDataIndex);
  19975. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  19976. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  19977. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  19978. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  19979. currentVertexDataIndex++;
  19980. }
  19981. }
  19982. // Return mesh
  19983. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  19984. vertexData.applyToMesh(decal);
  19985. decal.position = position.clone();
  19986. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  19987. return decal;
  19988. };
  19989. // Privates
  19990. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  19991. // extrusion geometry
  19992. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  19993. var tangents = path3D.getTangents();
  19994. var normals = path3D.getNormals();
  19995. var binormals = path3D.getBinormals();
  19996. var distances = path3D.getDistances();
  19997. var angle = 0;
  19998. var returnScale = function () { return scale; };
  19999. var returnRotation = function () { return rotation; };
  20000. var rotate = custom ? rotateFunction : returnRotation;
  20001. var scl = custom ? scaleFunction : returnScale;
  20002. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  20003. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  20004. for (var i = 0; i < curve.length; i++) {
  20005. var shapePath = new Array();
  20006. var angleStep = rotate(i, distances[i]);
  20007. var scaleRatio = scl(i, distances[i]);
  20008. for (var p = 0; p < shape.length; p++) {
  20009. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  20010. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  20011. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  20012. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  20013. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  20014. shapePath[p] = rotated;
  20015. }
  20016. shapePaths[index] = shapePath;
  20017. angle += angleStep;
  20018. index++;
  20019. }
  20020. // cap
  20021. var capPath = function (shapePath) {
  20022. var pointCap = Array();
  20023. var barycenter = BABYLON.Vector3.Zero();
  20024. var i;
  20025. for (i = 0; i < shapePath.length; i++) {
  20026. barycenter.addInPlace(shapePath[i]);
  20027. }
  20028. barycenter.scaleInPlace(1 / shapePath.length);
  20029. for (i = 0; i < shapePath.length; i++) {
  20030. pointCap.push(barycenter);
  20031. }
  20032. return pointCap;
  20033. };
  20034. switch (cap) {
  20035. case BABYLON.Mesh.NO_CAP:
  20036. break;
  20037. case BABYLON.Mesh.CAP_START:
  20038. shapePaths[0] = capPath(shapePaths[2]);
  20039. shapePaths[1] = shapePaths[2].slice(0);
  20040. break;
  20041. case BABYLON.Mesh.CAP_END:
  20042. shapePaths[index] = shapePaths[index - 1];
  20043. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  20044. break;
  20045. case BABYLON.Mesh.CAP_ALL:
  20046. shapePaths[0] = capPath(shapePaths[2]);
  20047. shapePaths[1] = shapePaths[2].slice(0);
  20048. shapePaths[index] = shapePaths[index - 1];
  20049. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  20050. break;
  20051. default:
  20052. break;
  20053. }
  20054. return shapePaths;
  20055. };
  20056. var path3D;
  20057. var pathArray;
  20058. if (instance) {
  20059. path3D = (instance.path3D).update(curve);
  20060. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  20061. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  20062. return instance;
  20063. }
  20064. // extruded shape creation
  20065. path3D = new BABYLON.Path3D(curve);
  20066. var newShapePaths = new Array();
  20067. cap = (cap < 0 || cap > 3) ? 0 : cap;
  20068. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  20069. var extrudedGeneric = BABYLON.Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  20070. extrudedGeneric.pathArray = pathArray;
  20071. extrudedGeneric.path3D = path3D;
  20072. extrudedGeneric.cap = cap;
  20073. return extrudedGeneric;
  20074. };
  20075. return MeshBuilder;
  20076. })();
  20077. BABYLON.MeshBuilder = MeshBuilder;
  20078. })(BABYLON || (BABYLON = {}));
  20079. var BABYLON;
  20080. (function (BABYLON) {
  20081. var BaseTexture = (function () {
  20082. function BaseTexture(scene) {
  20083. this.hasAlpha = false;
  20084. this.getAlphaFromRGB = false;
  20085. this.level = 1;
  20086. this.coordinatesIndex = 0;
  20087. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20088. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20089. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20090. this.anisotropicFilteringLevel = 4;
  20091. this.isCube = false;
  20092. this.isRenderTarget = false;
  20093. this.animations = new Array();
  20094. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20095. this._scene = scene;
  20096. this._scene.textures.push(this);
  20097. }
  20098. BaseTexture.prototype.getScene = function () {
  20099. return this._scene;
  20100. };
  20101. BaseTexture.prototype.getTextureMatrix = function () {
  20102. return null;
  20103. };
  20104. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20105. return null;
  20106. };
  20107. BaseTexture.prototype.getInternalTexture = function () {
  20108. return this._texture;
  20109. };
  20110. BaseTexture.prototype.isReady = function () {
  20111. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20112. return true;
  20113. }
  20114. if (this._texture) {
  20115. return this._texture.isReady;
  20116. }
  20117. return false;
  20118. };
  20119. BaseTexture.prototype.getSize = function () {
  20120. if (this._texture._width) {
  20121. return { width: this._texture._width, height: this._texture._height };
  20122. }
  20123. if (this._texture._size) {
  20124. return { width: this._texture._size, height: this._texture._size };
  20125. }
  20126. return { width: 0, height: 0 };
  20127. };
  20128. BaseTexture.prototype.getBaseSize = function () {
  20129. if (!this.isReady() || !this._texture)
  20130. return { width: 0, height: 0 };
  20131. if (this._texture._size) {
  20132. return { width: this._texture._size, height: this._texture._size };
  20133. }
  20134. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  20135. };
  20136. BaseTexture.prototype.scale = function (ratio) {
  20137. };
  20138. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20139. get: function () {
  20140. return false;
  20141. },
  20142. enumerable: true,
  20143. configurable: true
  20144. });
  20145. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  20146. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20147. for (var index = 0; index < texturesCache.length; index++) {
  20148. var texturesCacheEntry = texturesCache[index];
  20149. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  20150. texturesCache.splice(index, 1);
  20151. return;
  20152. }
  20153. }
  20154. };
  20155. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20156. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20157. for (var index = 0; index < texturesCache.length; index++) {
  20158. var texturesCacheEntry = texturesCache[index];
  20159. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  20160. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20161. texturesCacheEntry.references++;
  20162. return texturesCacheEntry;
  20163. }
  20164. }
  20165. }
  20166. return null;
  20167. };
  20168. BaseTexture.prototype.delayLoad = function () {
  20169. };
  20170. BaseTexture.prototype.clone = function () {
  20171. return null;
  20172. };
  20173. BaseTexture.prototype.releaseInternalTexture = function () {
  20174. if (this._texture) {
  20175. this._scene.getEngine().releaseInternalTexture(this._texture);
  20176. delete this._texture;
  20177. }
  20178. };
  20179. BaseTexture.prototype.dispose = function () {
  20180. // Animations
  20181. this.getScene().stopAnimation(this);
  20182. // Remove from scene
  20183. var index = this._scene.textures.indexOf(this);
  20184. if (index >= 0) {
  20185. this._scene.textures.splice(index, 1);
  20186. }
  20187. if (this._texture === undefined) {
  20188. return;
  20189. }
  20190. // Release
  20191. this.releaseInternalTexture();
  20192. // Callback
  20193. if (this.onDispose) {
  20194. this.onDispose();
  20195. }
  20196. };
  20197. BaseTexture.prototype.serialize = function () {
  20198. if (!this.name) {
  20199. return null;
  20200. }
  20201. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20202. // Animations
  20203. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20204. return serializationObject;
  20205. };
  20206. __decorate([
  20207. BABYLON.serialize()
  20208. ], BaseTexture.prototype, "name", void 0);
  20209. __decorate([
  20210. BABYLON.serialize()
  20211. ], BaseTexture.prototype, "hasAlpha", void 0);
  20212. __decorate([
  20213. BABYLON.serialize()
  20214. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20215. __decorate([
  20216. BABYLON.serialize()
  20217. ], BaseTexture.prototype, "level", void 0);
  20218. __decorate([
  20219. BABYLON.serialize()
  20220. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20221. __decorate([
  20222. BABYLON.serialize()
  20223. ], BaseTexture.prototype, "coordinatesMode", void 0);
  20224. __decorate([
  20225. BABYLON.serialize()
  20226. ], BaseTexture.prototype, "wrapU", void 0);
  20227. __decorate([
  20228. BABYLON.serialize()
  20229. ], BaseTexture.prototype, "wrapV", void 0);
  20230. __decorate([
  20231. BABYLON.serialize()
  20232. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20233. __decorate([
  20234. BABYLON.serialize()
  20235. ], BaseTexture.prototype, "isCube", void 0);
  20236. __decorate([
  20237. BABYLON.serialize()
  20238. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20239. return BaseTexture;
  20240. })();
  20241. BABYLON.BaseTexture = BaseTexture;
  20242. })(BABYLON || (BABYLON = {}));
  20243. var BABYLON;
  20244. (function (BABYLON) {
  20245. var Texture = (function (_super) {
  20246. __extends(Texture, _super);
  20247. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  20248. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20249. if (onLoad === void 0) { onLoad = null; }
  20250. if (onError === void 0) { onError = null; }
  20251. if (buffer === void 0) { buffer = null; }
  20252. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20253. _super.call(this, scene);
  20254. this.uOffset = 0;
  20255. this.vOffset = 0;
  20256. this.uScale = 1.0;
  20257. this.vScale = 1.0;
  20258. this.uAng = 0;
  20259. this.vAng = 0;
  20260. this.wAng = 0;
  20261. this.name = url;
  20262. this.url = url;
  20263. this._noMipmap = noMipmap;
  20264. this._invertY = invertY;
  20265. this._samplingMode = samplingMode;
  20266. this._buffer = buffer;
  20267. this._deleteBuffer = deleteBuffer;
  20268. if (!url) {
  20269. return;
  20270. }
  20271. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  20272. if (!this._texture) {
  20273. if (!scene.useDelayedTextureLoading) {
  20274. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  20275. if (deleteBuffer) {
  20276. delete this._buffer;
  20277. }
  20278. }
  20279. else {
  20280. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20281. this._delayedOnLoad = onLoad;
  20282. this._delayedOnError = onError;
  20283. }
  20284. }
  20285. else {
  20286. BABYLON.Tools.SetImmediate(function () {
  20287. if (onLoad) {
  20288. onLoad();
  20289. }
  20290. });
  20291. }
  20292. }
  20293. Texture.prototype.delayLoad = function () {
  20294. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20295. return;
  20296. }
  20297. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20298. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  20299. if (!this._texture) {
  20300. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  20301. if (this._deleteBuffer) {
  20302. delete this._buffer;
  20303. }
  20304. }
  20305. };
  20306. Texture.prototype.updateSamplingMode = function (samplingMode) {
  20307. if (!this._texture) {
  20308. return;
  20309. }
  20310. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  20311. };
  20312. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  20313. x *= this.uScale;
  20314. y *= this.vScale;
  20315. x -= 0.5 * this.uScale;
  20316. y -= 0.5 * this.vScale;
  20317. z -= 0.5;
  20318. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  20319. t.x += 0.5 * this.uScale + this.uOffset;
  20320. t.y += 0.5 * this.vScale + this.vOffset;
  20321. t.z += 0.5;
  20322. };
  20323. Texture.prototype.getTextureMatrix = function () {
  20324. if (this.uOffset === this._cachedUOffset &&
  20325. this.vOffset === this._cachedVOffset &&
  20326. this.uScale === this._cachedUScale &&
  20327. this.vScale === this._cachedVScale &&
  20328. this.uAng === this._cachedUAng &&
  20329. this.vAng === this._cachedVAng &&
  20330. this.wAng === this._cachedWAng) {
  20331. return this._cachedTextureMatrix;
  20332. }
  20333. this._cachedUOffset = this.uOffset;
  20334. this._cachedVOffset = this.vOffset;
  20335. this._cachedUScale = this.uScale;
  20336. this._cachedVScale = this.vScale;
  20337. this._cachedUAng = this.uAng;
  20338. this._cachedVAng = this.vAng;
  20339. this._cachedWAng = this.wAng;
  20340. if (!this._cachedTextureMatrix) {
  20341. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20342. this._rowGenerationMatrix = new BABYLON.Matrix();
  20343. this._t0 = BABYLON.Vector3.Zero();
  20344. this._t1 = BABYLON.Vector3.Zero();
  20345. this._t2 = BABYLON.Vector3.Zero();
  20346. }
  20347. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  20348. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  20349. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  20350. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  20351. this._t1.subtractInPlace(this._t0);
  20352. this._t2.subtractInPlace(this._t0);
  20353. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20354. this._cachedTextureMatrix.m[0] = this._t1.x;
  20355. this._cachedTextureMatrix.m[1] = this._t1.y;
  20356. this._cachedTextureMatrix.m[2] = this._t1.z;
  20357. this._cachedTextureMatrix.m[4] = this._t2.x;
  20358. this._cachedTextureMatrix.m[5] = this._t2.y;
  20359. this._cachedTextureMatrix.m[6] = this._t2.z;
  20360. this._cachedTextureMatrix.m[8] = this._t0.x;
  20361. this._cachedTextureMatrix.m[9] = this._t0.y;
  20362. this._cachedTextureMatrix.m[10] = this._t0.z;
  20363. return this._cachedTextureMatrix;
  20364. };
  20365. Texture.prototype.getReflectionTextureMatrix = function () {
  20366. if (this.uOffset === this._cachedUOffset &&
  20367. this.vOffset === this._cachedVOffset &&
  20368. this.uScale === this._cachedUScale &&
  20369. this.vScale === this._cachedVScale &&
  20370. this.coordinatesMode === this._cachedCoordinatesMode) {
  20371. return this._cachedTextureMatrix;
  20372. }
  20373. if (!this._cachedTextureMatrix) {
  20374. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20375. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  20376. }
  20377. this._cachedCoordinatesMode = this.coordinatesMode;
  20378. switch (this.coordinatesMode) {
  20379. case Texture.PLANAR_MODE:
  20380. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20381. this._cachedTextureMatrix[0] = this.uScale;
  20382. this._cachedTextureMatrix[5] = this.vScale;
  20383. this._cachedTextureMatrix[12] = this.uOffset;
  20384. this._cachedTextureMatrix[13] = this.vOffset;
  20385. break;
  20386. case Texture.PROJECTION_MODE:
  20387. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  20388. this._projectionModeMatrix.m[0] = 0.5;
  20389. this._projectionModeMatrix.m[5] = -0.5;
  20390. this._projectionModeMatrix.m[10] = 0.0;
  20391. this._projectionModeMatrix.m[12] = 0.5;
  20392. this._projectionModeMatrix.m[13] = 0.5;
  20393. this._projectionModeMatrix.m[14] = 1.0;
  20394. this._projectionModeMatrix.m[15] = 1.0;
  20395. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  20396. break;
  20397. default:
  20398. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20399. break;
  20400. }
  20401. return this._cachedTextureMatrix;
  20402. };
  20403. Texture.prototype.clone = function () {
  20404. var _this = this;
  20405. return BABYLON.SerializationHelper.Clone(function () {
  20406. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  20407. }, this);
  20408. };
  20409. // Statics
  20410. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  20411. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20412. if (onLoad === void 0) { onLoad = null; }
  20413. if (onError === void 0) { onError = null; }
  20414. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  20415. };
  20416. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  20417. if (parsedTexture.isCube) {
  20418. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  20419. }
  20420. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  20421. return null;
  20422. }
  20423. var texture = BABYLON.SerializationHelper.Parse(function () {
  20424. if (parsedTexture.mirrorPlane) {
  20425. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20426. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  20427. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  20428. return mirrorTexture;
  20429. }
  20430. else if (parsedTexture.isRenderTarget) {
  20431. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20432. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  20433. return renderTargetTexture;
  20434. }
  20435. else {
  20436. var texture;
  20437. if (parsedTexture.base64String) {
  20438. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  20439. }
  20440. else {
  20441. texture = new Texture(rootUrl + parsedTexture.name, scene);
  20442. }
  20443. return texture;
  20444. }
  20445. }, parsedTexture, scene);
  20446. // Animations
  20447. if (parsedTexture.animations) {
  20448. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20449. var parsedAnimation = parsedTexture.animations[animationIndex];
  20450. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20451. }
  20452. }
  20453. return texture;
  20454. };
  20455. // Constants
  20456. Texture.NEAREST_SAMPLINGMODE = 1;
  20457. Texture.BILINEAR_SAMPLINGMODE = 2;
  20458. Texture.TRILINEAR_SAMPLINGMODE = 3;
  20459. Texture.EXPLICIT_MODE = 0;
  20460. Texture.SPHERICAL_MODE = 1;
  20461. Texture.PLANAR_MODE = 2;
  20462. Texture.CUBIC_MODE = 3;
  20463. Texture.PROJECTION_MODE = 4;
  20464. Texture.SKYBOX_MODE = 5;
  20465. Texture.INVCUBIC_MODE = 6;
  20466. Texture.EQUIRECTANGULAR_MODE = 7;
  20467. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  20468. Texture.CLAMP_ADDRESSMODE = 0;
  20469. Texture.WRAP_ADDRESSMODE = 1;
  20470. Texture.MIRROR_ADDRESSMODE = 2;
  20471. __decorate([
  20472. BABYLON.serialize()
  20473. ], Texture.prototype, "url", void 0);
  20474. __decorate([
  20475. BABYLON.serialize()
  20476. ], Texture.prototype, "uOffset", void 0);
  20477. __decorate([
  20478. BABYLON.serialize()
  20479. ], Texture.prototype, "vOffset", void 0);
  20480. __decorate([
  20481. BABYLON.serialize()
  20482. ], Texture.prototype, "uScale", void 0);
  20483. __decorate([
  20484. BABYLON.serialize()
  20485. ], Texture.prototype, "vScale", void 0);
  20486. __decorate([
  20487. BABYLON.serialize()
  20488. ], Texture.prototype, "uAng", void 0);
  20489. __decorate([
  20490. BABYLON.serialize()
  20491. ], Texture.prototype, "vAng", void 0);
  20492. __decorate([
  20493. BABYLON.serialize()
  20494. ], Texture.prototype, "wAng", void 0);
  20495. return Texture;
  20496. })(BABYLON.BaseTexture);
  20497. BABYLON.Texture = Texture;
  20498. })(BABYLON || (BABYLON = {}));
  20499. var BABYLON;
  20500. (function (BABYLON) {
  20501. var CubeTexture = (function (_super) {
  20502. __extends(CubeTexture, _super);
  20503. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  20504. _super.call(this, scene);
  20505. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  20506. this.name = rootUrl;
  20507. this.url = rootUrl;
  20508. this._noMipmap = noMipmap;
  20509. this.hasAlpha = false;
  20510. if (!rootUrl && !files) {
  20511. return;
  20512. }
  20513. this._texture = this._getFromCache(rootUrl, noMipmap);
  20514. if (!files) {
  20515. if (!extensions) {
  20516. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  20517. }
  20518. files = [];
  20519. for (var index = 0; index < extensions.length; index++) {
  20520. files.push(rootUrl + extensions[index]);
  20521. }
  20522. this._extensions = extensions;
  20523. }
  20524. this._files = files;
  20525. if (!this._texture) {
  20526. if (!scene.useDelayedTextureLoading) {
  20527. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  20528. }
  20529. else {
  20530. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20531. }
  20532. }
  20533. this.isCube = true;
  20534. this._textureMatrix = BABYLON.Matrix.Identity();
  20535. }
  20536. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  20537. return new CubeTexture("", scene, null, noMipmap, files);
  20538. };
  20539. // Methods
  20540. CubeTexture.prototype.delayLoad = function () {
  20541. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20542. return;
  20543. }
  20544. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20545. this._texture = this._getFromCache(this.url, this._noMipmap);
  20546. if (!this._texture) {
  20547. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  20548. }
  20549. };
  20550. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  20551. return this._textureMatrix;
  20552. };
  20553. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  20554. var texture = BABYLON.SerializationHelper.Parse(function () {
  20555. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  20556. }, parsedTexture, scene);
  20557. // Animations
  20558. if (parsedTexture.animations) {
  20559. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20560. var parsedAnimation = parsedTexture.animations[animationIndex];
  20561. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20562. }
  20563. }
  20564. return texture;
  20565. };
  20566. CubeTexture.prototype.clone = function () {
  20567. var _this = this;
  20568. return BABYLON.SerializationHelper.Clone(function () {
  20569. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  20570. }, this);
  20571. };
  20572. return CubeTexture;
  20573. })(BABYLON.BaseTexture);
  20574. BABYLON.CubeTexture = CubeTexture;
  20575. })(BABYLON || (BABYLON = {}));
  20576. var BABYLON;
  20577. (function (BABYLON) {
  20578. var RenderTargetTexture = (function (_super) {
  20579. __extends(RenderTargetTexture, _super);
  20580. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube) {
  20581. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  20582. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  20583. if (isCube === void 0) { isCube = false; }
  20584. _super.call(this, null, scene, !generateMipMaps);
  20585. this.isCube = isCube;
  20586. this.renderList = new Array();
  20587. this.renderParticles = true;
  20588. this.renderSprites = false;
  20589. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  20590. this._currentRefreshId = -1;
  20591. this._refreshRate = 1;
  20592. this.name = name;
  20593. this.isRenderTarget = true;
  20594. this._size = size;
  20595. this._generateMipMaps = generateMipMaps;
  20596. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  20597. if (isCube) {
  20598. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  20599. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  20600. this._textureMatrix = BABYLON.Matrix.Identity();
  20601. }
  20602. else {
  20603. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  20604. }
  20605. // Rendering groups
  20606. this._renderingManager = new BABYLON.RenderingManager(scene);
  20607. }
  20608. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  20609. get: function () {
  20610. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  20611. },
  20612. enumerable: true,
  20613. configurable: true
  20614. });
  20615. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  20616. get: function () {
  20617. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  20618. },
  20619. enumerable: true,
  20620. configurable: true
  20621. });
  20622. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  20623. get: function () {
  20624. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  20625. },
  20626. enumerable: true,
  20627. configurable: true
  20628. });
  20629. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  20630. this._currentRefreshId = -1;
  20631. };
  20632. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  20633. get: function () {
  20634. return this._refreshRate;
  20635. },
  20636. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  20637. set: function (value) {
  20638. this._refreshRate = value;
  20639. this.resetRefreshCounter();
  20640. },
  20641. enumerable: true,
  20642. configurable: true
  20643. });
  20644. RenderTargetTexture.prototype._shouldRender = function () {
  20645. if (this._currentRefreshId === -1) {
  20646. this._currentRefreshId = 1;
  20647. return true;
  20648. }
  20649. if (this.refreshRate === this._currentRefreshId) {
  20650. this._currentRefreshId = 1;
  20651. return true;
  20652. }
  20653. this._currentRefreshId++;
  20654. return false;
  20655. };
  20656. RenderTargetTexture.prototype.isReady = function () {
  20657. if (!this.getScene().renderTargetsEnabled) {
  20658. return false;
  20659. }
  20660. return _super.prototype.isReady.call(this);
  20661. };
  20662. RenderTargetTexture.prototype.getRenderSize = function () {
  20663. return this._size;
  20664. };
  20665. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  20666. get: function () {
  20667. return true;
  20668. },
  20669. enumerable: true,
  20670. configurable: true
  20671. });
  20672. RenderTargetTexture.prototype.scale = function (ratio) {
  20673. var newSize = this._size * ratio;
  20674. this.resize(newSize, this._generateMipMaps);
  20675. };
  20676. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  20677. if (this.isCube) {
  20678. return this._textureMatrix;
  20679. }
  20680. return _super.prototype.getReflectionTextureMatrix.call(this);
  20681. };
  20682. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  20683. this.releaseInternalTexture();
  20684. if (this.isCube) {
  20685. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  20686. }
  20687. else {
  20688. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  20689. }
  20690. };
  20691. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  20692. var scene = this.getScene();
  20693. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  20694. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  20695. }
  20696. if (this._waitingRenderList) {
  20697. this.renderList = [];
  20698. for (var index = 0; index < this._waitingRenderList.length; index++) {
  20699. var id = this._waitingRenderList[index];
  20700. this.renderList.push(scene.getMeshByID(id));
  20701. }
  20702. delete this._waitingRenderList;
  20703. }
  20704. if (this.renderList && this.renderList.length === 0) {
  20705. return;
  20706. }
  20707. // Prepare renderingManager
  20708. this._renderingManager.reset();
  20709. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  20710. var sceneRenderId = scene.getRenderId();
  20711. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  20712. var mesh = currentRenderList[meshIndex];
  20713. if (mesh) {
  20714. if (!mesh.isReady()) {
  20715. // Reset _currentRefreshId
  20716. this.resetRefreshCounter();
  20717. continue;
  20718. }
  20719. mesh._preActivateForIntermediateRendering(sceneRenderId);
  20720. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  20721. mesh._activate(sceneRenderId);
  20722. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  20723. var subMesh = mesh.subMeshes[subIndex];
  20724. scene._activeIndices += subMesh.indexCount;
  20725. this._renderingManager.dispatch(subMesh);
  20726. }
  20727. }
  20728. }
  20729. }
  20730. if (this.isCube) {
  20731. for (var face = 0; face < 6; face++) {
  20732. this.renderToTarget(face, currentRenderList, useCameraPostProcess, dumpForDebug);
  20733. scene.incrementRenderId();
  20734. scene.resetCachedMaterial();
  20735. }
  20736. }
  20737. else {
  20738. this.renderToTarget(0, currentRenderList, useCameraPostProcess, dumpForDebug);
  20739. }
  20740. if (this.onAfterUnbind) {
  20741. this.onAfterUnbind();
  20742. }
  20743. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  20744. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  20745. }
  20746. scene.resetCachedMaterial();
  20747. };
  20748. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, useCameraPostProcess, dumpForDebug) {
  20749. var scene = this.getScene();
  20750. var engine = scene.getEngine();
  20751. // Bind
  20752. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  20753. if (this.isCube) {
  20754. engine.bindFramebuffer(this._texture, faceIndex);
  20755. }
  20756. else {
  20757. engine.bindFramebuffer(this._texture);
  20758. }
  20759. }
  20760. if (this.onBeforeRender) {
  20761. this.onBeforeRender(faceIndex);
  20762. }
  20763. // Clear
  20764. if (this.onClear) {
  20765. this.onClear(engine);
  20766. }
  20767. else {
  20768. engine.clear(scene.clearColor, true, true);
  20769. }
  20770. if (!this._doNotChangeAspectRatio) {
  20771. scene.updateTransformMatrix(true);
  20772. }
  20773. // Render
  20774. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  20775. if (useCameraPostProcess) {
  20776. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  20777. }
  20778. if (!this._doNotChangeAspectRatio) {
  20779. scene.updateTransformMatrix(true);
  20780. }
  20781. if (this.onAfterRender) {
  20782. this.onAfterRender(faceIndex);
  20783. }
  20784. // Dump ?
  20785. if (dumpForDebug) {
  20786. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  20787. }
  20788. // Unbind
  20789. if (!this.isCube || faceIndex === 5) {
  20790. if (this.isCube) {
  20791. if (faceIndex === 5) {
  20792. engine.generateMipMapsForCubemap(this._texture);
  20793. }
  20794. }
  20795. engine.unBindFramebuffer(this._texture, this.isCube);
  20796. }
  20797. };
  20798. RenderTargetTexture.prototype.clone = function () {
  20799. var textureSize = this.getSize();
  20800. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  20801. // Base texture
  20802. newTexture.hasAlpha = this.hasAlpha;
  20803. newTexture.level = this.level;
  20804. // RenderTarget Texture
  20805. newTexture.coordinatesMode = this.coordinatesMode;
  20806. newTexture.renderList = this.renderList.slice(0);
  20807. return newTexture;
  20808. };
  20809. RenderTargetTexture.prototype.serialize = function () {
  20810. if (!this.name) {
  20811. return null;
  20812. }
  20813. var serializationObject = _super.prototype.serialize.call(this);
  20814. serializationObject.renderTargetSize = this.getRenderSize();
  20815. serializationObject.renderList = [];
  20816. for (var index = 0; index < this.renderList.length; index++) {
  20817. serializationObject.renderList.push(this.renderList[index].id);
  20818. }
  20819. return serializationObject;
  20820. };
  20821. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  20822. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  20823. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  20824. return RenderTargetTexture;
  20825. })(BABYLON.Texture);
  20826. BABYLON.RenderTargetTexture = RenderTargetTexture;
  20827. })(BABYLON || (BABYLON = {}));
  20828. var BABYLON;
  20829. (function (BABYLON) {
  20830. var ProceduralTexture = (function (_super) {
  20831. __extends(ProceduralTexture, _super);
  20832. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  20833. if (generateMipMaps === void 0) { generateMipMaps = true; }
  20834. if (isCube === void 0) { isCube = false; }
  20835. _super.call(this, null, scene, !generateMipMaps);
  20836. this.isCube = isCube;
  20837. this.isEnabled = true;
  20838. this._currentRefreshId = -1;
  20839. this._refreshRate = 1;
  20840. this._vertexDeclaration = [2];
  20841. this._vertexStrideSize = 2 * 4;
  20842. this._uniforms = new Array();
  20843. this._samplers = new Array();
  20844. this._textures = new Array();
  20845. this._floats = new Array();
  20846. this._floatsArrays = {};
  20847. this._colors3 = new Array();
  20848. this._colors4 = new Array();
  20849. this._vectors2 = new Array();
  20850. this._vectors3 = new Array();
  20851. this._matrices = new Array();
  20852. this._fallbackTextureUsed = false;
  20853. scene._proceduralTextures.push(this);
  20854. this.name = name;
  20855. this.isRenderTarget = true;
  20856. this._size = size;
  20857. this._generateMipMaps = generateMipMaps;
  20858. this.setFragment(fragment);
  20859. this._fallbackTexture = fallbackTexture;
  20860. if (isCube) {
  20861. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  20862. this.setFloat("face", 0);
  20863. }
  20864. else {
  20865. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  20866. }
  20867. // VBO
  20868. var vertices = [];
  20869. vertices.push(1, 1);
  20870. vertices.push(-1, 1);
  20871. vertices.push(-1, -1);
  20872. vertices.push(1, -1);
  20873. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20874. // Indices
  20875. var indices = [];
  20876. indices.push(0);
  20877. indices.push(1);
  20878. indices.push(2);
  20879. indices.push(0);
  20880. indices.push(2);
  20881. indices.push(3);
  20882. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20883. }
  20884. ProceduralTexture.prototype.reset = function () {
  20885. if (this._effect === undefined) {
  20886. return;
  20887. }
  20888. var engine = this.getScene().getEngine();
  20889. engine._releaseEffect(this._effect);
  20890. };
  20891. ProceduralTexture.prototype.isReady = function () {
  20892. var _this = this;
  20893. var engine = this.getScene().getEngine();
  20894. var shaders;
  20895. if (!this._fragment) {
  20896. return false;
  20897. }
  20898. if (this._fallbackTextureUsed) {
  20899. return true;
  20900. }
  20901. if (this._fragment.fragmentElement !== undefined) {
  20902. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  20903. }
  20904. else {
  20905. shaders = { vertex: "procedural", fragment: this._fragment };
  20906. }
  20907. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  20908. _this.releaseInternalTexture();
  20909. if (_this._fallbackTexture) {
  20910. _this._texture = _this._fallbackTexture._texture;
  20911. _this._texture.references++;
  20912. }
  20913. _this._fallbackTextureUsed = true;
  20914. });
  20915. return this._effect.isReady();
  20916. };
  20917. ProceduralTexture.prototype.resetRefreshCounter = function () {
  20918. this._currentRefreshId = -1;
  20919. };
  20920. ProceduralTexture.prototype.setFragment = function (fragment) {
  20921. this._fragment = fragment;
  20922. };
  20923. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  20924. get: function () {
  20925. return this._refreshRate;
  20926. },
  20927. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  20928. set: function (value) {
  20929. this._refreshRate = value;
  20930. this.resetRefreshCounter();
  20931. },
  20932. enumerable: true,
  20933. configurable: true
  20934. });
  20935. ProceduralTexture.prototype._shouldRender = function () {
  20936. if (!this.isEnabled || !this.isReady() || !this._texture) {
  20937. return false;
  20938. }
  20939. if (this._fallbackTextureUsed) {
  20940. return false;
  20941. }
  20942. if (this._currentRefreshId === -1) {
  20943. this._currentRefreshId = 1;
  20944. return true;
  20945. }
  20946. if (this.refreshRate === this._currentRefreshId) {
  20947. this._currentRefreshId = 1;
  20948. return true;
  20949. }
  20950. this._currentRefreshId++;
  20951. return false;
  20952. };
  20953. ProceduralTexture.prototype.getRenderSize = function () {
  20954. return this._size;
  20955. };
  20956. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  20957. if (this._fallbackTextureUsed) {
  20958. return;
  20959. }
  20960. this.releaseInternalTexture();
  20961. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  20962. };
  20963. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  20964. if (this._uniforms.indexOf(uniformName) === -1) {
  20965. this._uniforms.push(uniformName);
  20966. }
  20967. };
  20968. ProceduralTexture.prototype.setTexture = function (name, texture) {
  20969. if (this._samplers.indexOf(name) === -1) {
  20970. this._samplers.push(name);
  20971. }
  20972. this._textures[name] = texture;
  20973. return this;
  20974. };
  20975. ProceduralTexture.prototype.setFloat = function (name, value) {
  20976. this._checkUniform(name);
  20977. this._floats[name] = value;
  20978. return this;
  20979. };
  20980. ProceduralTexture.prototype.setFloats = function (name, value) {
  20981. this._checkUniform(name);
  20982. this._floatsArrays[name] = value;
  20983. return this;
  20984. };
  20985. ProceduralTexture.prototype.setColor3 = function (name, value) {
  20986. this._checkUniform(name);
  20987. this._colors3[name] = value;
  20988. return this;
  20989. };
  20990. ProceduralTexture.prototype.setColor4 = function (name, value) {
  20991. this._checkUniform(name);
  20992. this._colors4[name] = value;
  20993. return this;
  20994. };
  20995. ProceduralTexture.prototype.setVector2 = function (name, value) {
  20996. this._checkUniform(name);
  20997. this._vectors2[name] = value;
  20998. return this;
  20999. };
  21000. ProceduralTexture.prototype.setVector3 = function (name, value) {
  21001. this._checkUniform(name);
  21002. this._vectors3[name] = value;
  21003. return this;
  21004. };
  21005. ProceduralTexture.prototype.setMatrix = function (name, value) {
  21006. this._checkUniform(name);
  21007. this._matrices[name] = value;
  21008. return this;
  21009. };
  21010. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  21011. var scene = this.getScene();
  21012. var engine = scene.getEngine();
  21013. // Render
  21014. engine.enableEffect(this._effect);
  21015. engine.setState(false);
  21016. // Texture
  21017. for (var name in this._textures) {
  21018. this._effect.setTexture(name, this._textures[name]);
  21019. }
  21020. // Float
  21021. for (name in this._floats) {
  21022. this._effect.setFloat(name, this._floats[name]);
  21023. }
  21024. // Floats
  21025. for (name in this._floatsArrays) {
  21026. this._effect.setArray(name, this._floatsArrays[name]);
  21027. }
  21028. // Color3
  21029. for (name in this._colors3) {
  21030. this._effect.setColor3(name, this._colors3[name]);
  21031. }
  21032. // Color4
  21033. for (name in this._colors4) {
  21034. var color = this._colors4[name];
  21035. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  21036. }
  21037. // Vector2
  21038. for (name in this._vectors2) {
  21039. this._effect.setVector2(name, this._vectors2[name]);
  21040. }
  21041. // Vector3
  21042. for (name in this._vectors3) {
  21043. this._effect.setVector3(name, this._vectors3[name]);
  21044. }
  21045. // Matrix
  21046. for (name in this._matrices) {
  21047. this._effect.setMatrix(name, this._matrices[name]);
  21048. }
  21049. // VBOs
  21050. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  21051. if (this.isCube) {
  21052. for (var face = 0; face < 6; face++) {
  21053. engine.bindFramebuffer(this._texture, face);
  21054. this._effect.setFloat("face", face);
  21055. // Clear
  21056. engine.clear(scene.clearColor, true, true);
  21057. // Draw order
  21058. engine.draw(true, 0, 6);
  21059. // Mipmaps
  21060. if (face === 5) {
  21061. engine.generateMipMapsForCubemap(this._texture);
  21062. }
  21063. }
  21064. }
  21065. else {
  21066. engine.bindFramebuffer(this._texture);
  21067. // Clear
  21068. engine.clear(scene.clearColor, true, true);
  21069. // Draw order
  21070. engine.draw(true, 0, 6);
  21071. }
  21072. // Unbind
  21073. engine.unBindFramebuffer(this._texture, this.isCube);
  21074. if (this.onGenerated) {
  21075. this.onGenerated();
  21076. }
  21077. };
  21078. ProceduralTexture.prototype.clone = function () {
  21079. var textureSize = this.getSize();
  21080. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  21081. // Base texture
  21082. newTexture.hasAlpha = this.hasAlpha;
  21083. newTexture.level = this.level;
  21084. // RenderTarget Texture
  21085. newTexture.coordinatesMode = this.coordinatesMode;
  21086. return newTexture;
  21087. };
  21088. ProceduralTexture.prototype.dispose = function () {
  21089. var index = this.getScene()._proceduralTextures.indexOf(this);
  21090. if (index >= 0) {
  21091. this.getScene()._proceduralTextures.splice(index, 1);
  21092. }
  21093. _super.prototype.dispose.call(this);
  21094. };
  21095. return ProceduralTexture;
  21096. })(BABYLON.Texture);
  21097. BABYLON.ProceduralTexture = ProceduralTexture;
  21098. })(BABYLON || (BABYLON = {}));
  21099. var BABYLON;
  21100. (function (BABYLON) {
  21101. var MirrorTexture = (function (_super) {
  21102. __extends(MirrorTexture, _super);
  21103. function MirrorTexture(name, size, scene, generateMipMaps) {
  21104. var _this = this;
  21105. _super.call(this, name, size, scene, generateMipMaps, true);
  21106. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  21107. this._transformMatrix = BABYLON.Matrix.Zero();
  21108. this._mirrorMatrix = BABYLON.Matrix.Zero();
  21109. this.onBeforeRender = function () {
  21110. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  21111. _this._savedViewMatrix = scene.getViewMatrix();
  21112. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  21113. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  21114. scene.clipPlane = _this.mirrorPlane;
  21115. scene.getEngine().cullBackFaces = false;
  21116. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  21117. };
  21118. this.onAfterRender = function () {
  21119. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  21120. scene.getEngine().cullBackFaces = true;
  21121. scene._mirroredCameraPosition = null;
  21122. delete scene.clipPlane;
  21123. };
  21124. }
  21125. MirrorTexture.prototype.clone = function () {
  21126. var textureSize = this.getSize();
  21127. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21128. // Base texture
  21129. newTexture.hasAlpha = this.hasAlpha;
  21130. newTexture.level = this.level;
  21131. // Mirror Texture
  21132. newTexture.mirrorPlane = this.mirrorPlane.clone();
  21133. newTexture.renderList = this.renderList.slice(0);
  21134. return newTexture;
  21135. };
  21136. MirrorTexture.prototype.serialize = function () {
  21137. if (!this.name) {
  21138. return null;
  21139. }
  21140. var serializationObject = _super.prototype.serialize.call(this);
  21141. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  21142. return serializationObject;
  21143. };
  21144. return MirrorTexture;
  21145. })(BABYLON.RenderTargetTexture);
  21146. BABYLON.MirrorTexture = MirrorTexture;
  21147. })(BABYLON || (BABYLON = {}));
  21148. var BABYLON;
  21149. (function (BABYLON) {
  21150. /**
  21151. * Creates a refraction texture used by refraction channel of the standard material.
  21152. * @param name the texture name
  21153. * @param size size of the underlying texture
  21154. * @param scene root scene
  21155. */
  21156. var RefractionTexture = (function (_super) {
  21157. __extends(RefractionTexture, _super);
  21158. function RefractionTexture(name, size, scene, generateMipMaps) {
  21159. var _this = this;
  21160. _super.call(this, name, size, scene, generateMipMaps, true);
  21161. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  21162. this.depth = 2.0;
  21163. this.onBeforeRender = function () {
  21164. scene.clipPlane = _this.refractionPlane;
  21165. };
  21166. this.onAfterRender = function () {
  21167. delete scene.clipPlane;
  21168. };
  21169. }
  21170. RefractionTexture.prototype.clone = function () {
  21171. var textureSize = this.getSize();
  21172. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21173. // Base texture
  21174. newTexture.hasAlpha = this.hasAlpha;
  21175. newTexture.level = this.level;
  21176. // Refraction Texture
  21177. newTexture.refractionPlane = this.refractionPlane.clone();
  21178. newTexture.renderList = this.renderList.slice(0);
  21179. newTexture.depth = this.depth;
  21180. return newTexture;
  21181. };
  21182. RefractionTexture.prototype.serialize = function () {
  21183. if (!this.name) {
  21184. return null;
  21185. }
  21186. var serializationObject = _super.prototype.serialize.call(this);
  21187. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  21188. serializationObject.depth = this.depth;
  21189. return serializationObject;
  21190. };
  21191. return RefractionTexture;
  21192. })(BABYLON.RenderTargetTexture);
  21193. BABYLON.RefractionTexture = RefractionTexture;
  21194. })(BABYLON || (BABYLON = {}));
  21195. var BABYLON;
  21196. (function (BABYLON) {
  21197. var DynamicTexture = (function (_super) {
  21198. __extends(DynamicTexture, _super);
  21199. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  21200. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21201. _super.call(this, null, scene, !generateMipMaps);
  21202. this.name = name;
  21203. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21204. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21205. this._generateMipMaps = generateMipMaps;
  21206. if (options.getContext) {
  21207. this._canvas = options;
  21208. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  21209. }
  21210. else {
  21211. this._canvas = document.createElement("canvas");
  21212. if (options.width) {
  21213. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  21214. }
  21215. else {
  21216. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  21217. }
  21218. }
  21219. var textureSize = this.getSize();
  21220. this._canvas.width = textureSize.width;
  21221. this._canvas.height = textureSize.height;
  21222. this._context = this._canvas.getContext("2d");
  21223. }
  21224. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  21225. get: function () {
  21226. return true;
  21227. },
  21228. enumerable: true,
  21229. configurable: true
  21230. });
  21231. DynamicTexture.prototype.scale = function (ratio) {
  21232. var textureSize = this.getSize();
  21233. textureSize.width *= ratio;
  21234. textureSize.height *= ratio;
  21235. this._canvas.width = textureSize.width;
  21236. this._canvas.height = textureSize.height;
  21237. this.releaseInternalTexture();
  21238. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  21239. };
  21240. DynamicTexture.prototype.getContext = function () {
  21241. return this._context;
  21242. };
  21243. DynamicTexture.prototype.clear = function () {
  21244. var size = this.getSize();
  21245. this._context.fillRect(0, 0, size.width, size.height);
  21246. };
  21247. DynamicTexture.prototype.update = function (invertY) {
  21248. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  21249. };
  21250. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  21251. if (update === void 0) { update = true; }
  21252. var size = this.getSize();
  21253. if (clearColor) {
  21254. this._context.fillStyle = clearColor;
  21255. this._context.fillRect(0, 0, size.width, size.height);
  21256. }
  21257. this._context.font = font;
  21258. if (x === null) {
  21259. var textSize = this._context.measureText(text);
  21260. x = (size.width - textSize.width) / 2;
  21261. }
  21262. this._context.fillStyle = color;
  21263. this._context.fillText(text, x, y);
  21264. if (update) {
  21265. this.update(invertY);
  21266. }
  21267. };
  21268. DynamicTexture.prototype.clone = function () {
  21269. var textureSize = this.getSize();
  21270. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  21271. // Base texture
  21272. newTexture.hasAlpha = this.hasAlpha;
  21273. newTexture.level = this.level;
  21274. // Dynamic Texture
  21275. newTexture.wrapU = this.wrapU;
  21276. newTexture.wrapV = this.wrapV;
  21277. return newTexture;
  21278. };
  21279. return DynamicTexture;
  21280. })(BABYLON.Texture);
  21281. BABYLON.DynamicTexture = DynamicTexture;
  21282. })(BABYLON || (BABYLON = {}));
  21283. var BABYLON;
  21284. (function (BABYLON) {
  21285. var VideoTexture = (function (_super) {
  21286. __extends(VideoTexture, _super);
  21287. /**
  21288. * Creates a video texture.
  21289. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  21290. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  21291. * @param {BABYLON.Scene} scene is obviously the current scene.
  21292. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  21293. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  21294. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  21295. */
  21296. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  21297. var _this = this;
  21298. if (generateMipMaps === void 0) { generateMipMaps = false; }
  21299. if (invertY === void 0) { invertY = false; }
  21300. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  21301. _super.call(this, null, scene, !generateMipMaps, invertY);
  21302. this._autoLaunch = true;
  21303. var urls;
  21304. this.name = name;
  21305. if (urlsOrVideo instanceof HTMLVideoElement) {
  21306. this.video = urlsOrVideo;
  21307. }
  21308. else {
  21309. urls = urlsOrVideo;
  21310. this.video = document.createElement("video");
  21311. this.video.autoplay = false;
  21312. this.video.loop = true;
  21313. }
  21314. this._generateMipMaps = generateMipMaps;
  21315. this._samplingMode = samplingMode;
  21316. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  21317. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21318. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21319. }
  21320. else {
  21321. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21322. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  21323. this._generateMipMaps = false;
  21324. }
  21325. if (urls) {
  21326. this.video.addEventListener("canplaythrough", function () {
  21327. _this._createTexture();
  21328. });
  21329. urls.forEach(function (url) {
  21330. var source = document.createElement("source");
  21331. source.src = url;
  21332. _this.video.appendChild(source);
  21333. });
  21334. }
  21335. else {
  21336. this._createTexture();
  21337. }
  21338. this._lastUpdate = BABYLON.Tools.Now;
  21339. }
  21340. VideoTexture.prototype._createTexture = function () {
  21341. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode, false);
  21342. this._texture.isReady = true;
  21343. };
  21344. VideoTexture.prototype.update = function () {
  21345. if (this._autoLaunch) {
  21346. this._autoLaunch = false;
  21347. this.video.play();
  21348. }
  21349. var now = BABYLON.Tools.Now;
  21350. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  21351. return false;
  21352. }
  21353. this._lastUpdate = now;
  21354. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  21355. return true;
  21356. };
  21357. return VideoTexture;
  21358. })(BABYLON.Texture);
  21359. BABYLON.VideoTexture = VideoTexture;
  21360. })(BABYLON || (BABYLON = {}));
  21361. var BABYLON;
  21362. (function (BABYLON) {
  21363. var CustomProceduralTexture = (function (_super) {
  21364. __extends(CustomProceduralTexture, _super);
  21365. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  21366. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  21367. this._animate = true;
  21368. this._time = 0;
  21369. this._texturePath = texturePath;
  21370. //Try to load json
  21371. this.loadJson(texturePath);
  21372. this.refreshRate = 1;
  21373. }
  21374. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  21375. var _this = this;
  21376. var that = this;
  21377. function noConfigFile() {
  21378. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  21379. try {
  21380. that.setFragment(that._texturePath);
  21381. }
  21382. catch (ex) {
  21383. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  21384. }
  21385. }
  21386. var configFileUrl = jsonUrl + "/config.json";
  21387. var xhr = new XMLHttpRequest();
  21388. xhr.open("GET", configFileUrl, true);
  21389. xhr.addEventListener("load", function () {
  21390. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  21391. try {
  21392. _this._config = JSON.parse(xhr.response);
  21393. _this.updateShaderUniforms();
  21394. _this.updateTextures();
  21395. _this.setFragment(_this._texturePath + "/custom");
  21396. _this._animate = _this._config.animate;
  21397. _this.refreshRate = _this._config.refreshrate;
  21398. }
  21399. catch (ex) {
  21400. noConfigFile();
  21401. }
  21402. }
  21403. else {
  21404. noConfigFile();
  21405. }
  21406. }, false);
  21407. xhr.addEventListener("error", function () {
  21408. noConfigFile();
  21409. }, false);
  21410. try {
  21411. xhr.send();
  21412. }
  21413. catch (ex) {
  21414. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  21415. }
  21416. };
  21417. CustomProceduralTexture.prototype.isReady = function () {
  21418. if (!_super.prototype.isReady.call(this)) {
  21419. return false;
  21420. }
  21421. for (var name in this._textures) {
  21422. var texture = this._textures[name];
  21423. if (!texture.isReady()) {
  21424. return false;
  21425. }
  21426. }
  21427. return true;
  21428. };
  21429. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  21430. if (this._animate) {
  21431. this._time += this.getScene().getAnimationRatio() * 0.03;
  21432. this.updateShaderUniforms();
  21433. }
  21434. _super.prototype.render.call(this, useCameraPostProcess);
  21435. };
  21436. CustomProceduralTexture.prototype.updateTextures = function () {
  21437. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  21438. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  21439. }
  21440. };
  21441. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  21442. if (this._config) {
  21443. for (var j = 0; j < this._config.uniforms.length; j++) {
  21444. var uniform = this._config.uniforms[j];
  21445. switch (uniform.type) {
  21446. case "float":
  21447. this.setFloat(uniform.name, uniform.value);
  21448. break;
  21449. case "color3":
  21450. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  21451. break;
  21452. case "color4":
  21453. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  21454. break;
  21455. case "vector2":
  21456. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  21457. break;
  21458. case "vector3":
  21459. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  21460. break;
  21461. }
  21462. }
  21463. }
  21464. this.setFloat("time", this._time);
  21465. };
  21466. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  21467. get: function () {
  21468. return this._animate;
  21469. },
  21470. set: function (value) {
  21471. this._animate = value;
  21472. },
  21473. enumerable: true,
  21474. configurable: true
  21475. });
  21476. return CustomProceduralTexture;
  21477. })(BABYLON.ProceduralTexture);
  21478. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  21479. })(BABYLON || (BABYLON = {}));
  21480. var BABYLON;
  21481. (function (BABYLON) {
  21482. var EffectFallbacks = (function () {
  21483. function EffectFallbacks() {
  21484. this._defines = {};
  21485. this._currentRank = 32;
  21486. this._maxRank = -1;
  21487. }
  21488. EffectFallbacks.prototype.addFallback = function (rank, define) {
  21489. if (!this._defines[rank]) {
  21490. if (rank < this._currentRank) {
  21491. this._currentRank = rank;
  21492. }
  21493. if (rank > this._maxRank) {
  21494. this._maxRank = rank;
  21495. }
  21496. this._defines[rank] = new Array();
  21497. }
  21498. this._defines[rank].push(define);
  21499. };
  21500. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  21501. this._meshRank = rank;
  21502. this._mesh = mesh;
  21503. if (rank > this._maxRank) {
  21504. this._maxRank = rank;
  21505. }
  21506. };
  21507. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  21508. get: function () {
  21509. return this._currentRank <= this._maxRank;
  21510. },
  21511. enumerable: true,
  21512. configurable: true
  21513. });
  21514. EffectFallbacks.prototype.reduce = function (currentDefines) {
  21515. var currentFallbacks = this._defines[this._currentRank];
  21516. for (var index = 0; index < currentFallbacks.length; index++) {
  21517. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  21518. }
  21519. if (this._mesh && this._currentRank === this._meshRank) {
  21520. this._mesh.computeBonesUsingShaders = false;
  21521. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  21522. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  21523. }
  21524. this._currentRank++;
  21525. return currentDefines;
  21526. };
  21527. return EffectFallbacks;
  21528. })();
  21529. BABYLON.EffectFallbacks = EffectFallbacks;
  21530. var Effect = (function () {
  21531. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  21532. var _this = this;
  21533. this._isReady = false;
  21534. this._compilationError = "";
  21535. this._valueCache = [];
  21536. this._engine = engine;
  21537. this.name = baseName;
  21538. this.defines = defines;
  21539. this._uniformsNames = uniformsNames.concat(samplers);
  21540. this._samplers = samplers;
  21541. this._attributesNames = attributesNames;
  21542. this.onError = onError;
  21543. this.onCompiled = onCompiled;
  21544. var vertexSource;
  21545. var fragmentSource;
  21546. if (baseName.vertexElement) {
  21547. vertexSource = document.getElementById(baseName.vertexElement);
  21548. if (!vertexSource) {
  21549. vertexSource = baseName.vertexElement;
  21550. }
  21551. }
  21552. else {
  21553. vertexSource = baseName.vertex || baseName;
  21554. }
  21555. if (baseName.fragmentElement) {
  21556. fragmentSource = document.getElementById(baseName.fragmentElement);
  21557. if (!fragmentSource) {
  21558. fragmentSource = baseName.fragmentElement;
  21559. }
  21560. }
  21561. else {
  21562. fragmentSource = baseName.fragment || baseName;
  21563. }
  21564. this._loadVertexShader(vertexSource, function (vertexCode) {
  21565. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  21566. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  21567. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  21568. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  21569. });
  21570. });
  21571. });
  21572. });
  21573. }
  21574. // Properties
  21575. Effect.prototype.isReady = function () {
  21576. return this._isReady;
  21577. };
  21578. Effect.prototype.getProgram = function () {
  21579. return this._program;
  21580. };
  21581. Effect.prototype.getAttributesNames = function () {
  21582. return this._attributesNames;
  21583. };
  21584. Effect.prototype.getAttributeLocation = function (index) {
  21585. return this._attributes[index];
  21586. };
  21587. Effect.prototype.getAttributeLocationByName = function (name) {
  21588. var index = this._attributesNames.indexOf(name);
  21589. return this._attributes[index];
  21590. };
  21591. Effect.prototype.getAttributesCount = function () {
  21592. return this._attributes.length;
  21593. };
  21594. Effect.prototype.getUniformIndex = function (uniformName) {
  21595. return this._uniformsNames.indexOf(uniformName);
  21596. };
  21597. Effect.prototype.getUniform = function (uniformName) {
  21598. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  21599. };
  21600. Effect.prototype.getSamplers = function () {
  21601. return this._samplers;
  21602. };
  21603. Effect.prototype.getCompilationError = function () {
  21604. return this._compilationError;
  21605. };
  21606. // Methods
  21607. Effect.prototype._loadVertexShader = function (vertex, callback) {
  21608. // DOM element ?
  21609. if (vertex instanceof HTMLElement) {
  21610. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  21611. callback(vertexCode);
  21612. return;
  21613. }
  21614. // Is in local store ?
  21615. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  21616. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  21617. return;
  21618. }
  21619. var vertexShaderUrl;
  21620. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  21621. vertexShaderUrl = vertex;
  21622. }
  21623. else {
  21624. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  21625. }
  21626. // Vertex shader
  21627. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  21628. };
  21629. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  21630. // DOM element ?
  21631. if (fragment instanceof HTMLElement) {
  21632. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  21633. callback(fragmentCode);
  21634. return;
  21635. }
  21636. // Is in local store ?
  21637. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  21638. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  21639. return;
  21640. }
  21641. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  21642. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  21643. return;
  21644. }
  21645. var fragmentShaderUrl;
  21646. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  21647. fragmentShaderUrl = fragment;
  21648. }
  21649. else {
  21650. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  21651. }
  21652. // Fragment shader
  21653. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  21654. };
  21655. Effect.prototype._dumpShadersName = function () {
  21656. if (this.name.vertexElement) {
  21657. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  21658. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  21659. }
  21660. else if (this.name.vertex) {
  21661. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  21662. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  21663. }
  21664. else {
  21665. BABYLON.Tools.Error("Vertex shader:" + this.name);
  21666. BABYLON.Tools.Error("Fragment shader:" + this.name);
  21667. }
  21668. };
  21669. Effect.prototype._processIncludes = function (sourceCode, callback) {
  21670. var _this = this;
  21671. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  21672. var match = regex.exec(sourceCode);
  21673. var returnValue = new String(sourceCode);
  21674. while (match != null) {
  21675. var includeFile = match[1];
  21676. if (Effect.IncludesShadersStore[includeFile]) {
  21677. // Substitution
  21678. var includeContent = Effect.IncludesShadersStore[includeFile];
  21679. if (match[2]) {
  21680. var splits = match[3].split(",");
  21681. for (var index = 0; index < splits.length; index += 2) {
  21682. var source = new RegExp(splits[index], "g");
  21683. var dest = splits[index + 1];
  21684. includeContent = includeContent.replace(source, dest);
  21685. }
  21686. }
  21687. if (match[4]) {
  21688. includeContent = includeContent.replace(/\{X\}/g, match[5]);
  21689. }
  21690. // Replace
  21691. returnValue = returnValue.replace(match[0], includeContent);
  21692. }
  21693. else {
  21694. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  21695. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  21696. Effect.IncludesShadersStore[includeFile] = fileContent;
  21697. _this._processIncludes(returnValue, callback);
  21698. });
  21699. return;
  21700. }
  21701. match = regex.exec(sourceCode);
  21702. }
  21703. callback(returnValue);
  21704. };
  21705. Effect.prototype._processPrecision = function (source) {
  21706. if (source.indexOf("precision highp float") === -1) {
  21707. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21708. source = "precision mediump float;\n" + source;
  21709. }
  21710. else {
  21711. source = "precision highp float;\n" + source;
  21712. }
  21713. }
  21714. else {
  21715. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21716. source = source.replace("precision highp float", "precision mediump float");
  21717. }
  21718. }
  21719. return source;
  21720. };
  21721. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  21722. try {
  21723. var engine = this._engine;
  21724. // Precision
  21725. vertexSourceCode = this._processPrecision(vertexSourceCode);
  21726. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  21727. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  21728. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  21729. this._attributes = engine.getAttributes(this._program, attributesNames);
  21730. for (var index = 0; index < this._samplers.length; index++) {
  21731. var sampler = this.getUniform(this._samplers[index]);
  21732. if (sampler == null) {
  21733. this._samplers.splice(index, 1);
  21734. index--;
  21735. }
  21736. }
  21737. engine.bindSamplers(this);
  21738. this._isReady = true;
  21739. if (this.onCompiled) {
  21740. this.onCompiled(this);
  21741. }
  21742. }
  21743. catch (e) {
  21744. // Is it a problem with precision?
  21745. if (e.message.indexOf("highp") !== -1) {
  21746. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  21747. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  21748. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  21749. return;
  21750. }
  21751. // Let's go through fallbacks then
  21752. if (fallbacks && fallbacks.isMoreFallbacks) {
  21753. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  21754. this._dumpShadersName();
  21755. defines = fallbacks.reduce(defines);
  21756. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  21757. }
  21758. else {
  21759. BABYLON.Tools.Error("Unable to compile effect: ");
  21760. this._dumpShadersName();
  21761. BABYLON.Tools.Error("Defines: " + defines);
  21762. BABYLON.Tools.Error("Error: " + e.message);
  21763. this._compilationError = e.message;
  21764. if (this.onError) {
  21765. this.onError(this, this._compilationError);
  21766. }
  21767. }
  21768. }
  21769. };
  21770. Object.defineProperty(Effect.prototype, "isSupported", {
  21771. get: function () {
  21772. return this._compilationError === "";
  21773. },
  21774. enumerable: true,
  21775. configurable: true
  21776. });
  21777. Effect.prototype._bindTexture = function (channel, texture) {
  21778. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  21779. };
  21780. Effect.prototype.setTexture = function (channel, texture) {
  21781. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  21782. };
  21783. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  21784. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  21785. };
  21786. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  21787. if (!this._valueCache[uniformName]) {
  21788. this._valueCache[uniformName] = new BABYLON.Matrix();
  21789. }
  21790. for (var index = 0; index < 16; index++) {
  21791. this._valueCache[uniformName].m[index] = matrix.m[index];
  21792. }
  21793. };
  21794. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  21795. if (!this._valueCache[uniformName]) {
  21796. this._valueCache[uniformName] = [x, y];
  21797. return;
  21798. }
  21799. this._valueCache[uniformName][0] = x;
  21800. this._valueCache[uniformName][1] = y;
  21801. };
  21802. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  21803. if (!this._valueCache[uniformName]) {
  21804. this._valueCache[uniformName] = [x, y, z];
  21805. return;
  21806. }
  21807. this._valueCache[uniformName][0] = x;
  21808. this._valueCache[uniformName][1] = y;
  21809. this._valueCache[uniformName][2] = z;
  21810. };
  21811. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  21812. if (!this._valueCache[uniformName]) {
  21813. this._valueCache[uniformName] = [x, y, z, w];
  21814. return;
  21815. }
  21816. this._valueCache[uniformName][0] = x;
  21817. this._valueCache[uniformName][1] = y;
  21818. this._valueCache[uniformName][2] = z;
  21819. this._valueCache[uniformName][3] = w;
  21820. };
  21821. Effect.prototype.setArray = function (uniformName, array) {
  21822. this._engine.setArray(this.getUniform(uniformName), array);
  21823. return this;
  21824. };
  21825. Effect.prototype.setArray2 = function (uniformName, array) {
  21826. this._engine.setArray2(this.getUniform(uniformName), array);
  21827. return this;
  21828. };
  21829. Effect.prototype.setArray3 = function (uniformName, array) {
  21830. this._engine.setArray3(this.getUniform(uniformName), array);
  21831. return this;
  21832. };
  21833. Effect.prototype.setArray4 = function (uniformName, array) {
  21834. this._engine.setArray4(this.getUniform(uniformName), array);
  21835. return this;
  21836. };
  21837. Effect.prototype.setMatrices = function (uniformName, matrices) {
  21838. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  21839. return this;
  21840. };
  21841. Effect.prototype.setMatrix = function (uniformName, matrix) {
  21842. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  21843. // return this;
  21844. // this._cacheMatrix(uniformName, matrix);
  21845. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  21846. return this;
  21847. };
  21848. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  21849. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  21850. return this;
  21851. };
  21852. Effect.prototype.setMatrix2x2 = function (uniformname, matrix) {
  21853. this._engine.setMatrix2x2(this.getUniform(uniformname), matrix);
  21854. return this;
  21855. };
  21856. Effect.prototype.setFloat = function (uniformName, value) {
  21857. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  21858. return this;
  21859. this._valueCache[uniformName] = value;
  21860. this._engine.setFloat(this.getUniform(uniformName), value);
  21861. return this;
  21862. };
  21863. Effect.prototype.setBool = function (uniformName, bool) {
  21864. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  21865. return this;
  21866. this._valueCache[uniformName] = bool;
  21867. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  21868. return this;
  21869. };
  21870. Effect.prototype.setVector2 = function (uniformName, vector2) {
  21871. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  21872. return this;
  21873. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  21874. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  21875. return this;
  21876. };
  21877. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  21878. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  21879. return this;
  21880. this._cacheFloat2(uniformName, x, y);
  21881. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  21882. return this;
  21883. };
  21884. Effect.prototype.setVector3 = function (uniformName, vector3) {
  21885. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  21886. return this;
  21887. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  21888. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  21889. return this;
  21890. };
  21891. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  21892. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  21893. return this;
  21894. this._cacheFloat3(uniformName, x, y, z);
  21895. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  21896. return this;
  21897. };
  21898. Effect.prototype.setVector4 = function (uniformName, vector4) {
  21899. 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)
  21900. return this;
  21901. this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w);
  21902. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  21903. return this;
  21904. };
  21905. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  21906. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  21907. return this;
  21908. this._cacheFloat4(uniformName, x, y, z, w);
  21909. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  21910. return this;
  21911. };
  21912. Effect.prototype.setColor3 = function (uniformName, color3) {
  21913. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  21914. return this;
  21915. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  21916. this._engine.setColor3(this.getUniform(uniformName), color3);
  21917. return this;
  21918. };
  21919. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  21920. 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)
  21921. return this;
  21922. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  21923. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  21924. return this;
  21925. };
  21926. // Statics
  21927. Effect.ShadersStore = {};
  21928. Effect.IncludesShadersStore = {};
  21929. return Effect;
  21930. })();
  21931. BABYLON.Effect = Effect;
  21932. })(BABYLON || (BABYLON = {}));
  21933. var BABYLON;
  21934. (function (BABYLON) {
  21935. var maxSimultaneousLights = 4;
  21936. var MaterialHelper = (function () {
  21937. function MaterialHelper() {
  21938. }
  21939. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines) {
  21940. var lightIndex = 0;
  21941. var needNormals = false;
  21942. for (var index = 0; index < scene.lights.length; index++) {
  21943. var light = scene.lights[index];
  21944. if (!light.isEnabled()) {
  21945. continue;
  21946. }
  21947. // Excluded check
  21948. if (light._excludedMeshesIds.length > 0) {
  21949. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  21950. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  21951. if (excludedMesh) {
  21952. light.excludedMeshes.push(excludedMesh);
  21953. }
  21954. }
  21955. light._excludedMeshesIds = [];
  21956. }
  21957. // Included check
  21958. if (light._includedOnlyMeshesIds.length > 0) {
  21959. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  21960. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  21961. if (includedOnlyMesh) {
  21962. light.includedOnlyMeshes.push(includedOnlyMesh);
  21963. }
  21964. }
  21965. light._includedOnlyMeshesIds = [];
  21966. }
  21967. if (!light.canAffectMesh(mesh)) {
  21968. continue;
  21969. }
  21970. needNormals = true;
  21971. defines["LIGHT" + lightIndex] = true;
  21972. var type;
  21973. if (light instanceof BABYLON.SpotLight) {
  21974. type = "SPOTLIGHT" + lightIndex;
  21975. }
  21976. else if (light instanceof BABYLON.HemisphericLight) {
  21977. type = "HEMILIGHT" + lightIndex;
  21978. }
  21979. else if (light instanceof BABYLON.PointLight) {
  21980. type = "POINTLIGHT" + lightIndex;
  21981. }
  21982. else {
  21983. type = "DIRLIGHT" + lightIndex;
  21984. }
  21985. defines[type] = true;
  21986. // Specular
  21987. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  21988. defines["SPECULARTERM"] = true;
  21989. }
  21990. // Shadows
  21991. if (scene.shadowsEnabled) {
  21992. var shadowGenerator = light.getShadowGenerator();
  21993. if (mesh && mesh.receiveShadows && shadowGenerator) {
  21994. defines["SHADOW" + lightIndex] = true;
  21995. defines["SHADOWS"] = true;
  21996. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  21997. defines["SHADOWVSM" + lightIndex] = true;
  21998. }
  21999. if (shadowGenerator.usePoissonSampling) {
  22000. defines["SHADOWPCF" + lightIndex] = true;
  22001. }
  22002. }
  22003. }
  22004. lightIndex++;
  22005. if (lightIndex === maxSimultaneousLights)
  22006. break;
  22007. }
  22008. return needNormals;
  22009. };
  22010. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks) {
  22011. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22012. if (!defines["LIGHT" + lightIndex]) {
  22013. continue;
  22014. }
  22015. if (lightIndex > 0) {
  22016. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  22017. }
  22018. if (defines["SHADOW" + lightIndex]) {
  22019. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  22020. }
  22021. if (defines["SHADOWPCF" + lightIndex]) {
  22022. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  22023. }
  22024. if (defines["SHADOWVSM" + lightIndex]) {
  22025. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  22026. }
  22027. }
  22028. };
  22029. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  22030. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  22031. fallbacks.addCPUSkinningFallback(0, mesh);
  22032. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22033. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22034. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  22035. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  22036. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  22037. }
  22038. }
  22039. };
  22040. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  22041. if (defines["INSTANCES"]) {
  22042. attribs.push("world0");
  22043. attribs.push("world1");
  22044. attribs.push("world2");
  22045. attribs.push("world3");
  22046. }
  22047. };
  22048. // Bindings
  22049. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  22050. var shadowGenerator = light.getShadowGenerator();
  22051. if (mesh.receiveShadows && shadowGenerator) {
  22052. if (!light.needCube()) {
  22053. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  22054. }
  22055. else {
  22056. if (!depthValuesAlreadySet) {
  22057. depthValuesAlreadySet = true;
  22058. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  22059. }
  22060. }
  22061. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  22062. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  22063. }
  22064. return depthValuesAlreadySet;
  22065. };
  22066. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  22067. if (light instanceof BABYLON.PointLight) {
  22068. // Point Light
  22069. light.transferToEffect(effect, "vLightData" + lightIndex);
  22070. }
  22071. else if (light instanceof BABYLON.DirectionalLight) {
  22072. // Directional Light
  22073. light.transferToEffect(effect, "vLightData" + lightIndex);
  22074. }
  22075. else if (light instanceof BABYLON.SpotLight) {
  22076. // Spot Light
  22077. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  22078. }
  22079. else if (light instanceof BABYLON.HemisphericLight) {
  22080. // Hemispheric Light
  22081. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  22082. }
  22083. };
  22084. MaterialHelper.BindLights = function (scene, mesh, effect, defines) {
  22085. var lightIndex = 0;
  22086. var depthValuesAlreadySet = false;
  22087. for (var index = 0; index < scene.lights.length; index++) {
  22088. var light = scene.lights[index];
  22089. if (!light.isEnabled()) {
  22090. continue;
  22091. }
  22092. if (!light.canAffectMesh(mesh)) {
  22093. continue;
  22094. }
  22095. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  22096. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  22097. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  22098. if (defines["SPECULARTERM"]) {
  22099. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  22100. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  22101. }
  22102. // Shadows
  22103. if (scene.shadowsEnabled) {
  22104. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  22105. }
  22106. lightIndex++;
  22107. if (lightIndex === maxSimultaneousLights)
  22108. break;
  22109. }
  22110. };
  22111. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  22112. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  22113. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  22114. effect.setColor3("vFogColor", scene.fogColor);
  22115. }
  22116. };
  22117. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  22118. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  22119. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  22120. }
  22121. };
  22122. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  22123. if (defines["LOGARITHMICDEPTH"]) {
  22124. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  22125. }
  22126. };
  22127. MaterialHelper.BindClipPlane = function (effect, scene) {
  22128. if (scene.clipPlane) {
  22129. var clipPlane = scene.clipPlane;
  22130. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22131. }
  22132. };
  22133. return MaterialHelper;
  22134. })();
  22135. BABYLON.MaterialHelper = MaterialHelper;
  22136. })(BABYLON || (BABYLON = {}));
  22137. var BABYLON;
  22138. (function (BABYLON) {
  22139. var FresnelParameters = (function () {
  22140. function FresnelParameters() {
  22141. this.isEnabled = true;
  22142. this.leftColor = BABYLON.Color3.White();
  22143. this.rightColor = BABYLON.Color3.Black();
  22144. this.bias = 0;
  22145. this.power = 1;
  22146. }
  22147. FresnelParameters.prototype.clone = function () {
  22148. var newFresnelParameters = new FresnelParameters();
  22149. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  22150. return new FresnelParameters;
  22151. };
  22152. FresnelParameters.prototype.serialize = function () {
  22153. var serializationObject = {};
  22154. serializationObject.isEnabled = this.isEnabled;
  22155. serializationObject.leftColor = this.leftColor;
  22156. serializationObject.rightColor = this.rightColor;
  22157. serializationObject.bias = this.bias;
  22158. serializationObject.power = this.power;
  22159. return serializationObject;
  22160. };
  22161. FresnelParameters.Parse = function (parsedFresnelParameters) {
  22162. var fresnelParameters = new FresnelParameters();
  22163. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  22164. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  22165. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  22166. fresnelParameters.bias = parsedFresnelParameters.bias;
  22167. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  22168. return fresnelParameters;
  22169. };
  22170. return FresnelParameters;
  22171. })();
  22172. BABYLON.FresnelParameters = FresnelParameters;
  22173. })(BABYLON || (BABYLON = {}));
  22174. var BABYLON;
  22175. (function (BABYLON) {
  22176. var MaterialDefines = (function () {
  22177. function MaterialDefines() {
  22178. }
  22179. MaterialDefines.prototype.isEqual = function (other) {
  22180. for (var index = 0; index < this._keys.length; index++) {
  22181. var prop = this._keys[index];
  22182. if (this[prop] !== other[prop]) {
  22183. return false;
  22184. }
  22185. }
  22186. return true;
  22187. };
  22188. MaterialDefines.prototype.cloneTo = function (other) {
  22189. for (var index = 0; index < this._keys.length; index++) {
  22190. var prop = this._keys[index];
  22191. other[prop] = this[prop];
  22192. }
  22193. };
  22194. MaterialDefines.prototype.reset = function () {
  22195. for (var index = 0; index < this._keys.length; index++) {
  22196. var prop = this._keys[index];
  22197. if (typeof (this[prop]) === "number") {
  22198. this[prop] = 0;
  22199. }
  22200. else {
  22201. this[prop] = false;
  22202. }
  22203. }
  22204. };
  22205. MaterialDefines.prototype.toString = function () {
  22206. var result = "";
  22207. for (var index = 0; index < this._keys.length; index++) {
  22208. var prop = this._keys[index];
  22209. if (typeof (this[prop]) === "number") {
  22210. result += "#define " + prop + " " + this[prop] + "\n";
  22211. }
  22212. else if (this[prop]) {
  22213. result += "#define " + prop + "\n";
  22214. }
  22215. }
  22216. return result;
  22217. };
  22218. return MaterialDefines;
  22219. })();
  22220. BABYLON.MaterialDefines = MaterialDefines;
  22221. var Material = (function () {
  22222. function Material(name, scene, doNotAdd) {
  22223. this.name = name;
  22224. this.checkReadyOnEveryCall = false;
  22225. this.checkReadyOnlyOnce = false;
  22226. this.state = "";
  22227. this.alpha = 1.0;
  22228. this.backFaceCulling = true;
  22229. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  22230. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  22231. this.disableDepthWrite = false;
  22232. this.fogEnabled = true;
  22233. this.pointSize = 1.0;
  22234. this.zOffset = 0;
  22235. this._wasPreviouslyReady = false;
  22236. this._fillMode = Material.TriangleFillMode;
  22237. this.id = name;
  22238. this._scene = scene;
  22239. if (!doNotAdd) {
  22240. scene.materials.push(this);
  22241. }
  22242. }
  22243. Object.defineProperty(Material, "TriangleFillMode", {
  22244. get: function () {
  22245. return Material._TriangleFillMode;
  22246. },
  22247. enumerable: true,
  22248. configurable: true
  22249. });
  22250. Object.defineProperty(Material, "WireFrameFillMode", {
  22251. get: function () {
  22252. return Material._WireFrameFillMode;
  22253. },
  22254. enumerable: true,
  22255. configurable: true
  22256. });
  22257. Object.defineProperty(Material, "PointFillMode", {
  22258. get: function () {
  22259. return Material._PointFillMode;
  22260. },
  22261. enumerable: true,
  22262. configurable: true
  22263. });
  22264. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  22265. get: function () {
  22266. return Material._ClockWiseSideOrientation;
  22267. },
  22268. enumerable: true,
  22269. configurable: true
  22270. });
  22271. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  22272. get: function () {
  22273. return Material._CounterClockWiseSideOrientation;
  22274. },
  22275. enumerable: true,
  22276. configurable: true
  22277. });
  22278. Object.defineProperty(Material.prototype, "wireframe", {
  22279. get: function () {
  22280. return this._fillMode === Material.WireFrameFillMode;
  22281. },
  22282. set: function (value) {
  22283. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  22284. },
  22285. enumerable: true,
  22286. configurable: true
  22287. });
  22288. Object.defineProperty(Material.prototype, "pointsCloud", {
  22289. get: function () {
  22290. return this._fillMode === Material.PointFillMode;
  22291. },
  22292. set: function (value) {
  22293. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  22294. },
  22295. enumerable: true,
  22296. configurable: true
  22297. });
  22298. Object.defineProperty(Material.prototype, "fillMode", {
  22299. get: function () {
  22300. return this._fillMode;
  22301. },
  22302. set: function (value) {
  22303. this._fillMode = value;
  22304. },
  22305. enumerable: true,
  22306. configurable: true
  22307. });
  22308. /**
  22309. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22310. * subclasses should override adding information pertainent to themselves
  22311. */
  22312. Material.prototype.toString = function (fullDetails) {
  22313. var ret = "Name: " + this.name;
  22314. if (fullDetails) {
  22315. }
  22316. return ret;
  22317. };
  22318. Object.defineProperty(Material.prototype, "isFrozen", {
  22319. get: function () {
  22320. return this.checkReadyOnlyOnce;
  22321. },
  22322. enumerable: true,
  22323. configurable: true
  22324. });
  22325. Material.prototype.freeze = function () {
  22326. this.checkReadyOnlyOnce = true;
  22327. };
  22328. Material.prototype.unfreeze = function () {
  22329. this.checkReadyOnlyOnce = false;
  22330. };
  22331. Material.prototype.isReady = function (mesh, useInstances) {
  22332. return true;
  22333. };
  22334. Material.prototype.getEffect = function () {
  22335. return this._effect;
  22336. };
  22337. Material.prototype.getScene = function () {
  22338. return this._scene;
  22339. };
  22340. Material.prototype.needAlphaBlending = function () {
  22341. return (this.alpha < 1.0);
  22342. };
  22343. Material.prototype.needAlphaTesting = function () {
  22344. return false;
  22345. };
  22346. Material.prototype.getAlphaTestTexture = function () {
  22347. return null;
  22348. };
  22349. Material.prototype.trackCreation = function (onCompiled, onError) {
  22350. };
  22351. Material.prototype.markDirty = function () {
  22352. this._wasPreviouslyReady = false;
  22353. };
  22354. Material.prototype._preBind = function () {
  22355. var engine = this._scene.getEngine();
  22356. engine.enableEffect(this._effect);
  22357. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  22358. };
  22359. Material.prototype.bind = function (world, mesh) {
  22360. this._scene._cachedMaterial = this;
  22361. if (this.onBind) {
  22362. this.onBind(this, mesh);
  22363. }
  22364. if (this.disableDepthWrite) {
  22365. var engine = this._scene.getEngine();
  22366. this._cachedDepthWriteState = engine.getDepthWrite();
  22367. engine.setDepthWrite(false);
  22368. }
  22369. };
  22370. Material.prototype.bindOnlyWorldMatrix = function (world) {
  22371. };
  22372. Material.prototype.unbind = function () {
  22373. if (this.disableDepthWrite) {
  22374. var engine = this._scene.getEngine();
  22375. engine.setDepthWrite(this._cachedDepthWriteState);
  22376. }
  22377. };
  22378. Material.prototype.clone = function (name) {
  22379. return null;
  22380. };
  22381. Material.prototype.getBindedMeshes = function () {
  22382. var result = new Array();
  22383. for (var index = 0; index < this._scene.meshes.length; index++) {
  22384. var mesh = this._scene.meshes[index];
  22385. if (mesh.material === this) {
  22386. result.push(mesh);
  22387. }
  22388. }
  22389. return result;
  22390. };
  22391. Material.prototype.dispose = function (forceDisposeEffect) {
  22392. // Animations
  22393. this.getScene().stopAnimation(this);
  22394. // Remove from scene
  22395. var index = this._scene.materials.indexOf(this);
  22396. if (index >= 0) {
  22397. this._scene.materials.splice(index, 1);
  22398. }
  22399. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  22400. if (forceDisposeEffect && this._effect) {
  22401. this._scene.getEngine()._releaseEffect(this._effect);
  22402. this._effect = null;
  22403. }
  22404. // Remove from meshes
  22405. for (index = 0; index < this._scene.meshes.length; index++) {
  22406. var mesh = this._scene.meshes[index];
  22407. if (mesh.material === this) {
  22408. mesh.material = null;
  22409. }
  22410. }
  22411. // Callback
  22412. if (this.onDispose) {
  22413. this.onDispose();
  22414. }
  22415. };
  22416. Material.prototype.serialize = function () {
  22417. return BABYLON.SerializationHelper.Serialize(this);
  22418. };
  22419. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  22420. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  22421. multiMaterial.id = parsedMultiMaterial.id;
  22422. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  22423. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  22424. var subMatId = parsedMultiMaterial.materials[matIndex];
  22425. if (subMatId) {
  22426. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  22427. }
  22428. else {
  22429. multiMaterial.subMaterials.push(null);
  22430. }
  22431. }
  22432. return multiMaterial;
  22433. };
  22434. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  22435. if (!parsedMaterial.customType) {
  22436. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  22437. }
  22438. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  22439. return materialType.Parse(parsedMaterial, scene, rootUrl);
  22440. ;
  22441. };
  22442. Material._TriangleFillMode = 0;
  22443. Material._WireFrameFillMode = 1;
  22444. Material._PointFillMode = 2;
  22445. Material._ClockWiseSideOrientation = 0;
  22446. Material._CounterClockWiseSideOrientation = 1;
  22447. __decorate([
  22448. BABYLON.serialize()
  22449. ], Material.prototype, "id", void 0);
  22450. __decorate([
  22451. BABYLON.serialize()
  22452. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  22453. __decorate([
  22454. BABYLON.serialize()
  22455. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  22456. __decorate([
  22457. BABYLON.serialize()
  22458. ], Material.prototype, "state", void 0);
  22459. __decorate([
  22460. BABYLON.serialize()
  22461. ], Material.prototype, "alpha", void 0);
  22462. __decorate([
  22463. BABYLON.serialize()
  22464. ], Material.prototype, "backFaceCulling", void 0);
  22465. __decorate([
  22466. BABYLON.serialize()
  22467. ], Material.prototype, "sideOrientation", void 0);
  22468. __decorate([
  22469. BABYLON.serialize()
  22470. ], Material.prototype, "alphaMode", void 0);
  22471. __decorate([
  22472. BABYLON.serialize()
  22473. ], Material.prototype, "disableDepthWrite", void 0);
  22474. __decorate([
  22475. BABYLON.serialize()
  22476. ], Material.prototype, "fogEnabled", void 0);
  22477. __decorate([
  22478. BABYLON.serialize()
  22479. ], Material.prototype, "pointSize", void 0);
  22480. __decorate([
  22481. BABYLON.serialize()
  22482. ], Material.prototype, "zOffset", void 0);
  22483. __decorate([
  22484. BABYLON.serialize()
  22485. ], Material.prototype, "wireframe", null);
  22486. __decorate([
  22487. BABYLON.serialize()
  22488. ], Material.prototype, "pointsCloud", null);
  22489. __decorate([
  22490. BABYLON.serialize()
  22491. ], Material.prototype, "fillMode", null);
  22492. return Material;
  22493. })();
  22494. BABYLON.Material = Material;
  22495. })(BABYLON || (BABYLON = {}));
  22496. var BABYLON;
  22497. (function (BABYLON) {
  22498. var StandardMaterialDefines = (function (_super) {
  22499. __extends(StandardMaterialDefines, _super);
  22500. function StandardMaterialDefines() {
  22501. _super.call(this);
  22502. this.DIFFUSE = false;
  22503. this.AMBIENT = false;
  22504. this.OPACITY = false;
  22505. this.OPACITYRGB = false;
  22506. this.REFLECTION = false;
  22507. this.EMISSIVE = false;
  22508. this.SPECULAR = false;
  22509. this.BUMP = false;
  22510. this.PARALLAX = false;
  22511. this.PARALLAXOCCLUSION = false;
  22512. this.SPECULAROVERALPHA = false;
  22513. this.CLIPPLANE = false;
  22514. this.ALPHATEST = false;
  22515. this.ALPHAFROMDIFFUSE = false;
  22516. this.POINTSIZE = false;
  22517. this.FOG = false;
  22518. this.LIGHT0 = false;
  22519. this.LIGHT1 = false;
  22520. this.LIGHT2 = false;
  22521. this.LIGHT3 = false;
  22522. this.SPOTLIGHT0 = false;
  22523. this.SPOTLIGHT1 = false;
  22524. this.SPOTLIGHT2 = false;
  22525. this.SPOTLIGHT3 = false;
  22526. this.HEMILIGHT0 = false;
  22527. this.HEMILIGHT1 = false;
  22528. this.HEMILIGHT2 = false;
  22529. this.HEMILIGHT3 = false;
  22530. this.POINTLIGHT0 = false;
  22531. this.POINTLIGHT1 = false;
  22532. this.POINTLIGHT2 = false;
  22533. this.POINTLIGHT3 = false;
  22534. this.DIRLIGHT0 = false;
  22535. this.DIRLIGHT1 = false;
  22536. this.DIRLIGHT2 = false;
  22537. this.DIRLIGHT3 = false;
  22538. this.SPECULARTERM = false;
  22539. this.SHADOW0 = false;
  22540. this.SHADOW1 = false;
  22541. this.SHADOW2 = false;
  22542. this.SHADOW3 = false;
  22543. this.SHADOWS = false;
  22544. this.SHADOWVSM0 = false;
  22545. this.SHADOWVSM1 = false;
  22546. this.SHADOWVSM2 = false;
  22547. this.SHADOWVSM3 = false;
  22548. this.SHADOWPCF0 = false;
  22549. this.SHADOWPCF1 = false;
  22550. this.SHADOWPCF2 = false;
  22551. this.SHADOWPCF3 = false;
  22552. this.DIFFUSEFRESNEL = false;
  22553. this.OPACITYFRESNEL = false;
  22554. this.REFLECTIONFRESNEL = false;
  22555. this.REFRACTIONFRESNEL = false;
  22556. this.EMISSIVEFRESNEL = false;
  22557. this.FRESNEL = false;
  22558. this.NORMAL = false;
  22559. this.UV1 = false;
  22560. this.UV2 = false;
  22561. this.VERTEXCOLOR = false;
  22562. this.VERTEXALPHA = false;
  22563. this.NUM_BONE_INFLUENCERS = 0;
  22564. this.BonesPerMesh = 0;
  22565. this.INSTANCES = false;
  22566. this.GLOSSINESS = false;
  22567. this.ROUGHNESS = false;
  22568. this.EMISSIVEASILLUMINATION = false;
  22569. this.LINKEMISSIVEWITHDIFFUSE = false;
  22570. this.REFLECTIONFRESNELFROMSPECULAR = false;
  22571. this.LIGHTMAP = false;
  22572. this.USELIGHTMAPASSHADOWMAP = false;
  22573. this.REFLECTIONMAP_3D = false;
  22574. this.REFLECTIONMAP_SPHERICAL = false;
  22575. this.REFLECTIONMAP_PLANAR = false;
  22576. this.REFLECTIONMAP_CUBIC = false;
  22577. this.REFLECTIONMAP_PROJECTION = false;
  22578. this.REFLECTIONMAP_SKYBOX = false;
  22579. this.REFLECTIONMAP_EXPLICIT = false;
  22580. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  22581. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  22582. this.INVERTCUBICMAP = false;
  22583. this.LOGARITHMICDEPTH = false;
  22584. this.REFRACTION = false;
  22585. this.REFRACTIONMAP_3D = false;
  22586. this.REFLECTIONOVERALPHA = false;
  22587. this._keys = Object.keys(this);
  22588. }
  22589. return StandardMaterialDefines;
  22590. })(BABYLON.MaterialDefines);
  22591. var StandardMaterial = (function (_super) {
  22592. __extends(StandardMaterial, _super);
  22593. function StandardMaterial(name, scene) {
  22594. var _this = this;
  22595. _super.call(this, name, scene);
  22596. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  22597. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  22598. this.specularColor = new BABYLON.Color3(1, 1, 1);
  22599. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  22600. this.specularPower = 64;
  22601. this.useAlphaFromDiffuseTexture = false;
  22602. this.useEmissiveAsIllumination = false;
  22603. this.linkEmissiveWithDiffuse = false;
  22604. this.useReflectionFresnelFromSpecular = false;
  22605. this.useSpecularOverAlpha = false;
  22606. this.useReflectionOverAlpha = false;
  22607. this.disableLighting = false;
  22608. this.useParallax = false;
  22609. this.useParallaxOcclusion = false;
  22610. this.parallaxScaleBias = 0.05;
  22611. this.roughness = 0;
  22612. this.indexOfRefraction = 0.98;
  22613. this.invertRefractionY = true;
  22614. this.useLightmapAsShadowmap = false;
  22615. this.useGlossinessFromSpecularMapAlpha = false;
  22616. this._renderTargets = new BABYLON.SmartArray(16);
  22617. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  22618. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  22619. this._defines = new StandardMaterialDefines();
  22620. this._cachedDefines = new StandardMaterialDefines();
  22621. this._cachedDefines.BonesPerMesh = -1;
  22622. this.getRenderTargetTextures = function () {
  22623. _this._renderTargets.reset();
  22624. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  22625. _this._renderTargets.push(_this.reflectionTexture);
  22626. }
  22627. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  22628. _this._renderTargets.push(_this.refractionTexture);
  22629. }
  22630. return _this._renderTargets;
  22631. };
  22632. }
  22633. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  22634. get: function () {
  22635. return this._useLogarithmicDepth;
  22636. },
  22637. set: function (value) {
  22638. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  22639. },
  22640. enumerable: true,
  22641. configurable: true
  22642. });
  22643. StandardMaterial.prototype.needAlphaBlending = function () {
  22644. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  22645. };
  22646. StandardMaterial.prototype.needAlphaTesting = function () {
  22647. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  22648. };
  22649. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  22650. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  22651. };
  22652. StandardMaterial.prototype.getAlphaTestTexture = function () {
  22653. return this.diffuseTexture;
  22654. };
  22655. // Methods
  22656. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  22657. if (!mesh) {
  22658. return true;
  22659. }
  22660. if (this._defines.INSTANCES !== useInstances) {
  22661. return false;
  22662. }
  22663. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  22664. return true;
  22665. }
  22666. return false;
  22667. };
  22668. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  22669. if (this.isFrozen) {
  22670. if (this._wasPreviouslyReady) {
  22671. return true;
  22672. }
  22673. }
  22674. var scene = this.getScene();
  22675. if (!this.checkReadyOnEveryCall) {
  22676. if (this._renderId === scene.getRenderId()) {
  22677. if (this._checkCache(scene, mesh, useInstances)) {
  22678. return true;
  22679. }
  22680. }
  22681. }
  22682. var engine = scene.getEngine();
  22683. var needNormals = false;
  22684. var needUVs = false;
  22685. this._defines.reset();
  22686. // Textures
  22687. if (scene.texturesEnabled) {
  22688. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  22689. if (!this.diffuseTexture.isReady()) {
  22690. return false;
  22691. }
  22692. else {
  22693. needUVs = true;
  22694. this._defines.DIFFUSE = true;
  22695. }
  22696. }
  22697. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  22698. if (!this.ambientTexture.isReady()) {
  22699. return false;
  22700. }
  22701. else {
  22702. needUVs = true;
  22703. this._defines.AMBIENT = true;
  22704. }
  22705. }
  22706. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  22707. if (!this.opacityTexture.isReady()) {
  22708. return false;
  22709. }
  22710. else {
  22711. needUVs = true;
  22712. this._defines.OPACITY = true;
  22713. if (this.opacityTexture.getAlphaFromRGB) {
  22714. this._defines.OPACITYRGB = true;
  22715. }
  22716. }
  22717. }
  22718. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  22719. if (!this.reflectionTexture.isReady()) {
  22720. return false;
  22721. }
  22722. else {
  22723. needNormals = true;
  22724. this._defines.REFLECTION = true;
  22725. if (this.roughness > 0) {
  22726. this._defines.ROUGHNESS = true;
  22727. }
  22728. if (this.useReflectionOverAlpha) {
  22729. this._defines.REFLECTIONOVERALPHA = true;
  22730. }
  22731. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  22732. this._defines.INVERTCUBICMAP = true;
  22733. }
  22734. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  22735. switch (this.reflectionTexture.coordinatesMode) {
  22736. case BABYLON.Texture.CUBIC_MODE:
  22737. case BABYLON.Texture.INVCUBIC_MODE:
  22738. this._defines.REFLECTIONMAP_CUBIC = true;
  22739. break;
  22740. case BABYLON.Texture.EXPLICIT_MODE:
  22741. this._defines.REFLECTIONMAP_EXPLICIT = true;
  22742. break;
  22743. case BABYLON.Texture.PLANAR_MODE:
  22744. this._defines.REFLECTIONMAP_PLANAR = true;
  22745. break;
  22746. case BABYLON.Texture.PROJECTION_MODE:
  22747. this._defines.REFLECTIONMAP_PROJECTION = true;
  22748. break;
  22749. case BABYLON.Texture.SKYBOX_MODE:
  22750. this._defines.REFLECTIONMAP_SKYBOX = true;
  22751. break;
  22752. case BABYLON.Texture.SPHERICAL_MODE:
  22753. this._defines.REFLECTIONMAP_SPHERICAL = true;
  22754. break;
  22755. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  22756. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  22757. break;
  22758. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  22759. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  22760. break;
  22761. }
  22762. }
  22763. }
  22764. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  22765. if (!this.emissiveTexture.isReady()) {
  22766. return false;
  22767. }
  22768. else {
  22769. needUVs = true;
  22770. this._defines.EMISSIVE = true;
  22771. }
  22772. }
  22773. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  22774. if (!this.lightmapTexture.isReady()) {
  22775. return false;
  22776. }
  22777. else {
  22778. needUVs = true;
  22779. this._defines.LIGHTMAP = true;
  22780. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  22781. }
  22782. }
  22783. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  22784. if (!this.specularTexture.isReady()) {
  22785. return false;
  22786. }
  22787. else {
  22788. needUVs = true;
  22789. this._defines.SPECULAR = true;
  22790. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  22791. }
  22792. }
  22793. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  22794. if (!this.bumpTexture.isReady()) {
  22795. return false;
  22796. }
  22797. else {
  22798. needUVs = true;
  22799. this._defines.BUMP = true;
  22800. if (this.useParallax) {
  22801. this._defines.PARALLAX = true;
  22802. if (this.useParallaxOcclusion) {
  22803. this._defines.PARALLAXOCCLUSION = true;
  22804. }
  22805. }
  22806. }
  22807. }
  22808. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  22809. if (!this.refractionTexture.isReady()) {
  22810. return false;
  22811. }
  22812. else {
  22813. needUVs = true;
  22814. this._defines.REFRACTION = true;
  22815. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  22816. }
  22817. }
  22818. }
  22819. // Effect
  22820. if (scene.clipPlane) {
  22821. this._defines.CLIPPLANE = true;
  22822. }
  22823. if (engine.getAlphaTesting()) {
  22824. this._defines.ALPHATEST = true;
  22825. }
  22826. if (this._shouldUseAlphaFromDiffuseTexture()) {
  22827. this._defines.ALPHAFROMDIFFUSE = true;
  22828. }
  22829. if (this.useEmissiveAsIllumination) {
  22830. this._defines.EMISSIVEASILLUMINATION = true;
  22831. }
  22832. if (this.linkEmissiveWithDiffuse) {
  22833. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  22834. }
  22835. if (this.useLogarithmicDepth) {
  22836. this._defines.LOGARITHMICDEPTH = true;
  22837. }
  22838. // Point size
  22839. if (this.pointsCloud || scene.forcePointsCloud) {
  22840. this._defines.POINTSIZE = true;
  22841. }
  22842. // Fog
  22843. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  22844. this._defines.FOG = true;
  22845. }
  22846. if (scene.lightsEnabled && !this.disableLighting) {
  22847. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines);
  22848. }
  22849. if (StandardMaterial.FresnelEnabled) {
  22850. // Fresnel
  22851. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  22852. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  22853. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  22854. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  22855. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  22856. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  22857. this._defines.DIFFUSEFRESNEL = true;
  22858. }
  22859. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  22860. this._defines.OPACITYFRESNEL = true;
  22861. }
  22862. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  22863. this._defines.REFLECTIONFRESNEL = true;
  22864. if (this.useReflectionFresnelFromSpecular) {
  22865. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  22866. }
  22867. }
  22868. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  22869. this._defines.REFRACTIONFRESNEL = true;
  22870. }
  22871. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  22872. this._defines.EMISSIVEFRESNEL = true;
  22873. }
  22874. needNormals = true;
  22875. this._defines.FRESNEL = true;
  22876. }
  22877. }
  22878. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  22879. this._defines.SPECULAROVERALPHA = true;
  22880. }
  22881. // Attribs
  22882. if (mesh) {
  22883. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22884. this._defines.NORMAL = true;
  22885. }
  22886. if (needUVs) {
  22887. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22888. this._defines.UV1 = true;
  22889. }
  22890. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22891. this._defines.UV2 = true;
  22892. }
  22893. }
  22894. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22895. this._defines.VERTEXCOLOR = true;
  22896. if (mesh.hasVertexAlpha) {
  22897. this._defines.VERTEXALPHA = true;
  22898. }
  22899. }
  22900. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  22901. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  22902. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  22903. }
  22904. // Instances
  22905. if (useInstances) {
  22906. this._defines.INSTANCES = true;
  22907. }
  22908. }
  22909. // Get correct effect
  22910. if (!this._defines.isEqual(this._cachedDefines)) {
  22911. this._defines.cloneTo(this._cachedDefines);
  22912. scene.resetCachedMaterial();
  22913. // Fallbacks
  22914. var fallbacks = new BABYLON.EffectFallbacks();
  22915. if (this._defines.REFLECTION) {
  22916. fallbacks.addFallback(0, "REFLECTION");
  22917. }
  22918. if (this._defines.SPECULAR) {
  22919. fallbacks.addFallback(0, "SPECULAR");
  22920. }
  22921. if (this._defines.BUMP) {
  22922. fallbacks.addFallback(0, "BUMP");
  22923. }
  22924. if (this._defines.PARALLAX) {
  22925. fallbacks.addFallback(1, "PARALLAX");
  22926. }
  22927. if (this._defines.PARALLAXOCCLUSION) {
  22928. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  22929. }
  22930. if (this._defines.SPECULAROVERALPHA) {
  22931. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  22932. }
  22933. if (this._defines.FOG) {
  22934. fallbacks.addFallback(1, "FOG");
  22935. }
  22936. if (this._defines.POINTSIZE) {
  22937. fallbacks.addFallback(0, "POINTSIZE");
  22938. }
  22939. if (this._defines.LOGARITHMICDEPTH) {
  22940. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  22941. }
  22942. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  22943. if (this._defines.SPECULARTERM) {
  22944. fallbacks.addFallback(0, "SPECULARTERM");
  22945. }
  22946. if (this._defines.DIFFUSEFRESNEL) {
  22947. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  22948. }
  22949. if (this._defines.OPACITYFRESNEL) {
  22950. fallbacks.addFallback(2, "OPACITYFRESNEL");
  22951. }
  22952. if (this._defines.REFLECTIONFRESNEL) {
  22953. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  22954. }
  22955. if (this._defines.EMISSIVEFRESNEL) {
  22956. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  22957. }
  22958. if (this._defines.FRESNEL) {
  22959. fallbacks.addFallback(4, "FRESNEL");
  22960. }
  22961. //Attributes
  22962. var attribs = [BABYLON.VertexBuffer.PositionKind];
  22963. if (this._defines.NORMAL) {
  22964. attribs.push(BABYLON.VertexBuffer.NormalKind);
  22965. }
  22966. if (this._defines.UV1) {
  22967. attribs.push(BABYLON.VertexBuffer.UVKind);
  22968. }
  22969. if (this._defines.UV2) {
  22970. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  22971. }
  22972. if (this._defines.VERTEXCOLOR) {
  22973. attribs.push(BABYLON.VertexBuffer.ColorKind);
  22974. }
  22975. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  22976. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  22977. // Legacy browser patch
  22978. var shaderName = "default";
  22979. if (!scene.getEngine().getCaps().standardDerivatives) {
  22980. shaderName = "legacydefault";
  22981. }
  22982. var join = this._defines.toString();
  22983. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  22984. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  22985. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  22986. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  22987. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  22988. "vFogInfos", "vFogColor", "pointSize",
  22989. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  22990. "mBones",
  22991. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  22992. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  22993. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  22994. "logarithmicDepthConstant"
  22995. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  22996. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  22997. ], join, fallbacks, this.onCompiled, this.onError);
  22998. }
  22999. if (!this._effect.isReady()) {
  23000. return false;
  23001. }
  23002. this._renderId = scene.getRenderId();
  23003. this._wasPreviouslyReady = true;
  23004. if (mesh) {
  23005. if (!mesh._materialDefines) {
  23006. mesh._materialDefines = new StandardMaterialDefines();
  23007. }
  23008. this._defines.cloneTo(mesh._materialDefines);
  23009. }
  23010. return true;
  23011. };
  23012. StandardMaterial.prototype.unbind = function () {
  23013. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  23014. this._effect.setTexture("reflection2DSampler", null);
  23015. }
  23016. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  23017. this._effect.setTexture("refraction2DSampler", null);
  23018. }
  23019. _super.prototype.unbind.call(this);
  23020. };
  23021. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  23022. this._effect.setMatrix("world", world);
  23023. };
  23024. StandardMaterial.prototype.bind = function (world, mesh) {
  23025. var scene = this.getScene();
  23026. // Matrices
  23027. this.bindOnlyWorldMatrix(world);
  23028. // Bones
  23029. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  23030. if (scene.getCachedMaterial() !== this) {
  23031. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  23032. if (StandardMaterial.FresnelEnabled) {
  23033. // Fresnel
  23034. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  23035. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  23036. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  23037. }
  23038. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  23039. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  23040. }
  23041. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  23042. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  23043. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  23044. }
  23045. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  23046. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  23047. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  23048. }
  23049. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  23050. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  23051. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  23052. }
  23053. }
  23054. // Textures
  23055. if (scene.texturesEnabled) {
  23056. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  23057. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  23058. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  23059. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  23060. }
  23061. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  23062. this._effect.setTexture("ambientSampler", this.ambientTexture);
  23063. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  23064. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  23065. }
  23066. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  23067. this._effect.setTexture("opacitySampler", this.opacityTexture);
  23068. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  23069. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  23070. }
  23071. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  23072. if (this.reflectionTexture.isCube) {
  23073. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  23074. }
  23075. else {
  23076. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  23077. }
  23078. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  23079. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  23080. }
  23081. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  23082. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  23083. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  23084. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  23085. }
  23086. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  23087. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  23088. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  23089. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  23090. }
  23091. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  23092. this._effect.setTexture("specularSampler", this.specularTexture);
  23093. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  23094. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  23095. }
  23096. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  23097. this._effect.setTexture("bumpSampler", this.bumpTexture);
  23098. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  23099. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  23100. }
  23101. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  23102. var depth = 1.0;
  23103. if (this.refractionTexture.isCube) {
  23104. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  23105. }
  23106. else {
  23107. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  23108. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  23109. if (this.refractionTexture.depth) {
  23110. depth = this.refractionTexture.depth;
  23111. }
  23112. }
  23113. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  23114. }
  23115. }
  23116. // Clip plane
  23117. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  23118. // Point size
  23119. if (this.pointsCloud) {
  23120. this._effect.setFloat("pointSize", this.pointSize);
  23121. }
  23122. // Colors
  23123. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  23124. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  23125. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  23126. if (this._defines.SPECULARTERM) {
  23127. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  23128. }
  23129. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  23130. }
  23131. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  23132. // Diffuse
  23133. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  23134. // Lights
  23135. if (scene.lightsEnabled && !this.disableLighting) {
  23136. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines);
  23137. }
  23138. // View
  23139. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  23140. this._effect.setMatrix("view", scene.getViewMatrix());
  23141. }
  23142. // Fog
  23143. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  23144. // Log. depth
  23145. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  23146. }
  23147. _super.prototype.bind.call(this, world, mesh);
  23148. };
  23149. StandardMaterial.prototype.getAnimatables = function () {
  23150. var results = [];
  23151. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  23152. results.push(this.diffuseTexture);
  23153. }
  23154. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  23155. results.push(this.ambientTexture);
  23156. }
  23157. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  23158. results.push(this.opacityTexture);
  23159. }
  23160. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  23161. results.push(this.reflectionTexture);
  23162. }
  23163. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  23164. results.push(this.emissiveTexture);
  23165. }
  23166. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  23167. results.push(this.specularTexture);
  23168. }
  23169. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  23170. results.push(this.bumpTexture);
  23171. }
  23172. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  23173. results.push(this.lightmapTexture);
  23174. }
  23175. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  23176. results.push(this.refractionTexture);
  23177. }
  23178. return results;
  23179. };
  23180. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  23181. if (this.diffuseTexture) {
  23182. this.diffuseTexture.dispose();
  23183. }
  23184. if (this.ambientTexture) {
  23185. this.ambientTexture.dispose();
  23186. }
  23187. if (this.opacityTexture) {
  23188. this.opacityTexture.dispose();
  23189. }
  23190. if (this.reflectionTexture) {
  23191. this.reflectionTexture.dispose();
  23192. }
  23193. if (this.emissiveTexture) {
  23194. this.emissiveTexture.dispose();
  23195. }
  23196. if (this.specularTexture) {
  23197. this.specularTexture.dispose();
  23198. }
  23199. if (this.bumpTexture) {
  23200. this.bumpTexture.dispose();
  23201. }
  23202. if (this.lightmapTexture) {
  23203. this.lightmapTexture.dispose();
  23204. }
  23205. if (this.refractionTexture) {
  23206. this.refractionTexture.dispose();
  23207. }
  23208. _super.prototype.dispose.call(this, forceDisposeEffect);
  23209. };
  23210. StandardMaterial.prototype.clone = function (name) {
  23211. var _this = this;
  23212. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  23213. };
  23214. StandardMaterial.prototype.serialize = function () {
  23215. return BABYLON.SerializationHelper.Serialize(this);
  23216. };
  23217. // Statics
  23218. StandardMaterial.Parse = function (source, scene, rootUrl) {
  23219. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  23220. };
  23221. // Flags used to enable or disable a type of texture for all Standard Materials
  23222. StandardMaterial.DiffuseTextureEnabled = true;
  23223. StandardMaterial.AmbientTextureEnabled = true;
  23224. StandardMaterial.OpacityTextureEnabled = true;
  23225. StandardMaterial.ReflectionTextureEnabled = true;
  23226. StandardMaterial.EmissiveTextureEnabled = true;
  23227. StandardMaterial.SpecularTextureEnabled = true;
  23228. StandardMaterial.BumpTextureEnabled = true;
  23229. StandardMaterial.FresnelEnabled = true;
  23230. StandardMaterial.LightmapTextureEnabled = true;
  23231. StandardMaterial.RefractionTextureEnabled = true;
  23232. __decorate([
  23233. BABYLON.serializeAsTexture()
  23234. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  23235. __decorate([
  23236. BABYLON.serializeAsTexture()
  23237. ], StandardMaterial.prototype, "ambientTexture", void 0);
  23238. __decorate([
  23239. BABYLON.serializeAsTexture()
  23240. ], StandardMaterial.prototype, "opacityTexture", void 0);
  23241. __decorate([
  23242. BABYLON.serializeAsTexture()
  23243. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  23244. __decorate([
  23245. BABYLON.serializeAsTexture()
  23246. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  23247. __decorate([
  23248. BABYLON.serializeAsTexture()
  23249. ], StandardMaterial.prototype, "specularTexture", void 0);
  23250. __decorate([
  23251. BABYLON.serializeAsTexture()
  23252. ], StandardMaterial.prototype, "bumpTexture", void 0);
  23253. __decorate([
  23254. BABYLON.serializeAsTexture()
  23255. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  23256. __decorate([
  23257. BABYLON.serializeAsTexture()
  23258. ], StandardMaterial.prototype, "refractionTexture", void 0);
  23259. __decorate([
  23260. BABYLON.serializeAsColor3("ambient")
  23261. ], StandardMaterial.prototype, "ambientColor", void 0);
  23262. __decorate([
  23263. BABYLON.serializeAsColor3("diffuse")
  23264. ], StandardMaterial.prototype, "diffuseColor", void 0);
  23265. __decorate([
  23266. BABYLON.serializeAsColor3("specular")
  23267. ], StandardMaterial.prototype, "specularColor", void 0);
  23268. __decorate([
  23269. BABYLON.serializeAsColor3("emissive")
  23270. ], StandardMaterial.prototype, "emissiveColor", void 0);
  23271. __decorate([
  23272. BABYLON.serialize()
  23273. ], StandardMaterial.prototype, "specularPower", void 0);
  23274. __decorate([
  23275. BABYLON.serialize()
  23276. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  23277. __decorate([
  23278. BABYLON.serialize()
  23279. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  23280. __decorate([
  23281. BABYLON.serialize()
  23282. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  23283. __decorate([
  23284. BABYLON.serialize()
  23285. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  23286. __decorate([
  23287. BABYLON.serialize()
  23288. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  23289. __decorate([
  23290. BABYLON.serialize()
  23291. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  23292. __decorate([
  23293. BABYLON.serialize()
  23294. ], StandardMaterial.prototype, "disableLighting", void 0);
  23295. __decorate([
  23296. BABYLON.serialize()
  23297. ], StandardMaterial.prototype, "useParallax", void 0);
  23298. __decorate([
  23299. BABYLON.serialize()
  23300. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  23301. __decorate([
  23302. BABYLON.serialize()
  23303. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  23304. __decorate([
  23305. BABYLON.serialize()
  23306. ], StandardMaterial.prototype, "roughness", void 0);
  23307. __decorate([
  23308. BABYLON.serialize()
  23309. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  23310. __decorate([
  23311. BABYLON.serialize()
  23312. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  23313. __decorate([
  23314. BABYLON.serialize()
  23315. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  23316. __decorate([
  23317. BABYLON.serializeAsFresnelParameters()
  23318. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  23319. __decorate([
  23320. BABYLON.serializeAsFresnelParameters()
  23321. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  23322. __decorate([
  23323. BABYLON.serializeAsFresnelParameters()
  23324. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  23325. __decorate([
  23326. BABYLON.serializeAsFresnelParameters()
  23327. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  23328. __decorate([
  23329. BABYLON.serializeAsFresnelParameters()
  23330. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  23331. __decorate([
  23332. BABYLON.serialize()
  23333. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  23334. __decorate([
  23335. BABYLON.serialize()
  23336. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  23337. return StandardMaterial;
  23338. })(BABYLON.Material);
  23339. BABYLON.StandardMaterial = StandardMaterial;
  23340. })(BABYLON || (BABYLON = {}));
  23341. var BABYLON;
  23342. (function (BABYLON) {
  23343. var MultiMaterial = (function (_super) {
  23344. __extends(MultiMaterial, _super);
  23345. function MultiMaterial(name, scene) {
  23346. _super.call(this, name, scene, true);
  23347. this.subMaterials = new Array();
  23348. scene.multiMaterials.push(this);
  23349. }
  23350. // Properties
  23351. MultiMaterial.prototype.getSubMaterial = function (index) {
  23352. if (index < 0 || index >= this.subMaterials.length) {
  23353. return this.getScene().defaultMaterial;
  23354. }
  23355. return this.subMaterials[index];
  23356. };
  23357. // Methods
  23358. MultiMaterial.prototype.isReady = function (mesh) {
  23359. for (var index = 0; index < this.subMaterials.length; index++) {
  23360. var subMaterial = this.subMaterials[index];
  23361. if (subMaterial) {
  23362. if (!this.subMaterials[index].isReady(mesh)) {
  23363. return false;
  23364. }
  23365. }
  23366. }
  23367. return true;
  23368. };
  23369. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  23370. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  23371. for (var index = 0; index < this.subMaterials.length; index++) {
  23372. var subMaterial = null;
  23373. if (cloneChildren) {
  23374. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  23375. }
  23376. else {
  23377. subMaterial = this.subMaterials[index];
  23378. }
  23379. newMultiMaterial.subMaterials.push(subMaterial);
  23380. }
  23381. return newMultiMaterial;
  23382. };
  23383. MultiMaterial.prototype.serialize = function () {
  23384. var serializationObject = {};
  23385. serializationObject.name = this.name;
  23386. serializationObject.id = this.id;
  23387. serializationObject.tags = BABYLON.Tags.GetTags(this);
  23388. serializationObject.materials = [];
  23389. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  23390. var subMat = this.subMaterials[matIndex];
  23391. if (subMat) {
  23392. serializationObject.materials.push(subMat.id);
  23393. }
  23394. else {
  23395. serializationObject.materials.push(null);
  23396. }
  23397. }
  23398. return serializationObject;
  23399. };
  23400. return MultiMaterial;
  23401. })(BABYLON.Material);
  23402. BABYLON.MultiMaterial = MultiMaterial;
  23403. })(BABYLON || (BABYLON = {}));
  23404. var BABYLON;
  23405. (function (BABYLON) {
  23406. var SceneLoader = (function () {
  23407. function SceneLoader() {
  23408. }
  23409. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  23410. get: function () {
  23411. return 0;
  23412. },
  23413. enumerable: true,
  23414. configurable: true
  23415. });
  23416. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  23417. get: function () {
  23418. return 1;
  23419. },
  23420. enumerable: true,
  23421. configurable: true
  23422. });
  23423. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  23424. get: function () {
  23425. return 2;
  23426. },
  23427. enumerable: true,
  23428. configurable: true
  23429. });
  23430. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  23431. get: function () {
  23432. return 3;
  23433. },
  23434. enumerable: true,
  23435. configurable: true
  23436. });
  23437. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  23438. get: function () {
  23439. return SceneLoader._ForceFullSceneLoadingForIncremental;
  23440. },
  23441. set: function (value) {
  23442. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  23443. },
  23444. enumerable: true,
  23445. configurable: true
  23446. });
  23447. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  23448. get: function () {
  23449. return SceneLoader._ShowLoadingScreen;
  23450. },
  23451. set: function (value) {
  23452. SceneLoader._ShowLoadingScreen = value;
  23453. },
  23454. enumerable: true,
  23455. configurable: true
  23456. });
  23457. Object.defineProperty(SceneLoader, "loggingLevel", {
  23458. get: function () {
  23459. return SceneLoader._loggingLevel;
  23460. },
  23461. set: function (value) {
  23462. SceneLoader._loggingLevel = value;
  23463. },
  23464. enumerable: true,
  23465. configurable: true
  23466. });
  23467. SceneLoader._getPluginForFilename = function (sceneFilename) {
  23468. var dotPosition = sceneFilename.lastIndexOf(".");
  23469. var queryStringPosition = sceneFilename.indexOf("?");
  23470. if (queryStringPosition === -1) {
  23471. queryStringPosition = sceneFilename.length;
  23472. }
  23473. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  23474. for (var index = 0; index < this._registeredPlugins.length; index++) {
  23475. var plugin = this._registeredPlugins[index];
  23476. if (plugin.extensions.indexOf(extension) !== -1) {
  23477. return plugin;
  23478. }
  23479. }
  23480. return this._registeredPlugins[this._registeredPlugins.length - 1];
  23481. };
  23482. // Public functions
  23483. SceneLoader.GetPluginForExtension = function (extension) {
  23484. for (var index = 0; index < this._registeredPlugins.length; index++) {
  23485. var plugin = this._registeredPlugins[index];
  23486. if (plugin.extensions.indexOf(extension) !== -1) {
  23487. return plugin;
  23488. }
  23489. }
  23490. return null;
  23491. };
  23492. SceneLoader.RegisterPlugin = function (plugin) {
  23493. plugin.extensions = plugin.extensions.toLowerCase();
  23494. SceneLoader._registeredPlugins.push(plugin);
  23495. };
  23496. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  23497. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  23498. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  23499. return;
  23500. }
  23501. var loadingToken = {};
  23502. scene._addPendingData(loadingToken);
  23503. var manifestChecked = function (success) {
  23504. scene.database = database;
  23505. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  23506. var importMeshFromData = function (data) {
  23507. var meshes = [];
  23508. var particleSystems = [];
  23509. var skeletons = [];
  23510. try {
  23511. if (plugin.importMesh) {
  23512. var syncedPlugin = plugin;
  23513. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  23514. if (onerror) {
  23515. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  23516. }
  23517. scene._removePendingData(loadingToken);
  23518. return;
  23519. }
  23520. if (onsuccess) {
  23521. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  23522. onsuccess(meshes, particleSystems, skeletons);
  23523. scene._removePendingData(loadingToken);
  23524. }
  23525. }
  23526. else {
  23527. var asyncedPlugin = plugin;
  23528. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  23529. if (onsuccess) {
  23530. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  23531. onsuccess(meshes, particleSystems, skeletons);
  23532. scene._removePendingData(loadingToken);
  23533. }
  23534. }, function () {
  23535. if (onerror) {
  23536. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  23537. }
  23538. scene._removePendingData(loadingToken);
  23539. });
  23540. }
  23541. }
  23542. catch (e) {
  23543. if (onerror) {
  23544. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename + ' (Exception: ' + e + ')');
  23545. }
  23546. scene._removePendingData(loadingToken);
  23547. }
  23548. };
  23549. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  23550. // Direct load
  23551. importMeshFromData(sceneFilename.substr(5));
  23552. return;
  23553. }
  23554. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  23555. importMeshFromData(data);
  23556. }, progressCallBack, database);
  23557. };
  23558. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  23559. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  23560. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  23561. }
  23562. else {
  23563. // If the scene is a data stream or offline support is not enabled, it's a direct load
  23564. manifestChecked(true);
  23565. }
  23566. };
  23567. /**
  23568. * Load a scene
  23569. * @param rootUrl a string that defines the root url for scene and resources
  23570. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  23571. * @param engine is the instance of BABYLON.Engine to use to create the scene
  23572. */
  23573. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  23574. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  23575. };
  23576. /**
  23577. * Append a scene
  23578. * @param rootUrl a string that defines the root url for scene and resources
  23579. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  23580. * @param scene is the instance of BABYLON.Scene to append to
  23581. */
  23582. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  23583. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  23584. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  23585. return;
  23586. }
  23587. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  23588. var database;
  23589. var loadingToken = {};
  23590. scene._addPendingData(loadingToken);
  23591. if (SceneLoader.ShowLoadingScreen) {
  23592. scene.getEngine().displayLoadingUI();
  23593. }
  23594. var loadSceneFromData = function (data) {
  23595. scene.database = database;
  23596. if (plugin.load) {
  23597. var syncedPlugin = plugin;
  23598. if (!syncedPlugin.load(scene, data, rootUrl)) {
  23599. if (onerror) {
  23600. onerror(scene);
  23601. }
  23602. scene._removePendingData(loadingToken);
  23603. scene.getEngine().hideLoadingUI();
  23604. return;
  23605. }
  23606. if (onsuccess) {
  23607. onsuccess(scene);
  23608. }
  23609. scene._removePendingData(loadingToken);
  23610. }
  23611. else {
  23612. var asyncedPlugin = plugin;
  23613. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  23614. if (onsuccess) {
  23615. onsuccess(scene);
  23616. }
  23617. }, function () {
  23618. if (onerror) {
  23619. onerror(scene);
  23620. }
  23621. scene._removePendingData(loadingToken);
  23622. scene.getEngine().hideLoadingUI();
  23623. });
  23624. }
  23625. if (SceneLoader.ShowLoadingScreen) {
  23626. scene.executeWhenReady(function () {
  23627. scene.getEngine().hideLoadingUI();
  23628. });
  23629. }
  23630. };
  23631. var manifestChecked = function (success) {
  23632. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  23633. };
  23634. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  23635. // Direct load
  23636. loadSceneFromData(sceneFilename.substr(5));
  23637. return;
  23638. }
  23639. if (rootUrl.indexOf("file:") === -1) {
  23640. if (scene.getEngine().enableOfflineSupport) {
  23641. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  23642. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  23643. }
  23644. else {
  23645. manifestChecked(true);
  23646. }
  23647. }
  23648. else {
  23649. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  23650. }
  23651. };
  23652. // Flags
  23653. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  23654. SceneLoader._ShowLoadingScreen = true;
  23655. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  23656. // Members
  23657. SceneLoader._registeredPlugins = new Array();
  23658. return SceneLoader;
  23659. })();
  23660. BABYLON.SceneLoader = SceneLoader;
  23661. ;
  23662. })(BABYLON || (BABYLON = {}));
  23663. var BABYLON;
  23664. (function (BABYLON) {
  23665. var Internals;
  23666. (function (Internals) {
  23667. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  23668. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  23669. var parsedMaterial = parsedData.materials[index];
  23670. if (parsedMaterial.id === id) {
  23671. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  23672. }
  23673. }
  23674. return null;
  23675. };
  23676. var isDescendantOf = function (mesh, names, hierarchyIds) {
  23677. names = (names instanceof Array) ? names : [names];
  23678. for (var i in names) {
  23679. if (mesh.name === names[i]) {
  23680. hierarchyIds.push(mesh.id);
  23681. return true;
  23682. }
  23683. }
  23684. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  23685. hierarchyIds.push(mesh.id);
  23686. return true;
  23687. }
  23688. return false;
  23689. };
  23690. var logOperation = function (operation, producer) {
  23691. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  23692. };
  23693. BABYLON.SceneLoader.RegisterPlugin({
  23694. extensions: ".babylon",
  23695. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  23696. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  23697. // when SceneLoader.debugLogging = true (default), or exception encountered.
  23698. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  23699. // and avoid problems with multiple concurrent .babylon loads.
  23700. var log = "importMesh has failed JSON parse";
  23701. try {
  23702. var parsedData = JSON.parse(data);
  23703. log = "";
  23704. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  23705. var loadedSkeletonsIds = [];
  23706. var loadedMaterialsIds = [];
  23707. var hierarchyIds = [];
  23708. var index;
  23709. var cache;
  23710. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  23711. var parsedMesh = parsedData.meshes[index];
  23712. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  23713. if (meshesNames instanceof Array) {
  23714. // Remove found mesh name from list.
  23715. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  23716. }
  23717. //Geometry?
  23718. if (parsedMesh.geometryId) {
  23719. //does the file contain geometries?
  23720. if (parsedData.geometries) {
  23721. //find the correct geometry and add it to the scene
  23722. var found = false;
  23723. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  23724. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  23725. return;
  23726. }
  23727. else {
  23728. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  23729. if (parsedGeometryData.id === parsedMesh.geometryId) {
  23730. switch (geometryType) {
  23731. case "boxes":
  23732. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  23733. break;
  23734. case "spheres":
  23735. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  23736. break;
  23737. case "cylinders":
  23738. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  23739. break;
  23740. case "toruses":
  23741. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  23742. break;
  23743. case "grounds":
  23744. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  23745. break;
  23746. case "planes":
  23747. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  23748. break;
  23749. case "torusKnots":
  23750. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  23751. break;
  23752. case "vertexData":
  23753. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  23754. break;
  23755. }
  23756. found = true;
  23757. }
  23758. });
  23759. }
  23760. });
  23761. if (!found) {
  23762. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  23763. }
  23764. }
  23765. }
  23766. // Material ?
  23767. if (parsedMesh.materialId) {
  23768. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  23769. if (!materialFound && parsedData.multiMaterials) {
  23770. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  23771. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  23772. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  23773. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  23774. var subMatId = parsedMultiMaterial.materials[matIndex];
  23775. loadedMaterialsIds.push(subMatId);
  23776. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  23777. log += "\n\tMaterial " + mat.toString(fullDetails);
  23778. }
  23779. loadedMaterialsIds.push(parsedMultiMaterial.id);
  23780. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  23781. materialFound = true;
  23782. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  23783. break;
  23784. }
  23785. }
  23786. }
  23787. if (!materialFound) {
  23788. loadedMaterialsIds.push(parsedMesh.materialId);
  23789. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  23790. if (!mat) {
  23791. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  23792. }
  23793. else {
  23794. log += "\n\tMaterial " + mat.toString(fullDetails);
  23795. }
  23796. }
  23797. }
  23798. // Skeleton ?
  23799. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  23800. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  23801. if (!skeletonAlreadyLoaded) {
  23802. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  23803. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  23804. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  23805. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  23806. skeletons.push(skeleton);
  23807. loadedSkeletonsIds.push(parsedSkeleton.id);
  23808. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  23809. }
  23810. }
  23811. }
  23812. }
  23813. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  23814. meshes.push(mesh);
  23815. log += "\n\tMesh " + mesh.toString(fullDetails);
  23816. }
  23817. }
  23818. // Connecting parents
  23819. var currentMesh;
  23820. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  23821. currentMesh = scene.meshes[index];
  23822. if (currentMesh._waitingParentId) {
  23823. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  23824. currentMesh._waitingParentId = undefined;
  23825. }
  23826. }
  23827. // freeze and compute world matrix application
  23828. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  23829. currentMesh = scene.meshes[index];
  23830. if (currentMesh._waitingFreezeWorldMatrix) {
  23831. currentMesh.freezeWorldMatrix();
  23832. currentMesh._waitingFreezeWorldMatrix = undefined;
  23833. }
  23834. else {
  23835. currentMesh.computeWorldMatrix(true);
  23836. }
  23837. }
  23838. // Particles
  23839. if (parsedData.particleSystems) {
  23840. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  23841. var parsedParticleSystem = parsedData.particleSystems[index];
  23842. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  23843. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  23844. }
  23845. }
  23846. }
  23847. return true;
  23848. }
  23849. catch (err) {
  23850. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + log);
  23851. log = null;
  23852. throw err;
  23853. }
  23854. finally {
  23855. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  23856. BABYLON.Tools.Log(logOperation("importMesh", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  23857. }
  23858. }
  23859. },
  23860. load: function (scene, data, rootUrl) {
  23861. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  23862. // when SceneLoader.debugLogging = true (default), or exception encountered.
  23863. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  23864. // and avoid problems with multiple concurrent .babylon loads.
  23865. var log = "importScene has failed JSON parse";
  23866. try {
  23867. var parsedData = JSON.parse(data);
  23868. log = "";
  23869. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  23870. // Scene
  23871. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  23872. scene.autoClear = parsedData.autoClear;
  23873. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  23874. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  23875. if (parsedData.gravity) {
  23876. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  23877. }
  23878. // Fog
  23879. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  23880. scene.fogMode = parsedData.fogMode;
  23881. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  23882. scene.fogStart = parsedData.fogStart;
  23883. scene.fogEnd = parsedData.fogEnd;
  23884. scene.fogDensity = parsedData.fogDensity;
  23885. log += "\tFog mode for scene: ";
  23886. switch (scene.fogMode) {
  23887. // getters not compiling, so using hardcoded
  23888. case 1:
  23889. log += "exp\n";
  23890. break;
  23891. case 2:
  23892. log += "exp2\n";
  23893. break;
  23894. case 3:
  23895. log += "linear\n";
  23896. break;
  23897. }
  23898. }
  23899. //Physics
  23900. if (parsedData.physicsEnabled) {
  23901. var physicsPlugin;
  23902. if (parsedData.physicsEngine === "cannon") {
  23903. physicsPlugin = new BABYLON.CannonJSPlugin();
  23904. }
  23905. else if (parsedData.physicsEngine === "oimo") {
  23906. physicsPlugin = new BABYLON.OimoJSPlugin();
  23907. }
  23908. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  23909. //else - default engine, which is currently oimo
  23910. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  23911. scene.enablePhysics(physicsGravity, physicsPlugin);
  23912. }
  23913. //collisions, if defined. otherwise, default is true
  23914. if (parsedData.collisionsEnabled != undefined) {
  23915. scene.collisionsEnabled = parsedData.collisionsEnabled;
  23916. }
  23917. scene.workerCollisions = !!parsedData.workerCollisions;
  23918. var index;
  23919. var cache;
  23920. // Lights
  23921. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  23922. var parsedLight = parsedData.lights[index];
  23923. var light = BABYLON.Light.Parse(parsedLight, scene);
  23924. log += (index === 0 ? "\n\tLights:" : "");
  23925. log += "\n\t\t" + light.toString(fullDetails);
  23926. }
  23927. // Animations
  23928. if (parsedData.animations) {
  23929. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  23930. var parsedAnimation = parsedData.animations[index];
  23931. var animation = BABYLON.Animation.Parse(parsedAnimation);
  23932. scene.animations.push(animation);
  23933. log += (index === 0 ? "\n\tAnimations:" : "");
  23934. log += "\n\t\t" + animation.toString(fullDetails);
  23935. }
  23936. }
  23937. // Materials
  23938. if (parsedData.materials) {
  23939. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  23940. var parsedMaterial = parsedData.materials[index];
  23941. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  23942. log += (index === 0 ? "\n\tMaterials:" : "");
  23943. log += "\n\t\t" + mat.toString(fullDetails);
  23944. }
  23945. }
  23946. if (parsedData.multiMaterials) {
  23947. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  23948. var parsedMultiMaterial = parsedData.multiMaterials[index];
  23949. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  23950. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  23951. log += "\n\t\t" + mmat.toString(fullDetails);
  23952. }
  23953. }
  23954. // Skeletons
  23955. if (parsedData.skeletons) {
  23956. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  23957. var parsedSkeleton = parsedData.skeletons[index];
  23958. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  23959. log += (index === 0 ? "\n\tSkeletons:" : "");
  23960. log += "\n\t\t" + skeleton.toString(fullDetails);
  23961. }
  23962. }
  23963. // Geometries
  23964. var geometries = parsedData.geometries;
  23965. if (geometries) {
  23966. // Boxes
  23967. var boxes = geometries.boxes;
  23968. if (boxes) {
  23969. for (index = 0, cache = boxes.length; index < cache; index++) {
  23970. var parsedBox = boxes[index];
  23971. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  23972. }
  23973. }
  23974. // Spheres
  23975. var spheres = geometries.spheres;
  23976. if (spheres) {
  23977. for (index = 0, cache = spheres.length; index < cache; index++) {
  23978. var parsedSphere = spheres[index];
  23979. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  23980. }
  23981. }
  23982. // Cylinders
  23983. var cylinders = geometries.cylinders;
  23984. if (cylinders) {
  23985. for (index = 0, cache = cylinders.length; index < cache; index++) {
  23986. var parsedCylinder = cylinders[index];
  23987. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  23988. }
  23989. }
  23990. // Toruses
  23991. var toruses = geometries.toruses;
  23992. if (toruses) {
  23993. for (index = 0, cache = toruses.length; index < cache; index++) {
  23994. var parsedTorus = toruses[index];
  23995. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  23996. }
  23997. }
  23998. // Grounds
  23999. var grounds = geometries.grounds;
  24000. if (grounds) {
  24001. for (index = 0, cache = grounds.length; index < cache; index++) {
  24002. var parsedGround = grounds[index];
  24003. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  24004. }
  24005. }
  24006. // Planes
  24007. var planes = geometries.planes;
  24008. if (planes) {
  24009. for (index = 0, cache = planes.length; index < cache; index++) {
  24010. var parsedPlane = planes[index];
  24011. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  24012. }
  24013. }
  24014. // TorusKnots
  24015. var torusKnots = geometries.torusKnots;
  24016. if (torusKnots) {
  24017. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  24018. var parsedTorusKnot = torusKnots[index];
  24019. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  24020. }
  24021. }
  24022. // VertexData
  24023. var vertexData = geometries.vertexData;
  24024. if (vertexData) {
  24025. for (index = 0, cache = vertexData.length; index < cache; index++) {
  24026. var parsedVertexData = vertexData[index];
  24027. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  24028. }
  24029. }
  24030. }
  24031. // Meshes
  24032. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  24033. var parsedMesh = parsedData.meshes[index];
  24034. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  24035. log += (index === 0 ? "\n\tMeshes:" : "");
  24036. log += "\n\t\t" + mesh.toString(fullDetails);
  24037. }
  24038. // Cameras
  24039. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  24040. var parsedCamera = parsedData.cameras[index];
  24041. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  24042. log += (index === 0 ? "\n\tCameras:" : "");
  24043. log += "\n\t\t" + camera.toString(fullDetails);
  24044. }
  24045. if (parsedData.activeCameraID) {
  24046. scene.setActiveCameraByID(parsedData.activeCameraID);
  24047. }
  24048. // Browsing all the graph to connect the dots
  24049. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  24050. var camera = scene.cameras[index];
  24051. if (camera._waitingParentId) {
  24052. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  24053. camera._waitingParentId = undefined;
  24054. }
  24055. }
  24056. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  24057. var light = scene.lights[index];
  24058. if (light._waitingParentId) {
  24059. light.parent = scene.getLastEntryByID(light._waitingParentId);
  24060. light._waitingParentId = undefined;
  24061. }
  24062. }
  24063. // Sounds
  24064. var loadedSounds = [];
  24065. var loadedSound;
  24066. if (BABYLON.AudioEngine && parsedData.sounds) {
  24067. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  24068. var parsedSound = parsedData.sounds[index];
  24069. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  24070. if (!parsedSound.url)
  24071. parsedSound.url = parsedSound.name;
  24072. if (!loadedSounds[parsedSound.url]) {
  24073. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  24074. loadedSounds[parsedSound.url] = loadedSound;
  24075. }
  24076. else {
  24077. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  24078. }
  24079. }
  24080. else {
  24081. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  24082. }
  24083. }
  24084. }
  24085. loadedSounds = [];
  24086. // Connect parents & children and parse actions
  24087. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24088. var mesh = scene.meshes[index];
  24089. if (mesh._waitingParentId) {
  24090. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  24091. mesh._waitingParentId = undefined;
  24092. }
  24093. if (mesh._waitingActions) {
  24094. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  24095. mesh._waitingActions = undefined;
  24096. }
  24097. }
  24098. // freeze world matrix application
  24099. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  24100. var currentMesh = scene.meshes[index];
  24101. if (currentMesh._waitingFreezeWorldMatrix) {
  24102. currentMesh.freezeWorldMatrix();
  24103. currentMesh._waitingFreezeWorldMatrix = undefined;
  24104. }
  24105. else {
  24106. currentMesh.computeWorldMatrix(true);
  24107. }
  24108. }
  24109. // Particles Systems
  24110. if (parsedData.particleSystems) {
  24111. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  24112. var parsedParticleSystem = parsedData.particleSystems[index];
  24113. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  24114. }
  24115. }
  24116. // Lens flares
  24117. if (parsedData.lensFlareSystems) {
  24118. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  24119. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  24120. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  24121. }
  24122. }
  24123. // Shadows
  24124. if (parsedData.shadowGenerators) {
  24125. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  24126. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  24127. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  24128. }
  24129. }
  24130. // Actions (scene)
  24131. if (parsedData.actions) {
  24132. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  24133. }
  24134. // Finish
  24135. return true;
  24136. }
  24137. catch (err) {
  24138. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + log);
  24139. log = null;
  24140. throw err;
  24141. }
  24142. finally {
  24143. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  24144. BABYLON.Tools.Log(logOperation("importScene", parsedData.producer) + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  24145. }
  24146. }
  24147. }
  24148. });
  24149. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24150. })(BABYLON || (BABYLON = {}));
  24151. var BABYLON;
  24152. (function (BABYLON) {
  24153. var SpriteManager = (function () {
  24154. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  24155. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24156. this.name = name;
  24157. this.cellSize = cellSize;
  24158. this.sprites = new Array();
  24159. this.renderingGroupId = 0;
  24160. this.layerMask = 0x0FFFFFFF;
  24161. this.fogEnabled = true;
  24162. this.isPickable = false;
  24163. this._vertexDeclaration = [4, 4, 4, 4];
  24164. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  24165. this._capacity = capacity;
  24166. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  24167. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24168. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24169. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  24170. this._scene = scene;
  24171. this._scene.spriteManagers.push(this);
  24172. // VBO
  24173. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  24174. var indices = [];
  24175. var index = 0;
  24176. for (var count = 0; count < capacity; count++) {
  24177. indices.push(index);
  24178. indices.push(index + 1);
  24179. indices.push(index + 2);
  24180. indices.push(index);
  24181. indices.push(index + 2);
  24182. indices.push(index + 3);
  24183. index += 4;
  24184. }
  24185. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24186. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  24187. // Effects
  24188. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  24189. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  24190. }
  24191. Object.defineProperty(SpriteManager.prototype, "texture", {
  24192. get: function () {
  24193. return this._spriteTexture;
  24194. },
  24195. set: function (value) {
  24196. this._spriteTexture = value;
  24197. },
  24198. enumerable: true,
  24199. configurable: true
  24200. });
  24201. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  24202. var arrayOffset = index * 16;
  24203. if (offsetX === 0)
  24204. offsetX = this._epsilon;
  24205. else if (offsetX === 1)
  24206. offsetX = 1 - this._epsilon;
  24207. if (offsetY === 0)
  24208. offsetY = this._epsilon;
  24209. else if (offsetY === 1)
  24210. offsetY = 1 - this._epsilon;
  24211. this._vertices[arrayOffset] = sprite.position.x;
  24212. this._vertices[arrayOffset + 1] = sprite.position.y;
  24213. this._vertices[arrayOffset + 2] = sprite.position.z;
  24214. this._vertices[arrayOffset + 3] = sprite.angle;
  24215. this._vertices[arrayOffset + 4] = sprite.width;
  24216. this._vertices[arrayOffset + 5] = sprite.height;
  24217. this._vertices[arrayOffset + 6] = offsetX;
  24218. this._vertices[arrayOffset + 7] = offsetY;
  24219. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  24220. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  24221. var offset = (sprite.cellIndex / rowSize) >> 0;
  24222. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  24223. this._vertices[arrayOffset + 11] = offset;
  24224. // Color
  24225. this._vertices[arrayOffset + 12] = sprite.color.r;
  24226. this._vertices[arrayOffset + 13] = sprite.color.g;
  24227. this._vertices[arrayOffset + 14] = sprite.color.b;
  24228. this._vertices[arrayOffset + 15] = sprite.color.a;
  24229. };
  24230. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  24231. var count = Math.min(this._capacity, this.sprites.length);
  24232. var min = BABYLON.Vector3.Zero();
  24233. var max = BABYLON.Vector3.Zero();
  24234. var distance = Number.MAX_VALUE;
  24235. var currentSprite;
  24236. var cameraSpacePosition = BABYLON.Vector3.Zero();
  24237. var cameraView = camera.getViewMatrix();
  24238. for (var index = 0; index < count; index++) {
  24239. var sprite = this.sprites[index];
  24240. if (!sprite) {
  24241. continue;
  24242. }
  24243. if (predicate) {
  24244. if (!predicate(sprite)) {
  24245. continue;
  24246. }
  24247. }
  24248. else if (!sprite.isPickable) {
  24249. continue;
  24250. }
  24251. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  24252. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  24253. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  24254. if (ray.intersectsBoxMinMax(min, max)) {
  24255. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  24256. if (distance > currentDistance) {
  24257. distance = currentDistance;
  24258. currentSprite = sprite;
  24259. if (fastCheck) {
  24260. break;
  24261. }
  24262. }
  24263. }
  24264. }
  24265. if (currentSprite) {
  24266. var result = new BABYLON.PickingInfo();
  24267. result.hit = true;
  24268. result.pickedSprite = currentSprite;
  24269. result.distance = distance;
  24270. return result;
  24271. }
  24272. return null;
  24273. };
  24274. SpriteManager.prototype.render = function () {
  24275. // Check
  24276. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  24277. return;
  24278. var engine = this._scene.getEngine();
  24279. var baseSize = this._spriteTexture.getBaseSize();
  24280. // Sprites
  24281. var deltaTime = engine.getDeltaTime();
  24282. var max = Math.min(this._capacity, this.sprites.length);
  24283. var rowSize = baseSize.width / this.cellSize;
  24284. var offset = 0;
  24285. for (var index = 0; index < max; index++) {
  24286. var sprite = this.sprites[index];
  24287. if (!sprite) {
  24288. continue;
  24289. }
  24290. sprite._animate(deltaTime);
  24291. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  24292. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  24293. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  24294. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  24295. }
  24296. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  24297. // Render
  24298. var effect = this._effectBase;
  24299. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  24300. effect = this._effectFog;
  24301. }
  24302. engine.enableEffect(effect);
  24303. var viewMatrix = this._scene.getViewMatrix();
  24304. effect.setTexture("diffuseSampler", this._spriteTexture);
  24305. effect.setMatrix("view", viewMatrix);
  24306. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  24307. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  24308. // Fog
  24309. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  24310. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  24311. effect.setColor3("vFogColor", this._scene.fogColor);
  24312. }
  24313. // VBOs
  24314. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  24315. // Draw order
  24316. engine.setDepthFunctionToLessOrEqual();
  24317. effect.setBool("alphaTest", true);
  24318. engine.setColorWrite(false);
  24319. engine.draw(true, 0, max * 6);
  24320. engine.setColorWrite(true);
  24321. effect.setBool("alphaTest", false);
  24322. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24323. engine.draw(true, 0, max * 6);
  24324. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24325. };
  24326. SpriteManager.prototype.dispose = function () {
  24327. if (this._vertexBuffer) {
  24328. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  24329. this._vertexBuffer = null;
  24330. }
  24331. if (this._indexBuffer) {
  24332. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  24333. this._indexBuffer = null;
  24334. }
  24335. if (this._spriteTexture) {
  24336. this._spriteTexture.dispose();
  24337. this._spriteTexture = null;
  24338. }
  24339. // Remove from scene
  24340. var index = this._scene.spriteManagers.indexOf(this);
  24341. this._scene.spriteManagers.splice(index, 1);
  24342. // Callback
  24343. if (this.onDispose) {
  24344. this.onDispose();
  24345. }
  24346. };
  24347. return SpriteManager;
  24348. })();
  24349. BABYLON.SpriteManager = SpriteManager;
  24350. })(BABYLON || (BABYLON = {}));
  24351. var BABYLON;
  24352. (function (BABYLON) {
  24353. var Sprite = (function () {
  24354. function Sprite(name, manager) {
  24355. this.name = name;
  24356. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24357. this.width = 1.0;
  24358. this.height = 1.0;
  24359. this.angle = 0;
  24360. this.cellIndex = 0;
  24361. this.invertU = 0;
  24362. this.invertV = 0;
  24363. this.animations = new Array();
  24364. this.isPickable = false;
  24365. this._animationStarted = false;
  24366. this._loopAnimation = false;
  24367. this._fromIndex = 0;
  24368. this._toIndex = 0;
  24369. this._delay = 0;
  24370. this._direction = 1;
  24371. this._frameCount = 0;
  24372. this._time = 0;
  24373. this._manager = manager;
  24374. this._manager.sprites.push(this);
  24375. this.position = BABYLON.Vector3.Zero();
  24376. }
  24377. Object.defineProperty(Sprite.prototype, "size", {
  24378. get: function () {
  24379. return this.width;
  24380. },
  24381. set: function (value) {
  24382. this.width = value;
  24383. this.height = value;
  24384. },
  24385. enumerable: true,
  24386. configurable: true
  24387. });
  24388. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  24389. this._fromIndex = from;
  24390. this._toIndex = to;
  24391. this._loopAnimation = loop;
  24392. this._delay = delay;
  24393. this._animationStarted = true;
  24394. this._direction = from < to ? 1 : -1;
  24395. this.cellIndex = from;
  24396. this._time = 0;
  24397. };
  24398. Sprite.prototype.stopAnimation = function () {
  24399. this._animationStarted = false;
  24400. };
  24401. Sprite.prototype._animate = function (deltaTime) {
  24402. if (!this._animationStarted)
  24403. return;
  24404. this._time += deltaTime;
  24405. if (this._time > this._delay) {
  24406. this._time = this._time % this._delay;
  24407. this.cellIndex += this._direction;
  24408. if (this.cellIndex == this._toIndex) {
  24409. if (this._loopAnimation) {
  24410. this.cellIndex = this._fromIndex;
  24411. }
  24412. else {
  24413. this._animationStarted = false;
  24414. if (this.disposeWhenFinishedAnimating) {
  24415. this.dispose();
  24416. }
  24417. }
  24418. }
  24419. }
  24420. };
  24421. Sprite.prototype.dispose = function () {
  24422. for (var i = 0; i < this._manager.sprites.length; i++) {
  24423. if (this._manager.sprites[i] == this) {
  24424. this._manager.sprites.splice(i, 1);
  24425. }
  24426. }
  24427. };
  24428. return Sprite;
  24429. })();
  24430. BABYLON.Sprite = Sprite;
  24431. })(BABYLON || (BABYLON = {}));
  24432. var BABYLON;
  24433. (function (BABYLON) {
  24434. var Layer = (function () {
  24435. function Layer(name, imgUrl, scene, isBackground, color) {
  24436. this.name = name;
  24437. this.scale = new BABYLON.Vector2(1, 1);
  24438. this.offset = new BABYLON.Vector2(0, 0);
  24439. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  24440. this._vertexDeclaration = [2];
  24441. this._vertexStrideSize = 2 * 4;
  24442. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  24443. this.isBackground = isBackground === undefined ? true : isBackground;
  24444. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  24445. this._scene = scene;
  24446. this._scene.layers.push(this);
  24447. // VBO
  24448. var vertices = [];
  24449. vertices.push(1, 1);
  24450. vertices.push(-1, 1);
  24451. vertices.push(-1, -1);
  24452. vertices.push(1, -1);
  24453. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  24454. // Indices
  24455. var indices = [];
  24456. indices.push(0);
  24457. indices.push(1);
  24458. indices.push(2);
  24459. indices.push(0);
  24460. indices.push(2);
  24461. indices.push(3);
  24462. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24463. // Effects
  24464. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  24465. this._alphaTestEffect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  24466. }
  24467. Layer.prototype.render = function () {
  24468. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  24469. // Check
  24470. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  24471. return;
  24472. var engine = this._scene.getEngine();
  24473. if (this.onBeforeRender) {
  24474. this.onBeforeRender();
  24475. }
  24476. // Render
  24477. engine.enableEffect(currentEffect);
  24478. engine.setState(false);
  24479. // Texture
  24480. currentEffect.setTexture("textureSampler", this.texture);
  24481. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  24482. // Color
  24483. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  24484. // Scale / offset
  24485. currentEffect.setVector2("offset", this.offset);
  24486. currentEffect.setVector2("scale", this.scale);
  24487. // VBOs
  24488. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, currentEffect);
  24489. // Draw order
  24490. if (!this._alphaTestEffect) {
  24491. engine.setAlphaMode(this.alphaBlendingMode);
  24492. engine.draw(true, 0, 6);
  24493. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24494. }
  24495. else {
  24496. engine.draw(true, 0, 6);
  24497. }
  24498. if (this.onAfterRender) {
  24499. this.onAfterRender();
  24500. }
  24501. };
  24502. Layer.prototype.dispose = function () {
  24503. if (this._vertexBuffer) {
  24504. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  24505. this._vertexBuffer = null;
  24506. }
  24507. if (this._indexBuffer) {
  24508. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  24509. this._indexBuffer = null;
  24510. }
  24511. if (this.texture) {
  24512. this.texture.dispose();
  24513. this.texture = null;
  24514. }
  24515. // Remove from scene
  24516. var index = this._scene.layers.indexOf(this);
  24517. this._scene.layers.splice(index, 1);
  24518. // Callback
  24519. if (this.onDispose) {
  24520. this.onDispose();
  24521. }
  24522. };
  24523. return Layer;
  24524. })();
  24525. BABYLON.Layer = Layer;
  24526. })(BABYLON || (BABYLON = {}));
  24527. var BABYLON;
  24528. (function (BABYLON) {
  24529. var Particle = (function () {
  24530. function Particle() {
  24531. this.position = BABYLON.Vector3.Zero();
  24532. this.direction = BABYLON.Vector3.Zero();
  24533. this.color = new BABYLON.Color4(0, 0, 0, 0);
  24534. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  24535. this.lifeTime = 1.0;
  24536. this.age = 0;
  24537. this.size = 0;
  24538. this.angle = 0;
  24539. this.angularSpeed = 0;
  24540. }
  24541. Particle.prototype.copyTo = function (other) {
  24542. other.position.copyFrom(this.position);
  24543. other.direction.copyFrom(this.direction);
  24544. other.color.copyFrom(this.color);
  24545. other.colorStep.copyFrom(this.colorStep);
  24546. other.lifeTime = this.lifeTime;
  24547. other.age = this.age;
  24548. other.size = this.size;
  24549. other.angle = this.angle;
  24550. other.angularSpeed = this.angularSpeed;
  24551. };
  24552. return Particle;
  24553. })();
  24554. BABYLON.Particle = Particle;
  24555. })(BABYLON || (BABYLON = {}));
  24556. var BABYLON;
  24557. (function (BABYLON) {
  24558. var randomNumber = function (min, max) {
  24559. if (min === max) {
  24560. return (min);
  24561. }
  24562. var random = Math.random();
  24563. return ((random * (max - min)) + min);
  24564. };
  24565. var ParticleSystem = (function () {
  24566. function ParticleSystem(name, capacity, scene, customEffect) {
  24567. var _this = this;
  24568. this.name = name;
  24569. // Members
  24570. this.animations = [];
  24571. this.renderingGroupId = 0;
  24572. this.emitter = null;
  24573. this.emitRate = 10;
  24574. this.manualEmitCount = -1;
  24575. this.updateSpeed = 0.01;
  24576. this.targetStopDuration = 0;
  24577. this.disposeOnStop = false;
  24578. this.minEmitPower = 1;
  24579. this.maxEmitPower = 1;
  24580. this.minLifeTime = 1;
  24581. this.maxLifeTime = 1;
  24582. this.minSize = 1;
  24583. this.maxSize = 1;
  24584. this.minAngularSpeed = 0;
  24585. this.maxAngularSpeed = 0;
  24586. this.layerMask = 0x0FFFFFFF;
  24587. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  24588. this.forceDepthWrite = false;
  24589. this.gravity = BABYLON.Vector3.Zero();
  24590. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  24591. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  24592. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  24593. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  24594. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24595. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24596. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  24597. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  24598. this.particles = new Array();
  24599. this._vertexDeclaration = [3, 4, 4];
  24600. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  24601. this._stockParticles = new Array();
  24602. this._newPartsExcess = 0;
  24603. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  24604. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  24605. this._scaledDirection = BABYLON.Vector3.Zero();
  24606. this._scaledGravity = BABYLON.Vector3.Zero();
  24607. this._currentRenderId = -1;
  24608. this._started = false;
  24609. this._stopped = false;
  24610. this._actualFrame = 0;
  24611. this.id = name;
  24612. this._capacity = capacity;
  24613. this._scene = scene;
  24614. this._customEffect = customEffect;
  24615. scene.particleSystems.push(this);
  24616. // VBO
  24617. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  24618. var indices = [];
  24619. var index = 0;
  24620. for (var count = 0; count < capacity; count++) {
  24621. indices.push(index);
  24622. indices.push(index + 1);
  24623. indices.push(index + 2);
  24624. indices.push(index);
  24625. indices.push(index + 2);
  24626. indices.push(index + 3);
  24627. index += 4;
  24628. }
  24629. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  24630. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  24631. // Default behaviors
  24632. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  24633. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  24634. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  24635. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  24636. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  24637. };
  24638. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  24639. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  24640. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  24641. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  24642. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  24643. };
  24644. this.updateFunction = function (particles) {
  24645. for (var index = 0; index < particles.length; index++) {
  24646. var particle = particles[index];
  24647. particle.age += _this._scaledUpdateSpeed;
  24648. if (particle.age >= particle.lifeTime) {
  24649. _this.recycleParticle(particle);
  24650. index--;
  24651. continue;
  24652. }
  24653. else {
  24654. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  24655. particle.color.addInPlace(_this._scaledColorStep);
  24656. if (particle.color.a < 0)
  24657. particle.color.a = 0;
  24658. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  24659. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  24660. particle.position.addInPlace(_this._scaledDirection);
  24661. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  24662. particle.direction.addInPlace(_this._scaledGravity);
  24663. }
  24664. }
  24665. };
  24666. }
  24667. ParticleSystem.prototype.recycleParticle = function (particle) {
  24668. var lastParticle = this.particles.pop();
  24669. if (lastParticle !== particle) {
  24670. lastParticle.copyTo(particle);
  24671. this._stockParticles.push(lastParticle);
  24672. }
  24673. };
  24674. ParticleSystem.prototype.getCapacity = function () {
  24675. return this._capacity;
  24676. };
  24677. ParticleSystem.prototype.isAlive = function () {
  24678. return this._alive;
  24679. };
  24680. ParticleSystem.prototype.isStarted = function () {
  24681. return this._started;
  24682. };
  24683. ParticleSystem.prototype.start = function () {
  24684. this._started = true;
  24685. this._stopped = false;
  24686. this._actualFrame = 0;
  24687. };
  24688. ParticleSystem.prototype.stop = function () {
  24689. this._stopped = true;
  24690. };
  24691. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  24692. var offset = index * 11;
  24693. this._vertices[offset] = particle.position.x;
  24694. this._vertices[offset + 1] = particle.position.y;
  24695. this._vertices[offset + 2] = particle.position.z;
  24696. this._vertices[offset + 3] = particle.color.r;
  24697. this._vertices[offset + 4] = particle.color.g;
  24698. this._vertices[offset + 5] = particle.color.b;
  24699. this._vertices[offset + 6] = particle.color.a;
  24700. this._vertices[offset + 7] = particle.angle;
  24701. this._vertices[offset + 8] = particle.size;
  24702. this._vertices[offset + 9] = offsetX;
  24703. this._vertices[offset + 10] = offsetY;
  24704. };
  24705. ParticleSystem.prototype._update = function (newParticles) {
  24706. // Update current
  24707. this._alive = this.particles.length > 0;
  24708. this.updateFunction(this.particles);
  24709. // Add new ones
  24710. var worldMatrix;
  24711. if (this.emitter.position) {
  24712. worldMatrix = this.emitter.getWorldMatrix();
  24713. }
  24714. else {
  24715. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  24716. }
  24717. var particle;
  24718. for (var index = 0; index < newParticles; index++) {
  24719. if (this.particles.length === this._capacity) {
  24720. break;
  24721. }
  24722. if (this._stockParticles.length !== 0) {
  24723. particle = this._stockParticles.pop();
  24724. particle.age = 0;
  24725. }
  24726. else {
  24727. particle = new BABYLON.Particle();
  24728. }
  24729. this.particles.push(particle);
  24730. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  24731. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  24732. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  24733. particle.size = randomNumber(this.minSize, this.maxSize);
  24734. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  24735. this.startPositionFunction(worldMatrix, particle.position, particle);
  24736. var step = randomNumber(0, 1.0);
  24737. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  24738. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  24739. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  24740. }
  24741. };
  24742. ParticleSystem.prototype._getEffect = function () {
  24743. if (this._customEffect) {
  24744. return this._customEffect;
  24745. }
  24746. ;
  24747. var defines = [];
  24748. if (this._scene.clipPlane) {
  24749. defines.push("#define CLIPPLANE");
  24750. }
  24751. // Effect
  24752. var join = defines.join("\n");
  24753. if (this._cachedDefines !== join) {
  24754. this._cachedDefines = join;
  24755. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  24756. }
  24757. return this._effect;
  24758. };
  24759. ParticleSystem.prototype.animate = function () {
  24760. if (!this._started)
  24761. return;
  24762. var effect = this._getEffect();
  24763. // Check
  24764. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  24765. return;
  24766. if (this._currentRenderId === this._scene.getRenderId()) {
  24767. return;
  24768. }
  24769. this._currentRenderId = this._scene.getRenderId();
  24770. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  24771. // determine the number of particles we need to create
  24772. var newParticles;
  24773. if (this.manualEmitCount > -1) {
  24774. newParticles = this.manualEmitCount;
  24775. this._newPartsExcess = 0;
  24776. this.manualEmitCount = 0;
  24777. }
  24778. else {
  24779. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  24780. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  24781. }
  24782. if (this._newPartsExcess > 1.0) {
  24783. newParticles += this._newPartsExcess >> 0;
  24784. this._newPartsExcess -= this._newPartsExcess >> 0;
  24785. }
  24786. this._alive = false;
  24787. if (!this._stopped) {
  24788. this._actualFrame += this._scaledUpdateSpeed;
  24789. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  24790. this.stop();
  24791. }
  24792. else {
  24793. newParticles = 0;
  24794. }
  24795. this._update(newParticles);
  24796. // Stopped?
  24797. if (this._stopped) {
  24798. if (!this._alive) {
  24799. this._started = false;
  24800. if (this.disposeOnStop) {
  24801. this._scene._toBeDisposed.push(this);
  24802. }
  24803. }
  24804. }
  24805. // Update VBO
  24806. var offset = 0;
  24807. for (var index = 0; index < this.particles.length; index++) {
  24808. var particle = this.particles[index];
  24809. this._appendParticleVertex(offset++, particle, 0, 0);
  24810. this._appendParticleVertex(offset++, particle, 1, 0);
  24811. this._appendParticleVertex(offset++, particle, 1, 1);
  24812. this._appendParticleVertex(offset++, particle, 0, 1);
  24813. }
  24814. var engine = this._scene.getEngine();
  24815. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  24816. };
  24817. ParticleSystem.prototype.render = function () {
  24818. var effect = this._getEffect();
  24819. // Check
  24820. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  24821. return 0;
  24822. var engine = this._scene.getEngine();
  24823. // Render
  24824. engine.enableEffect(effect);
  24825. engine.setState(false);
  24826. var viewMatrix = this._scene.getViewMatrix();
  24827. effect.setTexture("diffuseSampler", this.particleTexture);
  24828. effect.setMatrix("view", viewMatrix);
  24829. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  24830. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  24831. if (this._scene.clipPlane) {
  24832. var clipPlane = this._scene.clipPlane;
  24833. var invView = viewMatrix.clone();
  24834. invView.invert();
  24835. effect.setMatrix("invView", invView);
  24836. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  24837. }
  24838. // VBOs
  24839. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  24840. // Draw order
  24841. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  24842. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  24843. }
  24844. else {
  24845. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24846. }
  24847. if (this.forceDepthWrite) {
  24848. engine.setDepthWrite(true);
  24849. }
  24850. engine.draw(true, 0, this.particles.length * 6);
  24851. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24852. return this.particles.length;
  24853. };
  24854. ParticleSystem.prototype.dispose = function () {
  24855. if (this._vertexBuffer) {
  24856. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  24857. this._vertexBuffer = null;
  24858. }
  24859. if (this._indexBuffer) {
  24860. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  24861. this._indexBuffer = null;
  24862. }
  24863. if (this.particleTexture) {
  24864. this.particleTexture.dispose();
  24865. this.particleTexture = null;
  24866. }
  24867. // Remove from scene
  24868. var index = this._scene.particleSystems.indexOf(this);
  24869. this._scene.particleSystems.splice(index, 1);
  24870. // Callback
  24871. if (this.onDispose) {
  24872. this.onDispose();
  24873. }
  24874. };
  24875. // Clone
  24876. ParticleSystem.prototype.clone = function (name, newEmitter) {
  24877. var result = new ParticleSystem(name, this._capacity, this._scene);
  24878. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  24879. if (newEmitter === undefined) {
  24880. newEmitter = this.emitter;
  24881. }
  24882. result.emitter = newEmitter;
  24883. if (this.particleTexture) {
  24884. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  24885. }
  24886. result.start();
  24887. return result;
  24888. };
  24889. ParticleSystem.prototype.serialize = function () {
  24890. var serializationObject = {};
  24891. serializationObject.name = this.name;
  24892. serializationObject.id = this.id;
  24893. // Emitter
  24894. if (this.emitter.position) {
  24895. serializationObject.emitterId = this.emitter.id;
  24896. }
  24897. else {
  24898. serializationObject.emitter = this.emitter.asArray();
  24899. }
  24900. serializationObject.capacity = this.getCapacity();
  24901. if (this.particleTexture) {
  24902. serializationObject.textureName = this.particleTexture.name;
  24903. }
  24904. // Animations
  24905. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24906. // Particle system
  24907. serializationObject.minAngularSpeed = this.minAngularSpeed;
  24908. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  24909. serializationObject.minSize = this.minSize;
  24910. serializationObject.maxSize = this.maxSize;
  24911. serializationObject.minEmitPower = this.minEmitPower;
  24912. serializationObject.maxEmitPower = this.maxEmitPower;
  24913. serializationObject.minLifeTime = this.minLifeTime;
  24914. serializationObject.maxLifeTime = this.maxLifeTime;
  24915. serializationObject.emitRate = this.emitRate;
  24916. serializationObject.minEmitBox = this.minEmitBox.asArray();
  24917. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  24918. serializationObject.gravity = this.gravity.asArray();
  24919. serializationObject.direction1 = this.direction1.asArray();
  24920. serializationObject.direction2 = this.direction2.asArray();
  24921. serializationObject.color1 = this.color1.asArray();
  24922. serializationObject.color2 = this.color2.asArray();
  24923. serializationObject.colorDead = this.colorDead.asArray();
  24924. serializationObject.updateSpeed = this.updateSpeed;
  24925. serializationObject.targetStopDuration = this.targetStopDuration;
  24926. serializationObject.textureMask = this.textureMask.asArray();
  24927. serializationObject.blendMode = this.blendMode;
  24928. return serializationObject;
  24929. };
  24930. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  24931. var name = parsedParticleSystem.name;
  24932. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  24933. if (parsedParticleSystem.id) {
  24934. particleSystem.id = parsedParticleSystem.id;
  24935. }
  24936. // Texture
  24937. if (parsedParticleSystem.textureName) {
  24938. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  24939. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  24940. }
  24941. // Emitter
  24942. if (parsedParticleSystem.emitterId) {
  24943. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  24944. }
  24945. else {
  24946. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  24947. }
  24948. // Animations
  24949. if (parsedParticleSystem.animations) {
  24950. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  24951. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  24952. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24953. }
  24954. }
  24955. if (parsedParticleSystem.autoAnimate) {
  24956. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  24957. }
  24958. // Particle system
  24959. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  24960. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  24961. particleSystem.minSize = parsedParticleSystem.minSize;
  24962. particleSystem.maxSize = parsedParticleSystem.maxSize;
  24963. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  24964. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  24965. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  24966. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  24967. particleSystem.emitRate = parsedParticleSystem.emitRate;
  24968. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  24969. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  24970. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  24971. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  24972. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  24973. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  24974. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  24975. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  24976. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  24977. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  24978. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  24979. particleSystem.blendMode = parsedParticleSystem.blendMode;
  24980. particleSystem.start();
  24981. return particleSystem;
  24982. };
  24983. // Statics
  24984. ParticleSystem.BLENDMODE_ONEONE = 0;
  24985. ParticleSystem.BLENDMODE_STANDARD = 1;
  24986. return ParticleSystem;
  24987. })();
  24988. BABYLON.ParticleSystem = ParticleSystem;
  24989. })(BABYLON || (BABYLON = {}));
  24990. var BABYLON;
  24991. (function (BABYLON) {
  24992. var AnimationRange = (function () {
  24993. function AnimationRange(name, from, to) {
  24994. this.name = name;
  24995. this.from = from;
  24996. this.to = to;
  24997. }
  24998. AnimationRange.prototype.clone = function () {
  24999. return new AnimationRange(this.name, this.from, this.to);
  25000. };
  25001. return AnimationRange;
  25002. })();
  25003. BABYLON.AnimationRange = AnimationRange;
  25004. /**
  25005. * Composed of a frame, and an action function
  25006. */
  25007. var AnimationEvent = (function () {
  25008. function AnimationEvent(frame, action, onlyOnce) {
  25009. this.frame = frame;
  25010. this.action = action;
  25011. this.onlyOnce = onlyOnce;
  25012. this.isDone = false;
  25013. }
  25014. return AnimationEvent;
  25015. })();
  25016. BABYLON.AnimationEvent = AnimationEvent;
  25017. var PathCursor = (function () {
  25018. function PathCursor(path) {
  25019. this.path = path;
  25020. this._onchange = new Array();
  25021. this.value = 0;
  25022. this.animations = new Array();
  25023. }
  25024. PathCursor.prototype.getPoint = function () {
  25025. var point = this.path.getPointAtLengthPosition(this.value);
  25026. return new BABYLON.Vector3(point.x, 0, point.y);
  25027. };
  25028. PathCursor.prototype.moveAhead = function (step) {
  25029. if (step === void 0) { step = 0.002; }
  25030. this.move(step);
  25031. return this;
  25032. };
  25033. PathCursor.prototype.moveBack = function (step) {
  25034. if (step === void 0) { step = 0.002; }
  25035. this.move(-step);
  25036. return this;
  25037. };
  25038. PathCursor.prototype.move = function (step) {
  25039. if (Math.abs(step) > 1) {
  25040. throw "step size should be less than 1.";
  25041. }
  25042. this.value += step;
  25043. this.ensureLimits();
  25044. this.raiseOnChange();
  25045. return this;
  25046. };
  25047. PathCursor.prototype.ensureLimits = function () {
  25048. while (this.value > 1) {
  25049. this.value -= 1;
  25050. }
  25051. while (this.value < 0) {
  25052. this.value += 1;
  25053. }
  25054. return this;
  25055. };
  25056. // used by animation engine
  25057. PathCursor.prototype.markAsDirty = function (propertyName) {
  25058. this.ensureLimits();
  25059. this.raiseOnChange();
  25060. return this;
  25061. };
  25062. PathCursor.prototype.raiseOnChange = function () {
  25063. var _this = this;
  25064. this._onchange.forEach(function (f) { return f(_this); });
  25065. return this;
  25066. };
  25067. PathCursor.prototype.onchange = function (f) {
  25068. this._onchange.push(f);
  25069. return this;
  25070. };
  25071. return PathCursor;
  25072. })();
  25073. BABYLON.PathCursor = PathCursor;
  25074. var Animation = (function () {
  25075. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  25076. this.name = name;
  25077. this.targetProperty = targetProperty;
  25078. this.framePerSecond = framePerSecond;
  25079. this.dataType = dataType;
  25080. this.loopMode = loopMode;
  25081. this.enableBlending = enableBlending;
  25082. this._offsetsCache = {};
  25083. this._highLimitsCache = {};
  25084. this._stopped = false;
  25085. this._blendingFactor = 0;
  25086. // The set of event that will be linked to this animation
  25087. this._events = new Array();
  25088. this.allowMatricesInterpolation = false;
  25089. this.blendingSpeed = 0.01;
  25090. this._ranges = {};
  25091. this.targetPropertyPath = targetProperty.split(".");
  25092. this.dataType = dataType;
  25093. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  25094. }
  25095. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  25096. var dataType = undefined;
  25097. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  25098. dataType = Animation.ANIMATIONTYPE_FLOAT;
  25099. }
  25100. else if (from instanceof BABYLON.Quaternion) {
  25101. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  25102. }
  25103. else if (from instanceof BABYLON.Vector3) {
  25104. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  25105. }
  25106. else if (from instanceof BABYLON.Vector2) {
  25107. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  25108. }
  25109. else if (from instanceof BABYLON.Color3) {
  25110. dataType = Animation.ANIMATIONTYPE_COLOR3;
  25111. }
  25112. if (dataType == undefined) {
  25113. return null;
  25114. }
  25115. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  25116. var keys = [];
  25117. keys.push({ frame: 0, value: from });
  25118. keys.push({ frame: totalFrame, value: to });
  25119. animation.setKeys(keys);
  25120. if (easingFunction !== undefined) {
  25121. animation.setEasingFunction(easingFunction);
  25122. }
  25123. return animation;
  25124. };
  25125. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  25126. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  25127. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  25128. };
  25129. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  25130. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  25131. node.animations.push(animation);
  25132. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  25133. };
  25134. // Methods
  25135. /**
  25136. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25137. */
  25138. Animation.prototype.toString = function (fullDetails) {
  25139. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  25140. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  25141. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  25142. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  25143. if (fullDetails) {
  25144. ret += ", Ranges: {";
  25145. var first = true;
  25146. for (var name in this._ranges) {
  25147. if (!first) {
  25148. ret + ", ";
  25149. first = false;
  25150. }
  25151. ret += name;
  25152. }
  25153. ret += "}";
  25154. }
  25155. return ret;
  25156. };
  25157. /**
  25158. * Add an event to this animation.
  25159. */
  25160. Animation.prototype.addEvent = function (event) {
  25161. this._events.push(event);
  25162. };
  25163. /**
  25164. * Remove all events found at the given frame
  25165. * @param frame
  25166. */
  25167. Animation.prototype.removeEvents = function (frame) {
  25168. for (var index = 0; index < this._events.length; index++) {
  25169. if (this._events[index].frame === frame) {
  25170. this._events.splice(index, 1);
  25171. index--;
  25172. }
  25173. }
  25174. };
  25175. Animation.prototype.createRange = function (name, from, to) {
  25176. // check name not already in use; could happen for bones after serialized
  25177. if (!this._ranges[name]) {
  25178. this._ranges[name] = new AnimationRange(name, from, to);
  25179. }
  25180. };
  25181. Animation.prototype.deleteRange = function (name, deleteFrames) {
  25182. if (deleteFrames === void 0) { deleteFrames = true; }
  25183. if (this._ranges[name]) {
  25184. if (deleteFrames) {
  25185. var from = this._ranges[name].from;
  25186. var to = this._ranges[name].to;
  25187. // this loop MUST go high to low for multiple splices to work
  25188. for (var key = this._keys.length - 1; key >= 0; key--) {
  25189. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  25190. this._keys.splice(key, 1);
  25191. }
  25192. }
  25193. }
  25194. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  25195. }
  25196. };
  25197. Animation.prototype.getRange = function (name) {
  25198. return this._ranges[name];
  25199. };
  25200. Animation.prototype.reset = function () {
  25201. this._offsetsCache = {};
  25202. this._highLimitsCache = {};
  25203. this.currentFrame = 0;
  25204. this._blendingFactor = 0;
  25205. this._originalBlendValue = null;
  25206. };
  25207. Animation.prototype.isStopped = function () {
  25208. return this._stopped;
  25209. };
  25210. Animation.prototype.getKeys = function () {
  25211. return this._keys;
  25212. };
  25213. Animation.prototype.getHighestFrame = function () {
  25214. var ret = 0;
  25215. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  25216. if (ret < this._keys[key].frame) {
  25217. ret = this._keys[key].frame;
  25218. }
  25219. }
  25220. return ret;
  25221. };
  25222. Animation.prototype.getEasingFunction = function () {
  25223. return this._easingFunction;
  25224. };
  25225. Animation.prototype.setEasingFunction = function (easingFunction) {
  25226. this._easingFunction = easingFunction;
  25227. };
  25228. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  25229. return startValue + (endValue - startValue) * gradient;
  25230. };
  25231. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  25232. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  25233. };
  25234. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  25235. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  25236. };
  25237. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  25238. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  25239. };
  25240. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  25241. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  25242. };
  25243. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  25244. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  25245. };
  25246. Animation.prototype.clone = function () {
  25247. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  25248. if (this._keys) {
  25249. clone.setKeys(this._keys);
  25250. }
  25251. if (this._ranges) {
  25252. clone._ranges = {};
  25253. for (var name in this._ranges) {
  25254. clone._ranges[name] = this._ranges[name].clone();
  25255. }
  25256. }
  25257. return clone;
  25258. };
  25259. Animation.prototype.setKeys = function (values) {
  25260. this._keys = values.slice(0);
  25261. this._offsetsCache = {};
  25262. this._highLimitsCache = {};
  25263. };
  25264. Animation.prototype._getKeyValue = function (value) {
  25265. if (typeof value === "function") {
  25266. return value();
  25267. }
  25268. return value;
  25269. };
  25270. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  25271. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  25272. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  25273. }
  25274. this.currentFrame = currentFrame;
  25275. // Try to get a hash to find the right key
  25276. 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));
  25277. if (this._keys[startKey].frame >= currentFrame) {
  25278. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  25279. startKey--;
  25280. }
  25281. }
  25282. for (var key = startKey; key < this._keys.length; key++) {
  25283. if (this._keys[key + 1].frame >= currentFrame) {
  25284. var startValue = this._getKeyValue(this._keys[key].value);
  25285. var endValue = this._getKeyValue(this._keys[key + 1].value);
  25286. // gradient : percent of currentFrame between the frame inf and the frame sup
  25287. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  25288. // check for easingFunction and correction of gradient
  25289. if (this._easingFunction != null) {
  25290. gradient = this._easingFunction.ease(gradient);
  25291. }
  25292. switch (this.dataType) {
  25293. // Float
  25294. case Animation.ANIMATIONTYPE_FLOAT:
  25295. switch (loopMode) {
  25296. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25297. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25298. return this.floatInterpolateFunction(startValue, endValue, gradient);
  25299. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25300. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  25301. }
  25302. break;
  25303. // Quaternion
  25304. case Animation.ANIMATIONTYPE_QUATERNION:
  25305. var quaternion = null;
  25306. switch (loopMode) {
  25307. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25308. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25309. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  25310. break;
  25311. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25312. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25313. break;
  25314. }
  25315. return quaternion;
  25316. // Vector3
  25317. case Animation.ANIMATIONTYPE_VECTOR3:
  25318. switch (loopMode) {
  25319. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25320. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25321. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  25322. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25323. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25324. }
  25325. // Vector2
  25326. case Animation.ANIMATIONTYPE_VECTOR2:
  25327. switch (loopMode) {
  25328. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25329. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25330. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  25331. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25332. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25333. }
  25334. // Color3
  25335. case Animation.ANIMATIONTYPE_COLOR3:
  25336. switch (loopMode) {
  25337. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25338. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25339. return this.color3InterpolateFunction(startValue, endValue, gradient);
  25340. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25341. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  25342. }
  25343. // Matrix
  25344. case Animation.ANIMATIONTYPE_MATRIX:
  25345. switch (loopMode) {
  25346. case Animation.ANIMATIONLOOPMODE_CYCLE:
  25347. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  25348. if (this.allowMatricesInterpolation) {
  25349. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  25350. }
  25351. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  25352. return startValue;
  25353. }
  25354. default:
  25355. break;
  25356. }
  25357. break;
  25358. }
  25359. }
  25360. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  25361. };
  25362. Animation.prototype.setValue = function (currentValue, blend) {
  25363. if (blend === void 0) { blend = false; }
  25364. // Set value
  25365. var path;
  25366. var destination;
  25367. if (this.targetPropertyPath.length > 1) {
  25368. var property = this._target[this.targetPropertyPath[0]];
  25369. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  25370. property = property[this.targetPropertyPath[index]];
  25371. }
  25372. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  25373. destination = property;
  25374. }
  25375. else {
  25376. path = this.targetPropertyPath[0];
  25377. destination = this._target;
  25378. }
  25379. // Blending
  25380. if (this.enableBlending && this._blendingFactor <= 1.0) {
  25381. if (!this._originalBlendValue) {
  25382. this._originalBlendValue = destination[path];
  25383. }
  25384. if (this._originalBlendValue.prototype) {
  25385. if (this._originalBlendValue.prototype.Lerp) {
  25386. destination[path] = this._originalBlendValue.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  25387. }
  25388. else {
  25389. destination[path] = currentValue;
  25390. }
  25391. }
  25392. else {
  25393. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  25394. }
  25395. this._blendingFactor += this.blendingSpeed;
  25396. }
  25397. else {
  25398. destination[path] = currentValue;
  25399. }
  25400. if (this._target.markAsDirty) {
  25401. this._target.markAsDirty(this.targetProperty);
  25402. }
  25403. };
  25404. Animation.prototype.goToFrame = function (frame) {
  25405. if (frame < this._keys[0].frame) {
  25406. frame = this._keys[0].frame;
  25407. }
  25408. else if (frame > this._keys[this._keys.length - 1].frame) {
  25409. frame = this._keys[this._keys.length - 1].frame;
  25410. }
  25411. var currentValue = this._interpolate(frame, 0, this.loopMode);
  25412. this.setValue(currentValue);
  25413. };
  25414. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  25415. if (blend === void 0) { blend = false; }
  25416. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  25417. this._stopped = true;
  25418. return false;
  25419. }
  25420. var returnValue = true;
  25421. // Adding a start key at frame 0 if missing
  25422. if (this._keys[0].frame !== 0) {
  25423. var newKey = { frame: 0, value: this._keys[0].value };
  25424. this._keys.splice(0, 0, newKey);
  25425. }
  25426. // Check limits
  25427. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  25428. from = this._keys[0].frame;
  25429. }
  25430. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  25431. to = this._keys[this._keys.length - 1].frame;
  25432. }
  25433. // Compute ratio
  25434. var range = to - from;
  25435. var offsetValue;
  25436. // ratio represents the frame delta between from and to
  25437. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  25438. var highLimitValue = 0;
  25439. if (ratio > range && !loop) {
  25440. returnValue = false;
  25441. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  25442. }
  25443. else {
  25444. // Get max value if required
  25445. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  25446. var keyOffset = to.toString() + from.toString();
  25447. if (!this._offsetsCache[keyOffset]) {
  25448. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  25449. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  25450. switch (this.dataType) {
  25451. // Float
  25452. case Animation.ANIMATIONTYPE_FLOAT:
  25453. this._offsetsCache[keyOffset] = toValue - fromValue;
  25454. break;
  25455. // Quaternion
  25456. case Animation.ANIMATIONTYPE_QUATERNION:
  25457. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25458. break;
  25459. // Vector3
  25460. case Animation.ANIMATIONTYPE_VECTOR3:
  25461. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25462. // Vector2
  25463. case Animation.ANIMATIONTYPE_VECTOR2:
  25464. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25465. // Color3
  25466. case Animation.ANIMATIONTYPE_COLOR3:
  25467. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  25468. default:
  25469. break;
  25470. }
  25471. this._highLimitsCache[keyOffset] = toValue;
  25472. }
  25473. highLimitValue = this._highLimitsCache[keyOffset];
  25474. offsetValue = this._offsetsCache[keyOffset];
  25475. }
  25476. }
  25477. if (offsetValue === undefined) {
  25478. switch (this.dataType) {
  25479. // Float
  25480. case Animation.ANIMATIONTYPE_FLOAT:
  25481. offsetValue = 0;
  25482. break;
  25483. // Quaternion
  25484. case Animation.ANIMATIONTYPE_QUATERNION:
  25485. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  25486. break;
  25487. // Vector3
  25488. case Animation.ANIMATIONTYPE_VECTOR3:
  25489. offsetValue = BABYLON.Vector3.Zero();
  25490. break;
  25491. // Vector2
  25492. case Animation.ANIMATIONTYPE_VECTOR2:
  25493. offsetValue = BABYLON.Vector2.Zero();
  25494. break;
  25495. // Color3
  25496. case Animation.ANIMATIONTYPE_COLOR3:
  25497. offsetValue = BABYLON.Color3.Black();
  25498. }
  25499. }
  25500. // Compute value
  25501. var repeatCount = (ratio / range) >> 0;
  25502. var currentFrame = returnValue ? from + ratio % range : to;
  25503. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  25504. // Set value
  25505. this.setValue(currentValue);
  25506. // Check events
  25507. for (var index = 0; index < this._events.length; index++) {
  25508. if (currentFrame >= this._events[index].frame) {
  25509. var event = this._events[index];
  25510. if (!event.isDone) {
  25511. // If event should be done only once, remove it.
  25512. if (event.onlyOnce) {
  25513. this._events.splice(index, 1);
  25514. index--;
  25515. }
  25516. event.isDone = true;
  25517. event.action();
  25518. } // Don't do anything if the event has already be done.
  25519. }
  25520. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  25521. // reset event, the animation is looping
  25522. this._events[index].isDone = false;
  25523. }
  25524. }
  25525. if (!returnValue) {
  25526. this._stopped = true;
  25527. }
  25528. return returnValue;
  25529. };
  25530. Animation.prototype.serialize = function () {
  25531. var serializationObject = {};
  25532. serializationObject.name = this.name;
  25533. serializationObject.property = this.targetProperty;
  25534. serializationObject.framePerSecond = this.framePerSecond;
  25535. serializationObject.dataType = this.dataType;
  25536. serializationObject.loopBehavior = this.loopMode;
  25537. var dataType = this.dataType;
  25538. serializationObject.keys = [];
  25539. var keys = this.getKeys();
  25540. for (var index = 0; index < keys.length; index++) {
  25541. var animationKey = keys[index];
  25542. var key = {};
  25543. key.frame = animationKey.frame;
  25544. switch (dataType) {
  25545. case Animation.ANIMATIONTYPE_FLOAT:
  25546. key.values = [animationKey.value];
  25547. break;
  25548. case Animation.ANIMATIONTYPE_QUATERNION:
  25549. case Animation.ANIMATIONTYPE_MATRIX:
  25550. case Animation.ANIMATIONTYPE_VECTOR3:
  25551. case Animation.ANIMATIONTYPE_COLOR3:
  25552. key.values = animationKey.value.asArray();
  25553. break;
  25554. }
  25555. serializationObject.keys.push(key);
  25556. }
  25557. serializationObject.ranges = [];
  25558. for (var name in this._ranges) {
  25559. var range = {};
  25560. range.name = name;
  25561. range.from = this._ranges[name].from;
  25562. range.to = this._ranges[name].to;
  25563. serializationObject.ranges.push(range);
  25564. }
  25565. return serializationObject;
  25566. };
  25567. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  25568. get: function () {
  25569. return Animation._ANIMATIONTYPE_FLOAT;
  25570. },
  25571. enumerable: true,
  25572. configurable: true
  25573. });
  25574. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  25575. get: function () {
  25576. return Animation._ANIMATIONTYPE_VECTOR3;
  25577. },
  25578. enumerable: true,
  25579. configurable: true
  25580. });
  25581. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  25582. get: function () {
  25583. return Animation._ANIMATIONTYPE_VECTOR2;
  25584. },
  25585. enumerable: true,
  25586. configurable: true
  25587. });
  25588. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  25589. get: function () {
  25590. return Animation._ANIMATIONTYPE_QUATERNION;
  25591. },
  25592. enumerable: true,
  25593. configurable: true
  25594. });
  25595. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  25596. get: function () {
  25597. return Animation._ANIMATIONTYPE_MATRIX;
  25598. },
  25599. enumerable: true,
  25600. configurable: true
  25601. });
  25602. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  25603. get: function () {
  25604. return Animation._ANIMATIONTYPE_COLOR3;
  25605. },
  25606. enumerable: true,
  25607. configurable: true
  25608. });
  25609. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  25610. get: function () {
  25611. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  25612. },
  25613. enumerable: true,
  25614. configurable: true
  25615. });
  25616. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  25617. get: function () {
  25618. return Animation._ANIMATIONLOOPMODE_CYCLE;
  25619. },
  25620. enumerable: true,
  25621. configurable: true
  25622. });
  25623. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  25624. get: function () {
  25625. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  25626. },
  25627. enumerable: true,
  25628. configurable: true
  25629. });
  25630. Animation.Parse = function (parsedAnimation) {
  25631. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  25632. var dataType = parsedAnimation.dataType;
  25633. var keys = [];
  25634. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  25635. var key = parsedAnimation.keys[index];
  25636. var data;
  25637. switch (dataType) {
  25638. case Animation.ANIMATIONTYPE_FLOAT:
  25639. data = key.values[0];
  25640. break;
  25641. case Animation.ANIMATIONTYPE_QUATERNION:
  25642. data = BABYLON.Quaternion.FromArray(key.values);
  25643. break;
  25644. case Animation.ANIMATIONTYPE_MATRIX:
  25645. data = BABYLON.Matrix.FromArray(key.values);
  25646. break;
  25647. case Animation.ANIMATIONTYPE_COLOR3:
  25648. data = BABYLON.Color3.FromArray(key.values);
  25649. break;
  25650. case Animation.ANIMATIONTYPE_VECTOR3:
  25651. default:
  25652. data = BABYLON.Vector3.FromArray(key.values);
  25653. break;
  25654. }
  25655. keys.push({
  25656. frame: key.frame,
  25657. value: data
  25658. });
  25659. }
  25660. animation.setKeys(keys);
  25661. if (parsedAnimation.ranges) {
  25662. for (var index = 0; index < parsedAnimation.ranges.length; index++) {
  25663. data = parsedAnimation.ranges[index];
  25664. animation.createRange(data.name, data.from, data.to);
  25665. }
  25666. }
  25667. return animation;
  25668. };
  25669. Animation.AppendSerializedAnimations = function (source, destination) {
  25670. if (source.animations) {
  25671. destination.animations = [];
  25672. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  25673. var animation = source.animations[animationIndex];
  25674. destination.animations.push(animation.serialize());
  25675. }
  25676. }
  25677. };
  25678. // Statics
  25679. Animation._ANIMATIONTYPE_FLOAT = 0;
  25680. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  25681. Animation._ANIMATIONTYPE_QUATERNION = 2;
  25682. Animation._ANIMATIONTYPE_MATRIX = 3;
  25683. Animation._ANIMATIONTYPE_COLOR3 = 4;
  25684. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  25685. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  25686. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  25687. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  25688. return Animation;
  25689. })();
  25690. BABYLON.Animation = Animation;
  25691. })(BABYLON || (BABYLON = {}));
  25692. var BABYLON;
  25693. (function (BABYLON) {
  25694. var Animatable = (function () {
  25695. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  25696. if (fromFrame === void 0) { fromFrame = 0; }
  25697. if (toFrame === void 0) { toFrame = 100; }
  25698. if (loopAnimation === void 0) { loopAnimation = false; }
  25699. if (speedRatio === void 0) { speedRatio = 1.0; }
  25700. this.target = target;
  25701. this.fromFrame = fromFrame;
  25702. this.toFrame = toFrame;
  25703. this.loopAnimation = loopAnimation;
  25704. this.speedRatio = speedRatio;
  25705. this.onAnimationEnd = onAnimationEnd;
  25706. this._animations = new Array();
  25707. this._paused = false;
  25708. this.animationStarted = false;
  25709. if (animations) {
  25710. this.appendAnimations(target, animations);
  25711. }
  25712. this._scene = scene;
  25713. scene._activeAnimatables.push(this);
  25714. }
  25715. // Methods
  25716. Animatable.prototype.getAnimations = function () {
  25717. return this._animations;
  25718. };
  25719. Animatable.prototype.appendAnimations = function (target, animations) {
  25720. for (var index = 0; index < animations.length; index++) {
  25721. var animation = animations[index];
  25722. animation._target = target;
  25723. this._animations.push(animation);
  25724. }
  25725. };
  25726. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  25727. var animations = this._animations;
  25728. for (var index = 0; index < animations.length; index++) {
  25729. if (animations[index].targetProperty === property) {
  25730. return animations[index];
  25731. }
  25732. }
  25733. return null;
  25734. };
  25735. Animatable.prototype.reset = function () {
  25736. var animations = this._animations;
  25737. for (var index = 0; index < animations.length; index++) {
  25738. animations[index].reset();
  25739. }
  25740. this._localDelayOffset = null;
  25741. this._pausedDelay = null;
  25742. };
  25743. Animatable.prototype.enableBlending = function (blendingSpeed) {
  25744. var animations = this._animations;
  25745. for (var index = 0; index < animations.length; index++) {
  25746. animations[index].enableBlending = true;
  25747. animations[index].blendingSpeed = blendingSpeed;
  25748. }
  25749. };
  25750. Animatable.prototype.disableBlending = function () {
  25751. var animations = this._animations;
  25752. for (var index = 0; index < animations.length; index++) {
  25753. animations[index].enableBlending = false;
  25754. }
  25755. };
  25756. Animatable.prototype.goToFrame = function (frame) {
  25757. var animations = this._animations;
  25758. for (var index = 0; index < animations.length; index++) {
  25759. animations[index].goToFrame(frame);
  25760. }
  25761. };
  25762. Animatable.prototype.pause = function () {
  25763. if (this._paused) {
  25764. return;
  25765. }
  25766. this._paused = true;
  25767. };
  25768. Animatable.prototype.restart = function () {
  25769. this._paused = false;
  25770. };
  25771. Animatable.prototype.stop = function () {
  25772. var index = this._scene._activeAnimatables.indexOf(this);
  25773. if (index > -1) {
  25774. this._scene._activeAnimatables.splice(index, 1);
  25775. var animations = this._animations;
  25776. for (var index = 0; index < animations.length; index++) {
  25777. animations[index].reset();
  25778. }
  25779. if (this.onAnimationEnd) {
  25780. this.onAnimationEnd();
  25781. }
  25782. }
  25783. };
  25784. Animatable.prototype._animate = function (delay) {
  25785. if (this._paused) {
  25786. this.animationStarted = false;
  25787. if (!this._pausedDelay) {
  25788. this._pausedDelay = delay;
  25789. }
  25790. return true;
  25791. }
  25792. if (!this._localDelayOffset) {
  25793. this._localDelayOffset = delay;
  25794. }
  25795. else if (this._pausedDelay) {
  25796. this._localDelayOffset += delay - this._pausedDelay;
  25797. this._pausedDelay = null;
  25798. }
  25799. // Animating
  25800. var running = false;
  25801. var animations = this._animations;
  25802. var index;
  25803. for (index = 0; index < animations.length; index++) {
  25804. var animation = animations[index];
  25805. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  25806. running = running || isRunning;
  25807. }
  25808. this.animationStarted = running;
  25809. if (!running) {
  25810. // Remove from active animatables
  25811. index = this._scene._activeAnimatables.indexOf(this);
  25812. this._scene._activeAnimatables.splice(index, 1);
  25813. }
  25814. if (!running && this.onAnimationEnd) {
  25815. this.onAnimationEnd();
  25816. this.onAnimationEnd = null;
  25817. }
  25818. return running;
  25819. };
  25820. return Animatable;
  25821. })();
  25822. BABYLON.Animatable = Animatable;
  25823. })(BABYLON || (BABYLON = {}));
  25824. var BABYLON;
  25825. (function (BABYLON) {
  25826. var EasingFunction = (function () {
  25827. function EasingFunction() {
  25828. // Properties
  25829. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  25830. }
  25831. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  25832. get: function () {
  25833. return EasingFunction._EASINGMODE_EASEIN;
  25834. },
  25835. enumerable: true,
  25836. configurable: true
  25837. });
  25838. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  25839. get: function () {
  25840. return EasingFunction._EASINGMODE_EASEOUT;
  25841. },
  25842. enumerable: true,
  25843. configurable: true
  25844. });
  25845. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  25846. get: function () {
  25847. return EasingFunction._EASINGMODE_EASEINOUT;
  25848. },
  25849. enumerable: true,
  25850. configurable: true
  25851. });
  25852. EasingFunction.prototype.setEasingMode = function (easingMode) {
  25853. var n = Math.min(Math.max(easingMode, 0), 2);
  25854. this._easingMode = n;
  25855. };
  25856. EasingFunction.prototype.getEasingMode = function () {
  25857. return this._easingMode;
  25858. };
  25859. EasingFunction.prototype.easeInCore = function (gradient) {
  25860. throw new Error('You must implement this method');
  25861. };
  25862. EasingFunction.prototype.ease = function (gradient) {
  25863. switch (this._easingMode) {
  25864. case EasingFunction.EASINGMODE_EASEIN:
  25865. return this.easeInCore(gradient);
  25866. case EasingFunction.EASINGMODE_EASEOUT:
  25867. return (1 - this.easeInCore(1 - gradient));
  25868. }
  25869. if (gradient >= 0.5) {
  25870. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  25871. }
  25872. return (this.easeInCore(gradient * 2) * 0.5);
  25873. };
  25874. //Statics
  25875. EasingFunction._EASINGMODE_EASEIN = 0;
  25876. EasingFunction._EASINGMODE_EASEOUT = 1;
  25877. EasingFunction._EASINGMODE_EASEINOUT = 2;
  25878. return EasingFunction;
  25879. })();
  25880. BABYLON.EasingFunction = EasingFunction;
  25881. var CircleEase = (function (_super) {
  25882. __extends(CircleEase, _super);
  25883. function CircleEase() {
  25884. _super.apply(this, arguments);
  25885. }
  25886. CircleEase.prototype.easeInCore = function (gradient) {
  25887. gradient = Math.max(0, Math.min(1, gradient));
  25888. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  25889. };
  25890. return CircleEase;
  25891. })(EasingFunction);
  25892. BABYLON.CircleEase = CircleEase;
  25893. var BackEase = (function (_super) {
  25894. __extends(BackEase, _super);
  25895. function BackEase(amplitude) {
  25896. if (amplitude === void 0) { amplitude = 1; }
  25897. _super.call(this);
  25898. this.amplitude = amplitude;
  25899. }
  25900. BackEase.prototype.easeInCore = function (gradient) {
  25901. var num = Math.max(0, this.amplitude);
  25902. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  25903. };
  25904. return BackEase;
  25905. })(EasingFunction);
  25906. BABYLON.BackEase = BackEase;
  25907. var BounceEase = (function (_super) {
  25908. __extends(BounceEase, _super);
  25909. function BounceEase(bounces, bounciness) {
  25910. if (bounces === void 0) { bounces = 3; }
  25911. if (bounciness === void 0) { bounciness = 2; }
  25912. _super.call(this);
  25913. this.bounces = bounces;
  25914. this.bounciness = bounciness;
  25915. }
  25916. BounceEase.prototype.easeInCore = function (gradient) {
  25917. var y = Math.max(0.0, this.bounces);
  25918. var bounciness = this.bounciness;
  25919. if (bounciness <= 1.0) {
  25920. bounciness = 1.001;
  25921. }
  25922. var num9 = Math.pow(bounciness, y);
  25923. var num5 = 1.0 - bounciness;
  25924. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  25925. var num15 = gradient * num4;
  25926. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  25927. var num3 = Math.floor(num65);
  25928. var num13 = num3 + 1.0;
  25929. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  25930. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  25931. var num7 = (num8 + num12) * 0.5;
  25932. var num6 = gradient - num7;
  25933. var num2 = num7 - num8;
  25934. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  25935. };
  25936. return BounceEase;
  25937. })(EasingFunction);
  25938. BABYLON.BounceEase = BounceEase;
  25939. var CubicEase = (function (_super) {
  25940. __extends(CubicEase, _super);
  25941. function CubicEase() {
  25942. _super.apply(this, arguments);
  25943. }
  25944. CubicEase.prototype.easeInCore = function (gradient) {
  25945. return (gradient * gradient * gradient);
  25946. };
  25947. return CubicEase;
  25948. })(EasingFunction);
  25949. BABYLON.CubicEase = CubicEase;
  25950. var ElasticEase = (function (_super) {
  25951. __extends(ElasticEase, _super);
  25952. function ElasticEase(oscillations, springiness) {
  25953. if (oscillations === void 0) { oscillations = 3; }
  25954. if (springiness === void 0) { springiness = 3; }
  25955. _super.call(this);
  25956. this.oscillations = oscillations;
  25957. this.springiness = springiness;
  25958. }
  25959. ElasticEase.prototype.easeInCore = function (gradient) {
  25960. var num2;
  25961. var num3 = Math.max(0.0, this.oscillations);
  25962. var num = Math.max(0.0, this.springiness);
  25963. if (num == 0) {
  25964. num2 = gradient;
  25965. }
  25966. else {
  25967. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  25968. }
  25969. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  25970. };
  25971. return ElasticEase;
  25972. })(EasingFunction);
  25973. BABYLON.ElasticEase = ElasticEase;
  25974. var ExponentialEase = (function (_super) {
  25975. __extends(ExponentialEase, _super);
  25976. function ExponentialEase(exponent) {
  25977. if (exponent === void 0) { exponent = 2; }
  25978. _super.call(this);
  25979. this.exponent = exponent;
  25980. }
  25981. ExponentialEase.prototype.easeInCore = function (gradient) {
  25982. if (this.exponent <= 0) {
  25983. return gradient;
  25984. }
  25985. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  25986. };
  25987. return ExponentialEase;
  25988. })(EasingFunction);
  25989. BABYLON.ExponentialEase = ExponentialEase;
  25990. var PowerEase = (function (_super) {
  25991. __extends(PowerEase, _super);
  25992. function PowerEase(power) {
  25993. if (power === void 0) { power = 2; }
  25994. _super.call(this);
  25995. this.power = power;
  25996. }
  25997. PowerEase.prototype.easeInCore = function (gradient) {
  25998. var y = Math.max(0.0, this.power);
  25999. return Math.pow(gradient, y);
  26000. };
  26001. return PowerEase;
  26002. })(EasingFunction);
  26003. BABYLON.PowerEase = PowerEase;
  26004. var QuadraticEase = (function (_super) {
  26005. __extends(QuadraticEase, _super);
  26006. function QuadraticEase() {
  26007. _super.apply(this, arguments);
  26008. }
  26009. QuadraticEase.prototype.easeInCore = function (gradient) {
  26010. return (gradient * gradient);
  26011. };
  26012. return QuadraticEase;
  26013. })(EasingFunction);
  26014. BABYLON.QuadraticEase = QuadraticEase;
  26015. var QuarticEase = (function (_super) {
  26016. __extends(QuarticEase, _super);
  26017. function QuarticEase() {
  26018. _super.apply(this, arguments);
  26019. }
  26020. QuarticEase.prototype.easeInCore = function (gradient) {
  26021. return (gradient * gradient * gradient * gradient);
  26022. };
  26023. return QuarticEase;
  26024. })(EasingFunction);
  26025. BABYLON.QuarticEase = QuarticEase;
  26026. var QuinticEase = (function (_super) {
  26027. __extends(QuinticEase, _super);
  26028. function QuinticEase() {
  26029. _super.apply(this, arguments);
  26030. }
  26031. QuinticEase.prototype.easeInCore = function (gradient) {
  26032. return (gradient * gradient * gradient * gradient * gradient);
  26033. };
  26034. return QuinticEase;
  26035. })(EasingFunction);
  26036. BABYLON.QuinticEase = QuinticEase;
  26037. var SineEase = (function (_super) {
  26038. __extends(SineEase, _super);
  26039. function SineEase() {
  26040. _super.apply(this, arguments);
  26041. }
  26042. SineEase.prototype.easeInCore = function (gradient) {
  26043. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  26044. };
  26045. return SineEase;
  26046. })(EasingFunction);
  26047. BABYLON.SineEase = SineEase;
  26048. var BezierCurveEase = (function (_super) {
  26049. __extends(BezierCurveEase, _super);
  26050. function BezierCurveEase(x1, y1, x2, y2) {
  26051. if (x1 === void 0) { x1 = 0; }
  26052. if (y1 === void 0) { y1 = 0; }
  26053. if (x2 === void 0) { x2 = 1; }
  26054. if (y2 === void 0) { y2 = 1; }
  26055. _super.call(this);
  26056. this.x1 = x1;
  26057. this.y1 = y1;
  26058. this.x2 = x2;
  26059. this.y2 = y2;
  26060. }
  26061. BezierCurveEase.prototype.easeInCore = function (gradient) {
  26062. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  26063. };
  26064. return BezierCurveEase;
  26065. })(EasingFunction);
  26066. BABYLON.BezierCurveEase = BezierCurveEase;
  26067. })(BABYLON || (BABYLON = {}));
  26068. var BABYLON;
  26069. (function (BABYLON) {
  26070. var Bone = (function (_super) {
  26071. __extends(Bone, _super);
  26072. function Bone(name, skeleton, parentBone, matrix, restPose) {
  26073. _super.call(this, name, skeleton.getScene());
  26074. this.name = name;
  26075. this.children = new Array();
  26076. this.animations = new Array();
  26077. this._worldTransform = new BABYLON.Matrix();
  26078. this._absoluteTransform = new BABYLON.Matrix();
  26079. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  26080. this._skeleton = skeleton;
  26081. this._matrix = matrix;
  26082. this._baseMatrix = matrix;
  26083. this._restPose = restPose ? restPose : matrix.clone();
  26084. skeleton.bones.push(this);
  26085. if (parentBone) {
  26086. this._parent = parentBone;
  26087. parentBone.children.push(this);
  26088. }
  26089. else {
  26090. this._parent = null;
  26091. }
  26092. this._updateDifferenceMatrix();
  26093. }
  26094. // Members
  26095. Bone.prototype.getParent = function () {
  26096. return this._parent;
  26097. };
  26098. Bone.prototype.getLocalMatrix = function () {
  26099. return this._matrix;
  26100. };
  26101. Bone.prototype.getBaseMatrix = function () {
  26102. return this._baseMatrix;
  26103. };
  26104. Bone.prototype.getRestPose = function () {
  26105. return this._restPose;
  26106. };
  26107. Bone.prototype.returnToRest = function () {
  26108. this.updateMatrix(this._restPose.clone());
  26109. };
  26110. Bone.prototype.getWorldMatrix = function () {
  26111. return this._worldTransform;
  26112. };
  26113. Bone.prototype.getInvertedAbsoluteTransform = function () {
  26114. return this._invertedAbsoluteTransform;
  26115. };
  26116. Bone.prototype.getAbsoluteTransform = function () {
  26117. return this._absoluteTransform;
  26118. };
  26119. // Methods
  26120. Bone.prototype.updateMatrix = function (matrix) {
  26121. this._baseMatrix = matrix.clone();
  26122. this._matrix = matrix.clone();
  26123. this._skeleton._markAsDirty();
  26124. this._updateDifferenceMatrix();
  26125. };
  26126. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  26127. if (!rootMatrix) {
  26128. rootMatrix = this._baseMatrix;
  26129. }
  26130. if (this._parent) {
  26131. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  26132. }
  26133. else {
  26134. this._absoluteTransform.copyFrom(rootMatrix);
  26135. }
  26136. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  26137. for (var index = 0; index < this.children.length; index++) {
  26138. this.children[index]._updateDifferenceMatrix();
  26139. }
  26140. };
  26141. Bone.prototype.markAsDirty = function () {
  26142. this._currentRenderId++;
  26143. this._skeleton._markAsDirty();
  26144. };
  26145. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired) {
  26146. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  26147. // all animation may be coming from a library skeleton, so may need to create animation
  26148. if (this.animations.length === 0) {
  26149. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  26150. this.animations[0].setKeys([]);
  26151. }
  26152. // get animation info / verify there is such a range from the source bone
  26153. var sourceRange = source.animations[0].getRange(rangeName);
  26154. if (!sourceRange) {
  26155. return false;
  26156. }
  26157. var from = sourceRange.from;
  26158. var to = sourceRange.to;
  26159. var sourceKeys = source.animations[0].getKeys();
  26160. // rescaling prep
  26161. var sourceBoneLength = source.length;
  26162. var scalingReqd = rescaleAsRequired && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  26163. var ratio = scalingReqd ? this.length / sourceBoneLength : null;
  26164. var destKeys = this.animations[0].getKeys();
  26165. // loop vars declaration / initialization
  26166. var orig;
  26167. var origScale = scalingReqd ? BABYLON.Vector3.Zero() : null;
  26168. var origRotation = scalingReqd ? new BABYLON.Quaternion() : null;
  26169. var origTranslation = scalingReqd ? BABYLON.Vector3.Zero() : null;
  26170. var mat;
  26171. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  26172. orig = sourceKeys[key];
  26173. if (orig.frame >= from && orig.frame <= to) {
  26174. if (scalingReqd) {
  26175. orig.value.decompose(origScale, origRotation, origTranslation);
  26176. origTranslation.scaleInPlace(ratio);
  26177. mat = BABYLON.Matrix.Compose(origScale, origRotation, origTranslation);
  26178. }
  26179. else {
  26180. mat = orig.value;
  26181. }
  26182. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  26183. }
  26184. }
  26185. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  26186. return true;
  26187. };
  26188. return Bone;
  26189. })(BABYLON.Node);
  26190. BABYLON.Bone = Bone;
  26191. })(BABYLON || (BABYLON = {}));
  26192. var BABYLON;
  26193. (function (BABYLON) {
  26194. var Skeleton = (function () {
  26195. function Skeleton(name, id, scene) {
  26196. this.name = name;
  26197. this.id = id;
  26198. this.bones = new Array();
  26199. this.needInitialSkinMatrix = false;
  26200. this._isDirty = true;
  26201. this._meshesWithPoseMatrix = new Array();
  26202. this._identity = BABYLON.Matrix.Identity();
  26203. this._ranges = {};
  26204. this.bones = [];
  26205. this._scene = scene;
  26206. scene.skeletons.push(this);
  26207. //make sure it will recalculate the matrix next time prepare is called.
  26208. this._isDirty = true;
  26209. }
  26210. // Members
  26211. Skeleton.prototype.getTransformMatrices = function (mesh) {
  26212. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  26213. return mesh._bonesTransformMatrices;
  26214. }
  26215. return this._transformMatrices;
  26216. };
  26217. Skeleton.prototype.getScene = function () {
  26218. return this._scene;
  26219. };
  26220. // Methods
  26221. /**
  26222. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26223. */
  26224. Skeleton.prototype.toString = function (fullDetails) {
  26225. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  26226. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  26227. if (fullDetails) {
  26228. ret += ", Ranges: {";
  26229. var first = true;
  26230. for (var name in this._ranges) {
  26231. if (!first) {
  26232. ret + ", ";
  26233. first = false;
  26234. }
  26235. ret += name;
  26236. }
  26237. ret += "}";
  26238. }
  26239. return ret;
  26240. };
  26241. /**
  26242. * Get bone's index searching by name
  26243. * @param {string} name is bone's name to search for
  26244. * @return {number} Indice of the bone. Returns -1 if not found
  26245. */
  26246. Skeleton.prototype.getBoneIndexByName = function (name) {
  26247. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  26248. if (this.bones[boneIndex].name === name) {
  26249. return boneIndex;
  26250. }
  26251. }
  26252. return -1;
  26253. };
  26254. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  26255. // check name not already in use
  26256. if (!this._ranges[name]) {
  26257. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  26258. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26259. if (this.bones[i].animations[0]) {
  26260. this.bones[i].animations[0].createRange(name, from, to);
  26261. }
  26262. }
  26263. }
  26264. };
  26265. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  26266. if (deleteFrames === void 0) { deleteFrames = true; }
  26267. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26268. if (this.bones[i].animations[0]) {
  26269. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  26270. }
  26271. }
  26272. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  26273. };
  26274. Skeleton.prototype.getAnimationRange = function (name) {
  26275. return this._ranges[name];
  26276. };
  26277. /**
  26278. * Returns as an Array, all AnimationRanges defined on this skeleton
  26279. */
  26280. Skeleton.prototype.getAnimationRanges = function () {
  26281. var animationRanges = [];
  26282. var name;
  26283. var i = 0;
  26284. for (name in this._ranges) {
  26285. animationRanges[i] = this._ranges[name];
  26286. i++;
  26287. }
  26288. return animationRanges;
  26289. };
  26290. /**
  26291. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  26292. */
  26293. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  26294. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  26295. if (this._ranges[name] || !source.getAnimationRange(name)) {
  26296. return false;
  26297. }
  26298. var ret = true;
  26299. var frameOffset = this._getHighestAnimationFrame() + 1;
  26300. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  26301. var boneDict = {};
  26302. var sourceBones = source.bones;
  26303. for (var i = 0, nBones = sourceBones.length; i < nBones; i++) {
  26304. boneDict[sourceBones[i].name] = sourceBones[i];
  26305. }
  26306. if (this.bones.length !== sourceBones.length) {
  26307. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  26308. ret = false;
  26309. }
  26310. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26311. var boneName = this.bones[i].name;
  26312. var sourceBone = boneDict[boneName];
  26313. if (sourceBone) {
  26314. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired);
  26315. }
  26316. else {
  26317. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  26318. ret = false;
  26319. }
  26320. }
  26321. // do not call createAnimationRange(), since it also is done to bones, which was already done
  26322. var range = source.getAnimationRange(name);
  26323. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  26324. return ret;
  26325. };
  26326. Skeleton.prototype.returnToRest = function () {
  26327. for (var index = 0; index < this.bones.length; index++) {
  26328. this.bones[index].returnToRest();
  26329. }
  26330. };
  26331. Skeleton.prototype._getHighestAnimationFrame = function () {
  26332. var ret = 0;
  26333. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  26334. if (this.bones[i].animations[0]) {
  26335. var highest = this.bones[i].animations[0].getHighestFrame();
  26336. if (ret < highest) {
  26337. ret = highest;
  26338. }
  26339. }
  26340. }
  26341. return ret;
  26342. };
  26343. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  26344. var range = this.getAnimationRange(name);
  26345. if (!range) {
  26346. return null;
  26347. }
  26348. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  26349. };
  26350. Skeleton.prototype._markAsDirty = function () {
  26351. this._isDirty = true;
  26352. };
  26353. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  26354. this._meshesWithPoseMatrix.push(mesh);
  26355. };
  26356. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  26357. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  26358. if (index > -1) {
  26359. this._meshesWithPoseMatrix.splice(index, 1);
  26360. }
  26361. };
  26362. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  26363. for (var index = 0; index < this.bones.length; index++) {
  26364. var bone = this.bones[index];
  26365. var parentBone = bone.getParent();
  26366. if (parentBone) {
  26367. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  26368. }
  26369. else {
  26370. if (initialSkinMatrix) {
  26371. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  26372. }
  26373. else {
  26374. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  26375. }
  26376. }
  26377. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  26378. }
  26379. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  26380. };
  26381. Skeleton.prototype.prepare = function () {
  26382. if (!this._isDirty) {
  26383. return;
  26384. }
  26385. if (this.needInitialSkinMatrix) {
  26386. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  26387. var mesh = this._meshesWithPoseMatrix[index];
  26388. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  26389. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  26390. }
  26391. var poseMatrix = mesh.getPoseMatrix();
  26392. // Prepare bones
  26393. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  26394. var bone = this.bones[boneIndex];
  26395. if (!bone.getParent()) {
  26396. var matrix = bone.getBaseMatrix();
  26397. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  26398. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  26399. }
  26400. }
  26401. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  26402. }
  26403. }
  26404. else {
  26405. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  26406. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  26407. }
  26408. this._computeTransformMatrices(this._transformMatrices, null);
  26409. }
  26410. this._isDirty = false;
  26411. this._scene._activeBones += this.bones.length;
  26412. };
  26413. Skeleton.prototype.getAnimatables = function () {
  26414. if (!this._animatables || this._animatables.length !== this.bones.length) {
  26415. this._animatables = [];
  26416. for (var index = 0; index < this.bones.length; index++) {
  26417. this._animatables.push(this.bones[index]);
  26418. }
  26419. }
  26420. return this._animatables;
  26421. };
  26422. Skeleton.prototype.clone = function (name, id) {
  26423. var result = new Skeleton(name, id || name, this._scene);
  26424. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  26425. for (var index = 0; index < this.bones.length; index++) {
  26426. var source = this.bones[index];
  26427. var parentBone = null;
  26428. if (source.getParent()) {
  26429. var parentIndex = this.bones.indexOf(source.getParent());
  26430. parentBone = result.bones[parentIndex];
  26431. }
  26432. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  26433. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  26434. }
  26435. if (this._ranges) {
  26436. result._ranges = {};
  26437. for (var rangeName in this._ranges) {
  26438. result._ranges[rangeName] = this._ranges[rangeName].clone();
  26439. }
  26440. }
  26441. this._isDirty = true;
  26442. return result;
  26443. };
  26444. Skeleton.prototype.dispose = function () {
  26445. this._meshesWithPoseMatrix = [];
  26446. // Animations
  26447. this.getScene().stopAnimation(this);
  26448. // Remove from scene
  26449. this.getScene().removeSkeleton(this);
  26450. };
  26451. Skeleton.prototype.serialize = function () {
  26452. var serializationObject = {};
  26453. serializationObject.name = this.name;
  26454. serializationObject.id = this.id;
  26455. serializationObject.bones = [];
  26456. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  26457. for (var index = 0; index < this.bones.length; index++) {
  26458. var bone = this.bones[index];
  26459. var serializedBone = {
  26460. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  26461. name: bone.name,
  26462. matrix: bone.getLocalMatrix().toArray(),
  26463. rest: bone.getRestPose().toArray()
  26464. };
  26465. serializationObject.bones.push(serializedBone);
  26466. if (bone.length) {
  26467. serializedBone.length = bone.length;
  26468. }
  26469. if (bone.animations && bone.animations.length > 0) {
  26470. serializedBone.animation = bone.animations[0].serialize();
  26471. }
  26472. serializationObject.ranges = [];
  26473. for (var name in this._ranges) {
  26474. var range = {};
  26475. range.name = name;
  26476. range.from = this._ranges[name].from;
  26477. range.to = this._ranges[name].to;
  26478. serializationObject.ranges.push(range);
  26479. }
  26480. }
  26481. return serializationObject;
  26482. };
  26483. Skeleton.Parse = function (parsedSkeleton, scene) {
  26484. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  26485. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  26486. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  26487. var parsedBone = parsedSkeleton.bones[index];
  26488. var parentBone = null;
  26489. if (parsedBone.parentBoneIndex > -1) {
  26490. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  26491. }
  26492. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  26493. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  26494. if (parsedBone.length) {
  26495. bone.length = parsedBone.length;
  26496. }
  26497. if (parsedBone.animation) {
  26498. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  26499. }
  26500. }
  26501. // placed after bones, so createAnimationRange can cascade down
  26502. if (parsedSkeleton.ranges) {
  26503. for (var index = 0; index < parsedSkeleton.ranges.length; index++) {
  26504. var data = parsedSkeleton.ranges[index];
  26505. skeleton.createAnimationRange(data.name, data.from, data.to);
  26506. }
  26507. }
  26508. return skeleton;
  26509. };
  26510. return Skeleton;
  26511. })();
  26512. BABYLON.Skeleton = Skeleton;
  26513. })(BABYLON || (BABYLON = {}));
  26514. var BABYLON;
  26515. (function (BABYLON) {
  26516. var PostProcess = (function () {
  26517. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines, textureType) {
  26518. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  26519. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  26520. this.name = name;
  26521. this.width = -1;
  26522. this.height = -1;
  26523. this._reusable = false;
  26524. this._textures = new BABYLON.SmartArray(2);
  26525. this._currentRenderTextureInd = 0;
  26526. if (camera != null) {
  26527. this._camera = camera;
  26528. this._scene = camera.getScene();
  26529. camera.attachPostProcess(this);
  26530. this._engine = this._scene.getEngine();
  26531. }
  26532. else {
  26533. this._engine = engine;
  26534. }
  26535. this._renderRatio = ratio;
  26536. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  26537. this._reusable = reusable || false;
  26538. this._textureType = textureType;
  26539. this._samplers = samplers || [];
  26540. this._samplers.push("textureSampler");
  26541. this._fragmentUrl = fragmentUrl;
  26542. this._parameters = parameters || [];
  26543. this.updateEffect(defines);
  26544. }
  26545. PostProcess.prototype.updateEffect = function (defines) {
  26546. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  26547. };
  26548. PostProcess.prototype.isReusable = function () {
  26549. return this._reusable;
  26550. };
  26551. PostProcess.prototype.activate = function (camera, sourceTexture) {
  26552. camera = camera || this._camera;
  26553. var scene = camera.getScene();
  26554. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  26555. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  26556. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  26557. desiredWidth = this._renderRatio.width || BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  26558. desiredHeight = this._renderRatio.height || BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  26559. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  26560. if (this._textures.length > 0) {
  26561. for (var i = 0; i < this._textures.length; i++) {
  26562. this._engine._releaseTexture(this._textures.data[i]);
  26563. }
  26564. this._textures.reset();
  26565. }
  26566. this.width = desiredWidth;
  26567. this.height = desiredHeight;
  26568. 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 }));
  26569. if (this._reusable) {
  26570. 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 }));
  26571. }
  26572. if (this.onSizeChanged) {
  26573. this.onSizeChanged();
  26574. }
  26575. }
  26576. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  26577. if (this.onActivate) {
  26578. this.onActivate(camera);
  26579. }
  26580. // Clear
  26581. if (this.clearColor) {
  26582. this._engine.clear(this.clearColor, true, true);
  26583. }
  26584. else {
  26585. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  26586. }
  26587. if (this._reusable) {
  26588. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  26589. }
  26590. };
  26591. Object.defineProperty(PostProcess.prototype, "isSupported", {
  26592. get: function () {
  26593. return this._effect.isSupported;
  26594. },
  26595. enumerable: true,
  26596. configurable: true
  26597. });
  26598. PostProcess.prototype.apply = function () {
  26599. // Check
  26600. if (!this._effect.isReady())
  26601. return null;
  26602. // States
  26603. this._engine.enableEffect(this._effect);
  26604. this._engine.setState(false);
  26605. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26606. this._engine.setDepthBuffer(false);
  26607. this._engine.setDepthWrite(false);
  26608. // Texture
  26609. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  26610. // Parameters
  26611. if (this.onApply) {
  26612. this.onApply(this._effect);
  26613. }
  26614. return this._effect;
  26615. };
  26616. PostProcess.prototype.dispose = function (camera) {
  26617. camera = camera || this._camera;
  26618. if (this._textures.length > 0) {
  26619. for (var i = 0; i < this._textures.length; i++) {
  26620. this._engine._releaseTexture(this._textures.data[i]);
  26621. }
  26622. this._textures.reset();
  26623. }
  26624. if (!camera) {
  26625. return;
  26626. }
  26627. camera.detachPostProcess(this);
  26628. var index = camera._postProcesses.indexOf(this);
  26629. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  26630. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  26631. }
  26632. };
  26633. return PostProcess;
  26634. })();
  26635. BABYLON.PostProcess = PostProcess;
  26636. })(BABYLON || (BABYLON = {}));
  26637. var BABYLON;
  26638. (function (BABYLON) {
  26639. var PostProcessManager = (function () {
  26640. function PostProcessManager(scene) {
  26641. this._vertexDeclaration = [2];
  26642. this._vertexStrideSize = 2 * 4;
  26643. this._scene = scene;
  26644. }
  26645. PostProcessManager.prototype._prepareBuffers = function () {
  26646. if (this._vertexBuffer) {
  26647. return;
  26648. }
  26649. // VBO
  26650. var vertices = [];
  26651. vertices.push(1, 1);
  26652. vertices.push(-1, 1);
  26653. vertices.push(-1, -1);
  26654. vertices.push(1, -1);
  26655. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  26656. // Indices
  26657. var indices = [];
  26658. indices.push(0);
  26659. indices.push(1);
  26660. indices.push(2);
  26661. indices.push(0);
  26662. indices.push(2);
  26663. indices.push(3);
  26664. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  26665. };
  26666. // Methods
  26667. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  26668. var postProcesses = this._scene.activeCamera._postProcesses;
  26669. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  26670. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  26671. return false;
  26672. }
  26673. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  26674. return true;
  26675. };
  26676. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  26677. var engine = this._scene.getEngine();
  26678. for (var index = 0; index < postProcesses.length; index++) {
  26679. if (index < postProcesses.length - 1) {
  26680. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  26681. }
  26682. else {
  26683. if (targetTexture) {
  26684. engine.bindFramebuffer(targetTexture);
  26685. }
  26686. else {
  26687. engine.restoreDefaultFramebuffer();
  26688. }
  26689. }
  26690. var pp = postProcesses[index];
  26691. var effect = pp.apply();
  26692. if (effect) {
  26693. if (pp.onBeforeRender) {
  26694. pp.onBeforeRender(effect);
  26695. }
  26696. // VBOs
  26697. this._prepareBuffers();
  26698. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  26699. // Draw order
  26700. engine.draw(true, 0, 6);
  26701. if (pp.onAfterRender) {
  26702. pp.onAfterRender(effect);
  26703. }
  26704. }
  26705. }
  26706. // Restore depth buffer
  26707. engine.setDepthBuffer(true);
  26708. engine.setDepthWrite(true);
  26709. };
  26710. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  26711. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  26712. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  26713. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  26714. return;
  26715. }
  26716. var engine = this._scene.getEngine();
  26717. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  26718. if (index < postProcessesTakenIndices.length - 1) {
  26719. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera, targetTexture);
  26720. }
  26721. else {
  26722. if (targetTexture) {
  26723. engine.bindFramebuffer(targetTexture, faceIndex);
  26724. }
  26725. else {
  26726. engine.restoreDefaultFramebuffer();
  26727. }
  26728. }
  26729. if (doNotPresent) {
  26730. break;
  26731. }
  26732. var pp = postProcesses[postProcessesTakenIndices[index]];
  26733. var effect = pp.apply();
  26734. if (effect) {
  26735. if (pp.onBeforeRender) {
  26736. pp.onBeforeRender(effect);
  26737. }
  26738. // VBOs
  26739. this._prepareBuffers();
  26740. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  26741. // Draw order
  26742. engine.draw(true, 0, 6);
  26743. if (pp.onAfterRender) {
  26744. pp.onAfterRender(effect);
  26745. }
  26746. }
  26747. }
  26748. // Restore depth buffer
  26749. engine.setDepthBuffer(true);
  26750. engine.setDepthWrite(true);
  26751. };
  26752. PostProcessManager.prototype.dispose = function () {
  26753. if (this._vertexBuffer) {
  26754. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  26755. this._vertexBuffer = null;
  26756. }
  26757. if (this._indexBuffer) {
  26758. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26759. this._indexBuffer = null;
  26760. }
  26761. };
  26762. return PostProcessManager;
  26763. })();
  26764. BABYLON.PostProcessManager = PostProcessManager;
  26765. })(BABYLON || (BABYLON = {}));
  26766. var BABYLON;
  26767. (function (BABYLON) {
  26768. var PassPostProcess = (function (_super) {
  26769. __extends(PassPostProcess, _super);
  26770. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  26771. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  26772. }
  26773. return PassPostProcess;
  26774. })(BABYLON.PostProcess);
  26775. BABYLON.PassPostProcess = PassPostProcess;
  26776. })(BABYLON || (BABYLON = {}));
  26777. var BABYLON;
  26778. (function (BABYLON) {
  26779. /**
  26780. * This is a holder class for the physics joint created by the physics plugin.
  26781. * It holds a set of functions to control the underlying joint.
  26782. */
  26783. var PhysicsJoint = (function () {
  26784. function PhysicsJoint(type, jointData) {
  26785. this.type = type;
  26786. this.jointData = jointData;
  26787. jointData.nativeParams = jointData.nativeParams || {};
  26788. }
  26789. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  26790. get: function () {
  26791. return this._physicsJoint;
  26792. },
  26793. set: function (newJoint) {
  26794. if (this._physicsJoint) {
  26795. }
  26796. this._physicsJoint = newJoint;
  26797. },
  26798. enumerable: true,
  26799. configurable: true
  26800. });
  26801. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  26802. set: function (physicsPlugin) {
  26803. this._physicsPlugin = physicsPlugin;
  26804. },
  26805. enumerable: true,
  26806. configurable: true
  26807. });
  26808. /**
  26809. * Execute a function that is physics-plugin specific.
  26810. * @param {Function} func the function that will be executed.
  26811. * It accepts two parameters: the physics world and the physics joint.
  26812. */
  26813. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  26814. func(this._physicsPlugin.world, this._physicsJoint);
  26815. };
  26816. //TODO check if the native joints are the same
  26817. //Joint Types
  26818. PhysicsJoint.DistanceJoint = 0;
  26819. PhysicsJoint.HingeJoint = 1;
  26820. PhysicsJoint.BallAndSocketJoint = 2;
  26821. PhysicsJoint.WheelJoint = 3;
  26822. PhysicsJoint.SliderJoint = 4;
  26823. //OIMO
  26824. PhysicsJoint.PrismaticJoint = 5;
  26825. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  26826. PhysicsJoint.UniversalJoint = 6;
  26827. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  26828. //Cannon
  26829. //Similar to a Ball-Joint. Different in params
  26830. PhysicsJoint.PointToPointJoint = 8;
  26831. //Cannon only at the moment
  26832. PhysicsJoint.SpringJoint = 9;
  26833. return PhysicsJoint;
  26834. })();
  26835. BABYLON.PhysicsJoint = PhysicsJoint;
  26836. /**
  26837. * A class representing a physics distance joint.
  26838. */
  26839. var DistanceJoint = (function (_super) {
  26840. __extends(DistanceJoint, _super);
  26841. function DistanceJoint(jointData) {
  26842. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  26843. }
  26844. /**
  26845. * Update the predefined distance.
  26846. */
  26847. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  26848. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  26849. };
  26850. return DistanceJoint;
  26851. })(PhysicsJoint);
  26852. BABYLON.DistanceJoint = DistanceJoint;
  26853. /**
  26854. * This class represents a single hinge physics joint
  26855. */
  26856. var HingeJoint = (function (_super) {
  26857. __extends(HingeJoint, _super);
  26858. function HingeJoint(jointData) {
  26859. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  26860. }
  26861. /**
  26862. * Set the motor values.
  26863. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26864. * @param {number} force the force to apply
  26865. * @param {number} maxForce max force for this motor.
  26866. */
  26867. HingeJoint.prototype.setMotor = function (force, maxForce) {
  26868. this._physicsPlugin.setMotor(this, force, maxForce);
  26869. };
  26870. /**
  26871. * Set the motor's limits.
  26872. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26873. */
  26874. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  26875. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  26876. };
  26877. return HingeJoint;
  26878. })(PhysicsJoint);
  26879. BABYLON.HingeJoint = HingeJoint;
  26880. /**
  26881. * This class represents a dual hinge physics joint (same as wheel joint)
  26882. */
  26883. var Hinge2Joint = (function (_super) {
  26884. __extends(Hinge2Joint, _super);
  26885. function Hinge2Joint(jointData) {
  26886. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  26887. }
  26888. /**
  26889. * Set the motor values.
  26890. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26891. * @param {number} force the force to apply
  26892. * @param {number} maxForce max force for this motor.
  26893. * @param {motorIndex} the motor's index, 0 or 1.
  26894. */
  26895. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  26896. if (motorIndex === void 0) { motorIndex = 0; }
  26897. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  26898. };
  26899. /**
  26900. * Set the motor limits.
  26901. * Attention, this function is plugin specific. Engines won't react 100% the same.
  26902. * @param {number} upperLimit the upper limit
  26903. * @param {number} lowerLimit lower limit
  26904. * @param {motorIndex} the motor's index, 0 or 1.
  26905. */
  26906. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  26907. if (motorIndex === void 0) { motorIndex = 0; }
  26908. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  26909. };
  26910. return Hinge2Joint;
  26911. })(PhysicsJoint);
  26912. BABYLON.Hinge2Joint = Hinge2Joint;
  26913. })(BABYLON || (BABYLON = {}));
  26914. var BABYLON;
  26915. (function (BABYLON) {
  26916. var PhysicsImpostor = (function () {
  26917. function PhysicsImpostor(object, type, _options, _scene) {
  26918. var _this = this;
  26919. if (_options === void 0) { _options = { mass: 0 }; }
  26920. this.object = object;
  26921. this.type = type;
  26922. this._options = _options;
  26923. this._scene = _scene;
  26924. this._bodyUpdateRequired = false;
  26925. this._onBeforePhysicsStepCallbacks = new Array();
  26926. this._onAfterPhysicsStepCallbacks = new Array();
  26927. this._onPhysicsCollideCallbacks = [];
  26928. this._deltaPosition = BABYLON.Vector3.Zero();
  26929. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  26930. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  26931. /**
  26932. * this function is executed by the physics engine.
  26933. */
  26934. this.beforeStep = function () {
  26935. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  26936. //conjugate deltaRotation
  26937. if (_this._deltaRotationConjugated) {
  26938. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  26939. }
  26940. else {
  26941. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  26942. }
  26943. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  26944. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  26945. func(_this);
  26946. });
  26947. };
  26948. /**
  26949. * this function is executed by the physics engine.
  26950. */
  26951. this.afterStep = function () {
  26952. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  26953. func(_this);
  26954. });
  26955. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  26956. _this.object.position.addInPlace(_this._deltaPosition);
  26957. if (_this._deltaRotation) {
  26958. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  26959. }
  26960. };
  26961. //event and body object due to cannon's event-based architecture.
  26962. this.onCollide = function (e) {
  26963. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  26964. if (otherImpostor) {
  26965. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  26966. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  26967. }).forEach(function (obj) {
  26968. obj.callback(_this, otherImpostor);
  26969. });
  26970. }
  26971. };
  26972. //sanity check!
  26973. if (!this.object) {
  26974. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  26975. return;
  26976. }
  26977. //legacy support for old syntax.
  26978. if (!this._scene && object.getScene) {
  26979. this._scene = object.getScene();
  26980. }
  26981. this._physicsEngine = this._scene.getPhysicsEngine();
  26982. if (!this._physicsEngine) {
  26983. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  26984. }
  26985. else {
  26986. //set the object's quaternion, if not set
  26987. if (!this.object.rotationQuaternion) {
  26988. if (this.object.rotation) {
  26989. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  26990. }
  26991. else {
  26992. this.object.rotationQuaternion = new BABYLON.Quaternion();
  26993. }
  26994. }
  26995. //default options params
  26996. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  26997. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  26998. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  26999. this._joints = [];
  27000. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  27001. if (!this.object.parent) {
  27002. this._init();
  27003. }
  27004. }
  27005. }
  27006. /**
  27007. * This function will completly initialize this impostor.
  27008. * It will create a new body - but only if this mesh has no parent.
  27009. * If it has, this impostor will not be used other than to define the impostor
  27010. * of the child mesh.
  27011. */
  27012. PhysicsImpostor.prototype._init = function () {
  27013. this._physicsEngine.removeImpostor(this);
  27014. this.physicsBody = null;
  27015. this._parent = this._parent || this._getPhysicsParent();
  27016. if (!this.parent) {
  27017. this._physicsEngine.addImpostor(this);
  27018. }
  27019. };
  27020. PhysicsImpostor.prototype._getPhysicsParent = function () {
  27021. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  27022. var parentMesh = this.object.parent;
  27023. return parentMesh.physicsImpostor;
  27024. }
  27025. return;
  27026. };
  27027. /**
  27028. * Should a new body be generated.
  27029. */
  27030. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  27031. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  27032. };
  27033. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  27034. this.forceUpdate();
  27035. };
  27036. /**
  27037. * Force a regeneration of this or the parent's impostor's body.
  27038. * Use under cautious - This will remove all joints already implemented.
  27039. */
  27040. PhysicsImpostor.prototype.forceUpdate = function () {
  27041. this._init();
  27042. if (this.parent) {
  27043. this.parent.forceUpdate();
  27044. }
  27045. };
  27046. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  27047. /*public get mesh(): AbstractMesh {
  27048. return this._mesh;
  27049. }*/
  27050. /**
  27051. * Gets the body that holds this impostor. Either its own, or its parent.
  27052. */
  27053. get: function () {
  27054. return this._parent ? this._parent.physicsBody : this._physicsBody;
  27055. },
  27056. /**
  27057. * Set the physics body. Used mainly by the physics engine/plugin
  27058. */
  27059. set: function (physicsBody) {
  27060. if (this._physicsBody) {
  27061. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  27062. }
  27063. this._physicsBody = physicsBody;
  27064. this.resetUpdateFlags();
  27065. },
  27066. enumerable: true,
  27067. configurable: true
  27068. });
  27069. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  27070. get: function () {
  27071. return this._parent;
  27072. },
  27073. enumerable: true,
  27074. configurable: true
  27075. });
  27076. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  27077. this._bodyUpdateRequired = false;
  27078. };
  27079. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  27080. if (this.object.getBoundingInfo) {
  27081. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  27082. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  27083. }
  27084. else {
  27085. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  27086. }
  27087. };
  27088. PhysicsImpostor.prototype.getObjectCenter = function () {
  27089. if (this.object.getBoundingInfo) {
  27090. return this.object.getBoundingInfo().boundingBox.center;
  27091. }
  27092. else {
  27093. return this.object.position;
  27094. }
  27095. };
  27096. /**
  27097. * Get a specific parametes from the options parameter.
  27098. */
  27099. PhysicsImpostor.prototype.getParam = function (paramName) {
  27100. return this._options[paramName];
  27101. };
  27102. /**
  27103. * Sets a specific parameter in the options given to the physics plugin
  27104. */
  27105. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  27106. this._options[paramName] = value;
  27107. this._bodyUpdateRequired = true;
  27108. };
  27109. /**
  27110. * Specifically change the body's mass option. Won't recreate the physics body object
  27111. */
  27112. PhysicsImpostor.prototype.setMass = function (mass) {
  27113. if (this.getParam("mass") !== mass) {
  27114. this.setParam("mass", mass);
  27115. }
  27116. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  27117. };
  27118. PhysicsImpostor.prototype.getLinearVelocity = function () {
  27119. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  27120. };
  27121. /**
  27122. * Set the body's linear velocity.
  27123. */
  27124. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  27125. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  27126. };
  27127. PhysicsImpostor.prototype.getAngularVelocity = function () {
  27128. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  27129. };
  27130. /**
  27131. * Set the body's linear velocity.
  27132. */
  27133. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  27134. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  27135. };
  27136. /**
  27137. * Execute a function with the physics plugin native code.
  27138. * Provide a function the will have two variables - the world object and the physics body object.
  27139. */
  27140. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  27141. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  27142. };
  27143. /**
  27144. * Register a function that will be executed before the physics world is stepping forward.
  27145. */
  27146. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  27147. this._onBeforePhysicsStepCallbacks.push(func);
  27148. };
  27149. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  27150. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  27151. if (index > -1) {
  27152. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  27153. }
  27154. else {
  27155. BABYLON.Tools.Warn("Function to remove was not found");
  27156. }
  27157. };
  27158. /**
  27159. * Register a function that will be executed after the physics step
  27160. */
  27161. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  27162. this._onAfterPhysicsStepCallbacks.push(func);
  27163. };
  27164. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  27165. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  27166. if (index > -1) {
  27167. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  27168. }
  27169. else {
  27170. BABYLON.Tools.Warn("Function to remove was not found");
  27171. }
  27172. };
  27173. /**
  27174. * register a function that will be executed when this impostor collides against a different body.
  27175. */
  27176. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  27177. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  27178. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  27179. };
  27180. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  27181. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  27182. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  27183. if (index > -1) {
  27184. this._onPhysicsCollideCallbacks.splice(index, 1);
  27185. }
  27186. else {
  27187. BABYLON.Tools.Warn("Function to remove was not found");
  27188. }
  27189. };
  27190. /**
  27191. * Apply a force
  27192. */
  27193. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  27194. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  27195. };
  27196. /**
  27197. * Apply an impulse
  27198. */
  27199. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  27200. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  27201. };
  27202. /**
  27203. * A help function to create a joint.
  27204. */
  27205. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  27206. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  27207. this.addJoint(otherImpostor, joint);
  27208. };
  27209. /**
  27210. * Add a joint to this impostor with a different impostor.
  27211. */
  27212. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  27213. this._joints.push({
  27214. otherImpostor: otherImpostor,
  27215. joint: joint
  27216. });
  27217. this._physicsEngine.addJoint(this, otherImpostor, joint);
  27218. };
  27219. /**
  27220. * Will keep this body still, in a sleep mode.
  27221. */
  27222. PhysicsImpostor.prototype.sleep = function () {
  27223. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  27224. };
  27225. /**
  27226. * Wake the body up.
  27227. */
  27228. PhysicsImpostor.prototype.wakeUp = function () {
  27229. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  27230. };
  27231. PhysicsImpostor.prototype.clone = function (newObject) {
  27232. if (!newObject)
  27233. return null;
  27234. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  27235. };
  27236. PhysicsImpostor.prototype.dispose = function () {
  27237. this.physicsBody = null;
  27238. if (this.parent) {
  27239. this.parent.forceUpdate();
  27240. }
  27241. else {
  27242. }
  27243. };
  27244. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  27245. this._deltaPosition.copyFrom(position);
  27246. };
  27247. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  27248. if (!this._deltaRotation) {
  27249. this._deltaRotation = new BABYLON.Quaternion();
  27250. }
  27251. this._deltaRotation.copyFrom(rotation);
  27252. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  27253. };
  27254. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  27255. //Impostor types
  27256. PhysicsImpostor.NoImpostor = 0;
  27257. PhysicsImpostor.SphereImpostor = 1;
  27258. PhysicsImpostor.BoxImpostor = 2;
  27259. PhysicsImpostor.PlaneImpostor = 3;
  27260. PhysicsImpostor.MeshImpostor = 4;
  27261. PhysicsImpostor.CylinderImpostor = 7;
  27262. PhysicsImpostor.ParticleImpostor = 8;
  27263. PhysicsImpostor.HeightmapImpostor = 9;
  27264. return PhysicsImpostor;
  27265. })();
  27266. BABYLON.PhysicsImpostor = PhysicsImpostor;
  27267. })(BABYLON || (BABYLON = {}));
  27268. var BABYLON;
  27269. (function (BABYLON) {
  27270. var PhysicsEngine = (function () {
  27271. function PhysicsEngine(gravity, _physicsPlugin) {
  27272. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  27273. this._physicsPlugin = _physicsPlugin;
  27274. //new methods and parameters
  27275. this._impostors = [];
  27276. this._joints = [];
  27277. if (!this._physicsPlugin.isSupported()) {
  27278. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  27279. + "Please make sure it is included.");
  27280. }
  27281. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  27282. this.setGravity(gravity);
  27283. this.setTimeStep();
  27284. }
  27285. PhysicsEngine.prototype.setGravity = function (gravity) {
  27286. this.gravity = gravity;
  27287. this._physicsPlugin.setGravity(this.gravity);
  27288. };
  27289. /**
  27290. * Set the time step of the physics engine.
  27291. * default is 1/60.
  27292. * To slow it down, enter 1/600 for example.
  27293. * To speed it up, 1/30
  27294. * @param {number} newTimeStep the new timestep to apply to this world.
  27295. */
  27296. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  27297. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  27298. this._physicsPlugin.setTimeStep(newTimeStep);
  27299. };
  27300. PhysicsEngine.prototype.dispose = function () {
  27301. this._impostors.forEach(function (impostor) {
  27302. impostor.dispose();
  27303. });
  27304. this._physicsPlugin.dispose();
  27305. };
  27306. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  27307. return this._physicsPlugin.name;
  27308. };
  27309. /**
  27310. * Adding a new impostor for the impostor tracking.
  27311. * This will be done by the impostor itself.
  27312. * @param {PhysicsImpostor} impostor the impostor to add
  27313. */
  27314. PhysicsEngine.prototype.addImpostor = function (impostor) {
  27315. impostor.uniqueId = this._impostors.push(impostor);
  27316. //if no parent, generate the body
  27317. if (!impostor.parent) {
  27318. this._physicsPlugin.generatePhysicsBody(impostor);
  27319. }
  27320. };
  27321. /**
  27322. * Remove an impostor from the engine.
  27323. * This impostor and its mesh will not longer be updated by the physics engine.
  27324. * @param {PhysicsImpostor} impostor the impostor to remove
  27325. */
  27326. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  27327. var index = this._impostors.indexOf(impostor);
  27328. if (index > -1) {
  27329. var removed = this._impostors.splice(index, 1);
  27330. //Is it needed?
  27331. if (removed.length) {
  27332. //this will also remove it from the world.
  27333. removed[0].physicsBody = null;
  27334. }
  27335. }
  27336. };
  27337. /**
  27338. * Add a joint to the physics engine
  27339. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  27340. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  27341. * @param {PhysicsJoint} the joint that will connect both impostors.
  27342. */
  27343. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  27344. var impostorJoint = {
  27345. mainImpostor: mainImpostor,
  27346. connectedImpostor: connectedImpostor,
  27347. joint: joint
  27348. };
  27349. joint.physicsPlugin = this._physicsPlugin;
  27350. this._joints.push(impostorJoint);
  27351. this._physicsPlugin.generateJoint(impostorJoint);
  27352. };
  27353. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  27354. var matchingJoints = this._joints.filter(function (impostorJoint) {
  27355. return (impostorJoint.connectedImpostor === connectedImpostor
  27356. && impostorJoint.joint === joint
  27357. && impostorJoint.mainImpostor === mainImpostor);
  27358. });
  27359. if (matchingJoints.length) {
  27360. this._physicsPlugin.removeJoint(matchingJoints[0]);
  27361. }
  27362. };
  27363. /**
  27364. * Called by the scene. no need to call it.
  27365. */
  27366. PhysicsEngine.prototype._step = function (delta) {
  27367. var _this = this;
  27368. //check if any mesh has no body / requires an update
  27369. this._impostors.forEach(function (impostor) {
  27370. if (impostor.isBodyInitRequired()) {
  27371. _this._physicsPlugin.generatePhysicsBody(impostor);
  27372. }
  27373. });
  27374. if (delta > 0.1) {
  27375. delta = 0.1;
  27376. }
  27377. else if (delta <= 0) {
  27378. delta = 1.0 / 60.0;
  27379. }
  27380. this._physicsPlugin.executeStep(delta, this._impostors);
  27381. };
  27382. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  27383. return this._physicsPlugin;
  27384. };
  27385. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  27386. for (var i = 0; i < this._impostors.length; ++i) {
  27387. if (this._impostors[i].object === object) {
  27388. return this._impostors[i];
  27389. }
  27390. }
  27391. };
  27392. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  27393. for (var i = 0; i < this._impostors.length; ++i) {
  27394. if (this._impostors[i].physicsBody === body) {
  27395. return this._impostors[i];
  27396. }
  27397. }
  27398. };
  27399. // Statics, Legacy support.
  27400. /**
  27401. * @Deprecated
  27402. *
  27403. */
  27404. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  27405. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  27406. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  27407. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  27408. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  27409. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  27410. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  27411. PhysicsEngine.CapsuleImpostor = -1;
  27412. PhysicsEngine.ConeImpostor = -1;
  27413. PhysicsEngine.ConvexHullImpostor = -1;
  27414. PhysicsEngine.Epsilon = 0.001;
  27415. return PhysicsEngine;
  27416. })();
  27417. BABYLON.PhysicsEngine = PhysicsEngine;
  27418. })(BABYLON || (BABYLON = {}));
  27419. var BABYLON;
  27420. (function (BABYLON) {
  27421. var VertexData = (function () {
  27422. function VertexData() {
  27423. }
  27424. VertexData.prototype.set = function (data, kind) {
  27425. switch (kind) {
  27426. case BABYLON.VertexBuffer.PositionKind:
  27427. this.positions = data;
  27428. break;
  27429. case BABYLON.VertexBuffer.NormalKind:
  27430. this.normals = data;
  27431. break;
  27432. case BABYLON.VertexBuffer.UVKind:
  27433. this.uvs = data;
  27434. break;
  27435. case BABYLON.VertexBuffer.UV2Kind:
  27436. this.uvs2 = data;
  27437. break;
  27438. case BABYLON.VertexBuffer.UV3Kind:
  27439. this.uvs3 = data;
  27440. break;
  27441. case BABYLON.VertexBuffer.UV4Kind:
  27442. this.uvs4 = data;
  27443. break;
  27444. case BABYLON.VertexBuffer.UV5Kind:
  27445. this.uvs5 = data;
  27446. break;
  27447. case BABYLON.VertexBuffer.UV6Kind:
  27448. this.uvs6 = data;
  27449. break;
  27450. case BABYLON.VertexBuffer.ColorKind:
  27451. this.colors = data;
  27452. break;
  27453. case BABYLON.VertexBuffer.MatricesIndicesKind:
  27454. this.matricesIndices = data;
  27455. break;
  27456. case BABYLON.VertexBuffer.MatricesWeightsKind:
  27457. this.matricesWeights = data;
  27458. break;
  27459. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  27460. this.matricesIndicesExtra = data;
  27461. break;
  27462. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  27463. this.matricesWeightsExtra = data;
  27464. break;
  27465. }
  27466. };
  27467. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  27468. this._applyTo(mesh, updatable);
  27469. };
  27470. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  27471. this._applyTo(geometry, updatable);
  27472. };
  27473. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  27474. this._update(mesh);
  27475. };
  27476. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  27477. this._update(geometry);
  27478. };
  27479. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  27480. if (this.positions) {
  27481. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  27482. }
  27483. if (this.normals) {
  27484. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  27485. }
  27486. if (this.uvs) {
  27487. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  27488. }
  27489. if (this.uvs2) {
  27490. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  27491. }
  27492. if (this.uvs3) {
  27493. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  27494. }
  27495. if (this.uvs4) {
  27496. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  27497. }
  27498. if (this.uvs5) {
  27499. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  27500. }
  27501. if (this.uvs6) {
  27502. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  27503. }
  27504. if (this.colors) {
  27505. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  27506. }
  27507. if (this.matricesIndices) {
  27508. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  27509. }
  27510. if (this.matricesWeights) {
  27511. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  27512. }
  27513. if (this.matricesIndicesExtra) {
  27514. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  27515. }
  27516. if (this.matricesWeightsExtra) {
  27517. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  27518. }
  27519. if (this.indices) {
  27520. meshOrGeometry.setIndices(this.indices);
  27521. }
  27522. };
  27523. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  27524. if (this.positions) {
  27525. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  27526. }
  27527. if (this.normals) {
  27528. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  27529. }
  27530. if (this.uvs) {
  27531. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  27532. }
  27533. if (this.uvs2) {
  27534. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  27535. }
  27536. if (this.uvs3) {
  27537. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  27538. }
  27539. if (this.uvs4) {
  27540. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  27541. }
  27542. if (this.uvs5) {
  27543. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  27544. }
  27545. if (this.uvs6) {
  27546. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  27547. }
  27548. if (this.colors) {
  27549. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  27550. }
  27551. if (this.matricesIndices) {
  27552. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  27553. }
  27554. if (this.matricesWeights) {
  27555. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  27556. }
  27557. if (this.matricesIndicesExtra) {
  27558. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  27559. }
  27560. if (this.matricesWeightsExtra) {
  27561. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  27562. }
  27563. if (this.indices) {
  27564. meshOrGeometry.setIndices(this.indices);
  27565. }
  27566. };
  27567. VertexData.prototype.transform = function (matrix) {
  27568. var transformed = BABYLON.Vector3.Zero();
  27569. var index;
  27570. if (this.positions) {
  27571. var position = BABYLON.Vector3.Zero();
  27572. for (index = 0; index < this.positions.length; index += 3) {
  27573. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  27574. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  27575. this.positions[index] = transformed.x;
  27576. this.positions[index + 1] = transformed.y;
  27577. this.positions[index + 2] = transformed.z;
  27578. }
  27579. }
  27580. if (this.normals) {
  27581. var normal = BABYLON.Vector3.Zero();
  27582. for (index = 0; index < this.normals.length; index += 3) {
  27583. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  27584. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  27585. this.normals[index] = transformed.x;
  27586. this.normals[index + 1] = transformed.y;
  27587. this.normals[index + 2] = transformed.z;
  27588. }
  27589. }
  27590. };
  27591. VertexData.prototype.merge = function (other) {
  27592. if (other.indices) {
  27593. if (!this.indices) {
  27594. this.indices = [];
  27595. }
  27596. var offset = this.positions ? this.positions.length / 3 : 0;
  27597. for (var index = 0; index < other.indices.length; index++) {
  27598. //TODO check type - if Int32Array!
  27599. this.indices.push(other.indices[index] + offset);
  27600. }
  27601. }
  27602. this.positions = this._mergeElement(this.positions, other.positions);
  27603. this.normals = this._mergeElement(this.normals, other.normals);
  27604. this.uvs = this._mergeElement(this.uvs, other.uvs);
  27605. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  27606. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  27607. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  27608. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  27609. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  27610. this.colors = this._mergeElement(this.colors, other.colors);
  27611. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  27612. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  27613. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  27614. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  27615. };
  27616. VertexData.prototype._mergeElement = function (source, other) {
  27617. if (!other)
  27618. return source;
  27619. if (!source)
  27620. return other;
  27621. var len = other.length + source.length;
  27622. var isSrcTypedArray = source instanceof Float32Array;
  27623. var isOthTypedArray = other instanceof Float32Array;
  27624. // use non-loop method when the source is Float32Array
  27625. if (isSrcTypedArray) {
  27626. var ret32 = new Float32Array(len);
  27627. ret32.set(source);
  27628. ret32.set(other, source.length);
  27629. return ret32;
  27630. }
  27631. else if (!isOthTypedArray) {
  27632. return source.concat(other);
  27633. }
  27634. else {
  27635. var ret = source.slice(0); // copy source to a separate array
  27636. for (var i = 0, len = other.length; i < len; i++) {
  27637. ret.push(other[i]);
  27638. }
  27639. return ret;
  27640. }
  27641. };
  27642. VertexData.prototype.serialize = function () {
  27643. var serializationObject = this.serialize();
  27644. if (this.positions) {
  27645. serializationObject.positions = this.positions;
  27646. }
  27647. if (this.normals) {
  27648. serializationObject.normals = this.normals;
  27649. }
  27650. if (this.uvs) {
  27651. serializationObject.uvs = this.uvs;
  27652. }
  27653. if (this.uvs2) {
  27654. serializationObject.uvs2 = this.uvs2;
  27655. }
  27656. if (this.uvs3) {
  27657. serializationObject.uvs3 = this.uvs3;
  27658. }
  27659. if (this.uvs4) {
  27660. serializationObject.uvs4 = this.uvs4;
  27661. }
  27662. if (this.uvs5) {
  27663. serializationObject.uvs5 = this.uvs5;
  27664. }
  27665. if (this.uvs6) {
  27666. serializationObject.uvs6 = this.uvs6;
  27667. }
  27668. if (this.colors) {
  27669. serializationObject.colors = this.colors;
  27670. }
  27671. if (this.matricesIndices) {
  27672. serializationObject.matricesIndices = this.matricesIndices;
  27673. serializationObject.matricesIndices._isExpanded = true;
  27674. }
  27675. if (this.matricesWeights) {
  27676. serializationObject.matricesWeights = this.matricesWeights;
  27677. }
  27678. if (this.matricesIndicesExtra) {
  27679. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  27680. serializationObject.matricesIndicesExtra._isExpanded = true;
  27681. }
  27682. if (this.matricesWeightsExtra) {
  27683. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  27684. }
  27685. serializationObject.indices = this.indices;
  27686. return serializationObject;
  27687. };
  27688. // Statics
  27689. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  27690. return VertexData._ExtractFrom(mesh, copyWhenShared);
  27691. };
  27692. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  27693. return VertexData._ExtractFrom(geometry, copyWhenShared);
  27694. };
  27695. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  27696. var result = new VertexData();
  27697. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27698. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  27699. }
  27700. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27701. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  27702. }
  27703. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27704. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  27705. }
  27706. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27707. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  27708. }
  27709. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  27710. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  27711. }
  27712. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  27713. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  27714. }
  27715. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  27716. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  27717. }
  27718. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  27719. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  27720. }
  27721. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27722. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  27723. }
  27724. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27725. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  27726. }
  27727. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27728. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  27729. }
  27730. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  27731. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  27732. }
  27733. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  27734. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  27735. }
  27736. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  27737. return result;
  27738. };
  27739. VertexData.CreateRibbon = function (options) {
  27740. var pathArray = options.pathArray;
  27741. var closeArray = options.closeArray || false;
  27742. var closePath = options.closePath || false;
  27743. var defaultOffset = Math.floor(pathArray[0].length / 2);
  27744. var offset = options.offset || defaultOffset;
  27745. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  27746. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27747. var positions = [];
  27748. var indices = [];
  27749. var normals = [];
  27750. var uvs = [];
  27751. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  27752. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  27753. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  27754. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  27755. var minlg; // minimal length among all paths from pathArray
  27756. var lg = []; // array of path lengths : nb of vertex per path
  27757. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  27758. var p; // path iterator
  27759. var i; // point iterator
  27760. var j; // point iterator
  27761. // if single path in pathArray
  27762. if (pathArray.length < 2) {
  27763. var ar1 = [];
  27764. var ar2 = [];
  27765. for (i = 0; i < pathArray[0].length - offset; i++) {
  27766. ar1.push(pathArray[0][i]);
  27767. ar2.push(pathArray[0][i + offset]);
  27768. }
  27769. pathArray = [ar1, ar2];
  27770. }
  27771. // positions and horizontal distances (u)
  27772. var idc = 0;
  27773. var closePathCorr = (closePath) ? 1 : 0;
  27774. var path;
  27775. var l;
  27776. minlg = pathArray[0].length;
  27777. var vectlg;
  27778. var dist;
  27779. for (p = 0; p < pathArray.length; p++) {
  27780. uTotalDistance[p] = 0;
  27781. us[p] = [0];
  27782. path = pathArray[p];
  27783. l = path.length;
  27784. minlg = (minlg < l) ? minlg : l;
  27785. j = 0;
  27786. while (j < l) {
  27787. positions.push(path[j].x, path[j].y, path[j].z);
  27788. if (j > 0) {
  27789. vectlg = path[j].subtract(path[j - 1]).length();
  27790. dist = vectlg + uTotalDistance[p];
  27791. us[p].push(dist);
  27792. uTotalDistance[p] = dist;
  27793. }
  27794. j++;
  27795. }
  27796. if (closePath) {
  27797. j--;
  27798. positions.push(path[0].x, path[0].y, path[0].z);
  27799. vectlg = path[j].subtract(path[0]).length();
  27800. dist = vectlg + uTotalDistance[p];
  27801. us[p].push(dist);
  27802. uTotalDistance[p] = dist;
  27803. }
  27804. lg[p] = l + closePathCorr;
  27805. idx[p] = idc;
  27806. idc += (l + closePathCorr);
  27807. }
  27808. // vertical distances (v)
  27809. var path1;
  27810. var path2;
  27811. var vertex1;
  27812. var vertex2;
  27813. for (i = 0; i < minlg + closePathCorr; i++) {
  27814. vTotalDistance[i] = 0;
  27815. vs[i] = [0];
  27816. for (p = 0; p < pathArray.length - 1; p++) {
  27817. path1 = pathArray[p];
  27818. path2 = pathArray[p + 1];
  27819. if (i === minlg) {
  27820. vertex1 = path1[0];
  27821. vertex2 = path2[0];
  27822. }
  27823. else {
  27824. vertex1 = path1[i];
  27825. vertex2 = path2[i];
  27826. }
  27827. vectlg = vertex2.subtract(vertex1).length();
  27828. dist = vectlg + vTotalDistance[i];
  27829. vs[i].push(dist);
  27830. vTotalDistance[i] = dist;
  27831. }
  27832. if (closeArray) {
  27833. path1 = pathArray[p];
  27834. path2 = pathArray[0];
  27835. if (i === minlg) {
  27836. vertex2 = path2[0];
  27837. }
  27838. vectlg = vertex2.subtract(vertex1).length();
  27839. dist = vectlg + vTotalDistance[i];
  27840. vTotalDistance[i] = dist;
  27841. }
  27842. }
  27843. // uvs
  27844. var u;
  27845. var v;
  27846. for (p = 0; p < pathArray.length; p++) {
  27847. for (i = 0; i < minlg + closePathCorr; i++) {
  27848. u = us[p][i] / uTotalDistance[p];
  27849. v = vs[i][p] / vTotalDistance[i];
  27850. uvs.push(u, v);
  27851. }
  27852. }
  27853. // indices
  27854. p = 0; // path index
  27855. var pi = 0; // positions array index
  27856. var l1 = lg[p] - 1; // path1 length
  27857. var l2 = lg[p + 1] - 1; // path2 length
  27858. var min = (l1 < l2) ? l1 : l2; // current path stop index
  27859. var shft = idx[1] - idx[0]; // shift
  27860. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  27861. while (pi <= min && p < path1nb) {
  27862. // 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
  27863. indices.push(pi, pi + shft, pi + 1);
  27864. indices.push(pi + shft + 1, pi + 1, pi + shft);
  27865. pi += 1;
  27866. if (pi === min) {
  27867. p++;
  27868. if (p === lg.length - 1) {
  27869. shft = idx[0] - idx[p];
  27870. l1 = lg[p] - 1;
  27871. l2 = lg[0] - 1;
  27872. }
  27873. else {
  27874. shft = idx[p + 1] - idx[p];
  27875. l1 = lg[p] - 1;
  27876. l2 = lg[p + 1] - 1;
  27877. }
  27878. pi = idx[p];
  27879. min = (l1 < l2) ? l1 + pi : l2 + pi;
  27880. }
  27881. }
  27882. // normals
  27883. VertexData.ComputeNormals(positions, indices, normals);
  27884. if (closePath) {
  27885. var indexFirst = 0;
  27886. var indexLast = 0;
  27887. for (p = 0; p < pathArray.length; p++) {
  27888. indexFirst = idx[p] * 3;
  27889. if (p + 1 < pathArray.length) {
  27890. indexLast = (idx[p + 1] - 1) * 3;
  27891. }
  27892. else {
  27893. indexLast = normals.length - 3;
  27894. }
  27895. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  27896. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  27897. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  27898. normals[indexLast] = normals[indexFirst];
  27899. normals[indexLast + 1] = normals[indexFirst + 1];
  27900. normals[indexLast + 2] = normals[indexFirst + 2];
  27901. }
  27902. }
  27903. // sides
  27904. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27905. // Result
  27906. var vertexData = new VertexData();
  27907. vertexData.indices = indices;
  27908. vertexData.positions = positions;
  27909. vertexData.normals = normals;
  27910. vertexData.uvs = uvs;
  27911. if (closePath) {
  27912. vertexData._idx = idx;
  27913. }
  27914. return vertexData;
  27915. };
  27916. VertexData.CreateBox = function (options) {
  27917. var normalsSource = [
  27918. new BABYLON.Vector3(0, 0, 1),
  27919. new BABYLON.Vector3(0, 0, -1),
  27920. new BABYLON.Vector3(1, 0, 0),
  27921. new BABYLON.Vector3(-1, 0, 0),
  27922. new BABYLON.Vector3(0, 1, 0),
  27923. new BABYLON.Vector3(0, -1, 0)
  27924. ];
  27925. var indices = [];
  27926. var positions = [];
  27927. var normals = [];
  27928. var uvs = [];
  27929. var width = options.width || options.size || 1;
  27930. var height = options.height || options.size || 1;
  27931. var depth = options.depth || options.size || 1;
  27932. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27933. var faceUV = options.faceUV || new Array(6);
  27934. var faceColors = options.faceColors;
  27935. var colors = [];
  27936. // default face colors and UV if undefined
  27937. for (var f = 0; f < 6; f++) {
  27938. if (faceUV[f] === undefined) {
  27939. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27940. }
  27941. if (faceColors && faceColors[f] === undefined) {
  27942. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27943. }
  27944. }
  27945. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  27946. // Create each face in turn.
  27947. for (var index = 0; index < normalsSource.length; index++) {
  27948. var normal = normalsSource[index];
  27949. // Get two vectors perpendicular to the face normal and to each other.
  27950. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  27951. var side2 = BABYLON.Vector3.Cross(normal, side1);
  27952. // Six indices (two triangles) per face.
  27953. var verticesLength = positions.length / 3;
  27954. indices.push(verticesLength);
  27955. indices.push(verticesLength + 1);
  27956. indices.push(verticesLength + 2);
  27957. indices.push(verticesLength);
  27958. indices.push(verticesLength + 2);
  27959. indices.push(verticesLength + 3);
  27960. // Four vertices per face.
  27961. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  27962. positions.push(vertex.x, vertex.y, vertex.z);
  27963. normals.push(normal.x, normal.y, normal.z);
  27964. uvs.push(faceUV[index].z, faceUV[index].w);
  27965. if (faceColors) {
  27966. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27967. }
  27968. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  27969. positions.push(vertex.x, vertex.y, vertex.z);
  27970. normals.push(normal.x, normal.y, normal.z);
  27971. uvs.push(faceUV[index].x, faceUV[index].w);
  27972. if (faceColors) {
  27973. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27974. }
  27975. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  27976. positions.push(vertex.x, vertex.y, vertex.z);
  27977. normals.push(normal.x, normal.y, normal.z);
  27978. uvs.push(faceUV[index].x, faceUV[index].y);
  27979. if (faceColors) {
  27980. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27981. }
  27982. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  27983. positions.push(vertex.x, vertex.y, vertex.z);
  27984. normals.push(normal.x, normal.y, normal.z);
  27985. uvs.push(faceUV[index].z, faceUV[index].y);
  27986. if (faceColors) {
  27987. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  27988. }
  27989. }
  27990. // sides
  27991. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  27992. // Result
  27993. var vertexData = new VertexData();
  27994. vertexData.indices = indices;
  27995. vertexData.positions = positions;
  27996. vertexData.normals = normals;
  27997. vertexData.uvs = uvs;
  27998. if (faceColors) {
  27999. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28000. vertexData.colors = totalColors;
  28001. }
  28002. return vertexData;
  28003. };
  28004. VertexData.CreateSphere = function (options) {
  28005. var segments = options.segments || 32;
  28006. var diameterX = options.diameterX || options.diameter || 1;
  28007. var diameterY = options.diameterY || options.diameter || 1;
  28008. var diameterZ = options.diameterZ || options.diameter || 1;
  28009. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28010. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  28011. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28012. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  28013. var totalZRotationSteps = 2 + segments;
  28014. var totalYRotationSteps = 2 * totalZRotationSteps;
  28015. var indices = [];
  28016. var positions = [];
  28017. var normals = [];
  28018. var uvs = [];
  28019. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  28020. var normalizedZ = zRotationStep / totalZRotationSteps;
  28021. var angleZ = normalizedZ * Math.PI * slice;
  28022. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  28023. var normalizedY = yRotationStep / totalYRotationSteps;
  28024. var angleY = normalizedY * Math.PI * 2 * arc;
  28025. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  28026. var rotationY = BABYLON.Matrix.RotationY(angleY);
  28027. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  28028. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  28029. var vertex = complete.multiply(radius);
  28030. var normal = complete.divide(radius).normalize();
  28031. positions.push(vertex.x, vertex.y, vertex.z);
  28032. normals.push(normal.x, normal.y, normal.z);
  28033. uvs.push(normalizedY, normalizedZ);
  28034. }
  28035. if (zRotationStep > 0) {
  28036. var verticesCount = positions.length / 3;
  28037. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  28038. indices.push((firstIndex));
  28039. indices.push((firstIndex + 1));
  28040. indices.push(firstIndex + totalYRotationSteps + 1);
  28041. indices.push((firstIndex + totalYRotationSteps + 1));
  28042. indices.push((firstIndex + 1));
  28043. indices.push((firstIndex + totalYRotationSteps + 2));
  28044. }
  28045. }
  28046. }
  28047. // Sides
  28048. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28049. // Result
  28050. var vertexData = new VertexData();
  28051. vertexData.indices = indices;
  28052. vertexData.positions = positions;
  28053. vertexData.normals = normals;
  28054. vertexData.uvs = uvs;
  28055. return vertexData;
  28056. };
  28057. // Cylinder and cone
  28058. VertexData.CreateCylinder = function (options) {
  28059. var height = options.height || 2;
  28060. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  28061. var diameterBottom = options.diameterBottom || options.diameter || 1;
  28062. var tessellation = options.tessellation || 24;
  28063. var subdivisions = options.subdivisions || 1;
  28064. var hasRings = options.hasRings;
  28065. var enclose = options.enclose;
  28066. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28067. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28068. var faceUV = options.faceUV || new Array(3);
  28069. var faceColors = options.faceColors;
  28070. // default face colors and UV if undefined
  28071. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  28072. var ringNb = (hasRings) ? subdivisions : 1;
  28073. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  28074. var f;
  28075. for (f = 0; f < surfaceNb; f++) {
  28076. if (faceColors && faceColors[f] === undefined) {
  28077. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28078. }
  28079. }
  28080. for (f = 0; f < surfaceNb; f++) {
  28081. if (faceUV && faceUV[f] === undefined) {
  28082. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28083. }
  28084. }
  28085. var indices = [];
  28086. var positions = [];
  28087. var normals = [];
  28088. var uvs = [];
  28089. var colors = [];
  28090. var angle_step = Math.PI * 2 * arc / tessellation;
  28091. var angle;
  28092. var h;
  28093. var radius;
  28094. var tan = (diameterBottom - diameterTop) / 2 / height;
  28095. var ringVertex = BABYLON.Vector3.Zero();
  28096. var ringNormal = BABYLON.Vector3.Zero();
  28097. var ringFirstVertex = BABYLON.Vector3.Zero();
  28098. var ringFirstNormal = BABYLON.Vector3.Zero();
  28099. var quadNormal = BABYLON.Vector3.Zero();
  28100. var Y = BABYLON.Axis.Y;
  28101. // positions, normals, uvs
  28102. var i;
  28103. var j;
  28104. var r;
  28105. var ringIdx = 1;
  28106. var s = 1; // surface index
  28107. var cs = 0;
  28108. var v = 0;
  28109. for (i = 0; i <= subdivisions; i++) {
  28110. h = i / subdivisions;
  28111. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  28112. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  28113. for (r = 0; r < ringIdx; r++) {
  28114. if (hasRings) {
  28115. s += r;
  28116. }
  28117. if (enclose) {
  28118. s += 2 * r;
  28119. }
  28120. for (j = 0; j <= tessellation; j++) {
  28121. angle = j * angle_step;
  28122. // position
  28123. ringVertex.x = Math.cos(-angle) * radius;
  28124. ringVertex.y = -height / 2 + h * height;
  28125. ringVertex.z = Math.sin(-angle) * radius;
  28126. // normal
  28127. if (diameterTop === 0 && i === subdivisions) {
  28128. // if no top cap, reuse former normals
  28129. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  28130. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  28131. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  28132. }
  28133. else {
  28134. ringNormal.x = ringVertex.x;
  28135. ringNormal.z = ringVertex.z;
  28136. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  28137. ringNormal.normalize();
  28138. }
  28139. // keep first ring vertex values for enclose
  28140. if (j === 0) {
  28141. ringFirstVertex.copyFrom(ringVertex);
  28142. ringFirstNormal.copyFrom(ringNormal);
  28143. }
  28144. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28145. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  28146. if (hasRings) {
  28147. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  28148. }
  28149. else {
  28150. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  28151. }
  28152. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  28153. if (faceColors) {
  28154. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  28155. }
  28156. }
  28157. // if enclose, add four vertices and their dedicated normals
  28158. if (arc !== 1 && enclose) {
  28159. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28160. positions.push(0, ringVertex.y, 0);
  28161. positions.push(0, ringVertex.y, 0);
  28162. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  28163. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  28164. quadNormal.normalize();
  28165. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28166. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  28167. quadNormal.normalize();
  28168. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28169. if (hasRings) {
  28170. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  28171. }
  28172. else {
  28173. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  28174. }
  28175. uvs.push(faceUV[s + 1].x, v);
  28176. uvs.push(faceUV[s + 1].z, v);
  28177. if (hasRings) {
  28178. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  28179. }
  28180. else {
  28181. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  28182. }
  28183. uvs.push(faceUV[s + 2].x, v);
  28184. uvs.push(faceUV[s + 2].z, v);
  28185. if (faceColors) {
  28186. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28187. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  28188. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28189. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  28190. }
  28191. }
  28192. if (cs !== s) {
  28193. cs = s;
  28194. }
  28195. }
  28196. }
  28197. // indices
  28198. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  28199. var s;
  28200. i = 0;
  28201. for (s = 0; s < subdivisions; s++) {
  28202. for (j = 0; j < tessellation; j++) {
  28203. var i0 = i * (e + 1) + j;
  28204. var i1 = (i + 1) * (e + 1) + j;
  28205. var i2 = i * (e + 1) + (j + 1);
  28206. var i3 = (i + 1) * (e + 1) + (j + 1);
  28207. indices.push(i0, i1, i2);
  28208. indices.push(i3, i2, i1);
  28209. }
  28210. if (arc !== 1 && enclose) {
  28211. indices.push(i0 + 2, i1 + 2, i2 + 2);
  28212. indices.push(i3 + 2, i2 + 2, i1 + 2);
  28213. indices.push(i0 + 4, i1 + 4, i2 + 4);
  28214. indices.push(i3 + 4, i2 + 4, i1 + 4);
  28215. }
  28216. i = (hasRings) ? (i + 2) : (i + 1);
  28217. }
  28218. // Caps
  28219. var createCylinderCap = function (isTop) {
  28220. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  28221. if (radius === 0) {
  28222. return;
  28223. }
  28224. // Cap positions, normals & uvs
  28225. var angle;
  28226. var circleVector;
  28227. var i;
  28228. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  28229. var c;
  28230. if (faceColors) {
  28231. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  28232. }
  28233. // cap center
  28234. var vbase = positions.length / 3;
  28235. var offset = isTop ? height / 2 : -height / 2;
  28236. var center = new BABYLON.Vector3(0, offset, 0);
  28237. positions.push(center.x, center.y, center.z);
  28238. normals.push(0, isTop ? 1 : -1, 0);
  28239. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  28240. if (faceColors) {
  28241. colors.push(c.r, c.g, c.b, c.a);
  28242. }
  28243. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  28244. for (i = 0; i <= tessellation; i++) {
  28245. angle = Math.PI * 2 * i * arc / tessellation;
  28246. var cos = Math.cos(-angle);
  28247. var sin = Math.sin(-angle);
  28248. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  28249. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  28250. positions.push(circleVector.x, circleVector.y, circleVector.z);
  28251. normals.push(0, isTop ? 1 : -1, 0);
  28252. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  28253. if (faceColors) {
  28254. colors.push(c.r, c.g, c.b, c.a);
  28255. }
  28256. }
  28257. // Cap indices
  28258. for (i = 0; i < tessellation; i++) {
  28259. if (!isTop) {
  28260. indices.push(vbase);
  28261. indices.push(vbase + (i + 1));
  28262. indices.push(vbase + (i + 2));
  28263. }
  28264. else {
  28265. indices.push(vbase);
  28266. indices.push(vbase + (i + 2));
  28267. indices.push(vbase + (i + 1));
  28268. }
  28269. }
  28270. };
  28271. // add caps to geometry
  28272. createCylinderCap(false);
  28273. createCylinderCap(true);
  28274. // Sides
  28275. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28276. var vertexData = new VertexData();
  28277. vertexData.indices = indices;
  28278. vertexData.positions = positions;
  28279. vertexData.normals = normals;
  28280. vertexData.uvs = uvs;
  28281. if (faceColors) {
  28282. vertexData.colors = colors;
  28283. }
  28284. return vertexData;
  28285. };
  28286. VertexData.CreateTorus = function (options) {
  28287. var indices = [];
  28288. var positions = [];
  28289. var normals = [];
  28290. var uvs = [];
  28291. var diameter = options.diameter || 1;
  28292. var thickness = options.thickness || 0.5;
  28293. var tessellation = options.tessellation || 16;
  28294. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28295. var stride = tessellation + 1;
  28296. for (var i = 0; i <= tessellation; i++) {
  28297. var u = i / tessellation;
  28298. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  28299. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  28300. for (var j = 0; j <= tessellation; j++) {
  28301. var v = 1 - j / tessellation;
  28302. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  28303. var dx = Math.cos(innerAngle);
  28304. var dy = Math.sin(innerAngle);
  28305. // Create a vertex.
  28306. var normal = new BABYLON.Vector3(dx, dy, 0);
  28307. var position = normal.scale(thickness / 2);
  28308. var textureCoordinate = new BABYLON.Vector2(u, v);
  28309. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  28310. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  28311. positions.push(position.x, position.y, position.z);
  28312. normals.push(normal.x, normal.y, normal.z);
  28313. uvs.push(textureCoordinate.x, textureCoordinate.y);
  28314. // And create indices for two triangles.
  28315. var nextI = (i + 1) % stride;
  28316. var nextJ = (j + 1) % stride;
  28317. indices.push(i * stride + j);
  28318. indices.push(i * stride + nextJ);
  28319. indices.push(nextI * stride + j);
  28320. indices.push(i * stride + nextJ);
  28321. indices.push(nextI * stride + nextJ);
  28322. indices.push(nextI * stride + j);
  28323. }
  28324. }
  28325. // Sides
  28326. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28327. // Result
  28328. var vertexData = new VertexData();
  28329. vertexData.indices = indices;
  28330. vertexData.positions = positions;
  28331. vertexData.normals = normals;
  28332. vertexData.uvs = uvs;
  28333. return vertexData;
  28334. };
  28335. VertexData.CreateLineSystem = function (options) {
  28336. var indices = [];
  28337. var positions = [];
  28338. var lines = options.lines;
  28339. var idx = 0;
  28340. for (var l = 0; l < lines.length; l++) {
  28341. var points = lines[l];
  28342. for (var index = 0; index < points.length; index++) {
  28343. positions.push(points[index].x, points[index].y, points[index].z);
  28344. if (index > 0) {
  28345. indices.push(idx - 1);
  28346. indices.push(idx);
  28347. }
  28348. idx++;
  28349. }
  28350. }
  28351. var vertexData = new VertexData();
  28352. vertexData.indices = indices;
  28353. vertexData.positions = positions;
  28354. return vertexData;
  28355. };
  28356. VertexData.CreateDashedLines = function (options) {
  28357. var dashSize = options.dashSize || 3;
  28358. var gapSize = options.gapSize || 1;
  28359. var dashNb = options.dashNb || 200;
  28360. var points = options.points;
  28361. var positions = new Array();
  28362. var indices = new Array();
  28363. var curvect = BABYLON.Vector3.Zero();
  28364. var lg = 0;
  28365. var nb = 0;
  28366. var shft = 0;
  28367. var dashshft = 0;
  28368. var curshft = 0;
  28369. var idx = 0;
  28370. var i = 0;
  28371. for (i = 0; i < points.length - 1; i++) {
  28372. points[i + 1].subtractToRef(points[i], curvect);
  28373. lg += curvect.length();
  28374. }
  28375. shft = lg / dashNb;
  28376. dashshft = dashSize * shft / (dashSize + gapSize);
  28377. for (i = 0; i < points.length - 1; i++) {
  28378. points[i + 1].subtractToRef(points[i], curvect);
  28379. nb = Math.floor(curvect.length() / shft);
  28380. curvect.normalize();
  28381. for (var j = 0; j < nb; j++) {
  28382. curshft = shft * j;
  28383. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  28384. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  28385. indices.push(idx, idx + 1);
  28386. idx += 2;
  28387. }
  28388. }
  28389. // Result
  28390. var vertexData = new VertexData();
  28391. vertexData.positions = positions;
  28392. vertexData.indices = indices;
  28393. return vertexData;
  28394. };
  28395. VertexData.CreateGround = function (options) {
  28396. var indices = [];
  28397. var positions = [];
  28398. var normals = [];
  28399. var uvs = [];
  28400. var row, col;
  28401. var width = options.width || 1;
  28402. var height = options.height || 1;
  28403. var subdivisions = options.subdivisions || 1;
  28404. for (row = 0; row <= subdivisions; row++) {
  28405. for (col = 0; col <= subdivisions; col++) {
  28406. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  28407. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28408. positions.push(position.x, position.y, position.z);
  28409. normals.push(normal.x, normal.y, normal.z);
  28410. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  28411. }
  28412. }
  28413. for (row = 0; row < subdivisions; row++) {
  28414. for (col = 0; col < subdivisions; col++) {
  28415. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  28416. indices.push(col + 1 + row * (subdivisions + 1));
  28417. indices.push(col + row * (subdivisions + 1));
  28418. indices.push(col + (row + 1) * (subdivisions + 1));
  28419. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  28420. indices.push(col + row * (subdivisions + 1));
  28421. }
  28422. }
  28423. // Result
  28424. var vertexData = new VertexData();
  28425. vertexData.indices = indices;
  28426. vertexData.positions = positions;
  28427. vertexData.normals = normals;
  28428. vertexData.uvs = uvs;
  28429. return vertexData;
  28430. };
  28431. VertexData.CreateTiledGround = function (options) {
  28432. var xmin = options.xmin;
  28433. var zmin = options.zmin;
  28434. var xmax = options.xmax;
  28435. var zmax = options.zmax;
  28436. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  28437. var precision = options.precision || { w: 1, h: 1 };
  28438. var indices = [];
  28439. var positions = [];
  28440. var normals = [];
  28441. var uvs = [];
  28442. var row, col, tileRow, tileCol;
  28443. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  28444. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  28445. precision.w = (precision.w < 1) ? 1 : precision.w;
  28446. precision.h = (precision.h < 1) ? 1 : precision.h;
  28447. var tileSize = {
  28448. 'w': (xmax - xmin) / subdivisions.w,
  28449. 'h': (zmax - zmin) / subdivisions.h
  28450. };
  28451. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  28452. // Indices
  28453. var base = positions.length / 3;
  28454. var rowLength = precision.w + 1;
  28455. for (row = 0; row < precision.h; row++) {
  28456. for (col = 0; col < precision.w; col++) {
  28457. var square = [
  28458. base + col + row * rowLength,
  28459. base + (col + 1) + row * rowLength,
  28460. base + (col + 1) + (row + 1) * rowLength,
  28461. base + col + (row + 1) * rowLength
  28462. ];
  28463. indices.push(square[1]);
  28464. indices.push(square[2]);
  28465. indices.push(square[3]);
  28466. indices.push(square[0]);
  28467. indices.push(square[1]);
  28468. indices.push(square[3]);
  28469. }
  28470. }
  28471. // Position, normals and uvs
  28472. var position = BABYLON.Vector3.Zero();
  28473. var normal = new BABYLON.Vector3(0, 1.0, 0);
  28474. for (row = 0; row <= precision.h; row++) {
  28475. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  28476. for (col = 0; col <= precision.w; col++) {
  28477. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  28478. position.y = 0;
  28479. positions.push(position.x, position.y, position.z);
  28480. normals.push(normal.x, normal.y, normal.z);
  28481. uvs.push(col / precision.w, row / precision.h);
  28482. }
  28483. }
  28484. }
  28485. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  28486. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  28487. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  28488. }
  28489. }
  28490. // Result
  28491. var vertexData = new VertexData();
  28492. vertexData.indices = indices;
  28493. vertexData.positions = positions;
  28494. vertexData.normals = normals;
  28495. vertexData.uvs = uvs;
  28496. return vertexData;
  28497. };
  28498. VertexData.CreateGroundFromHeightMap = function (options) {
  28499. var indices = [];
  28500. var positions = [];
  28501. var normals = [];
  28502. var uvs = [];
  28503. var row, col;
  28504. // Vertices
  28505. for (row = 0; row <= options.subdivisions; row++) {
  28506. for (col = 0; col <= options.subdivisions; col++) {
  28507. 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));
  28508. // Compute height
  28509. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  28510. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  28511. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  28512. var r = options.buffer[pos] / 255.0;
  28513. var g = options.buffer[pos + 1] / 255.0;
  28514. var b = options.buffer[pos + 2] / 255.0;
  28515. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28516. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  28517. // Add vertex
  28518. positions.push(position.x, position.y, position.z);
  28519. normals.push(0, 0, 0);
  28520. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  28521. }
  28522. }
  28523. // Indices
  28524. for (row = 0; row < options.subdivisions; row++) {
  28525. for (col = 0; col < options.subdivisions; col++) {
  28526. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28527. indices.push(col + 1 + row * (options.subdivisions + 1));
  28528. indices.push(col + row * (options.subdivisions + 1));
  28529. indices.push(col + (row + 1) * (options.subdivisions + 1));
  28530. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  28531. indices.push(col + row * (options.subdivisions + 1));
  28532. }
  28533. }
  28534. // Normals
  28535. VertexData.ComputeNormals(positions, indices, normals);
  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.CreatePlane = function (options) {
  28545. var indices = [];
  28546. var positions = [];
  28547. var normals = [];
  28548. var uvs = [];
  28549. var width = options.width || options.size || 1;
  28550. var height = options.height || options.size || 1;
  28551. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28552. // Vertices
  28553. var halfWidth = width / 2.0;
  28554. var halfHeight = height / 2.0;
  28555. positions.push(-halfWidth, -halfHeight, 0);
  28556. normals.push(0, 0, -1.0);
  28557. uvs.push(0.0, 0.0);
  28558. positions.push(halfWidth, -halfHeight, 0);
  28559. normals.push(0, 0, -1.0);
  28560. uvs.push(1.0, 0.0);
  28561. positions.push(halfWidth, halfHeight, 0);
  28562. normals.push(0, 0, -1.0);
  28563. uvs.push(1.0, 1.0);
  28564. positions.push(-halfWidth, halfHeight, 0);
  28565. normals.push(0, 0, -1.0);
  28566. uvs.push(0.0, 1.0);
  28567. // Indices
  28568. indices.push(0);
  28569. indices.push(1);
  28570. indices.push(2);
  28571. indices.push(0);
  28572. indices.push(2);
  28573. indices.push(3);
  28574. // Sides
  28575. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28576. // Result
  28577. var vertexData = new VertexData();
  28578. vertexData.indices = indices;
  28579. vertexData.positions = positions;
  28580. vertexData.normals = normals;
  28581. vertexData.uvs = uvs;
  28582. return vertexData;
  28583. };
  28584. VertexData.CreateDisc = function (options) {
  28585. var positions = [];
  28586. var indices = [];
  28587. var normals = [];
  28588. var uvs = [];
  28589. var radius = options.radius || 0.5;
  28590. var tessellation = options.tessellation || 64;
  28591. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28592. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28593. // positions and uvs
  28594. positions.push(0, 0, 0); // disc center first
  28595. uvs.push(0.5, 0.5);
  28596. var theta = Math.PI * 2 * arc;
  28597. var step = theta / tessellation;
  28598. for (var a = 0; a < theta; a += step) {
  28599. var x = Math.cos(a);
  28600. var y = Math.sin(a);
  28601. var u = (x + 1) / 2;
  28602. var v = (1 - y) / 2;
  28603. positions.push(radius * x, radius * y, 0);
  28604. uvs.push(u, v);
  28605. }
  28606. if (arc === 1) {
  28607. positions.push(positions[3], positions[4], positions[5]); // close the circle
  28608. uvs.push(uvs[2], uvs[3]);
  28609. }
  28610. //indices
  28611. var vertexNb = positions.length / 3;
  28612. for (var i = 1; i < vertexNb - 1; i++) {
  28613. indices.push(i + 1, 0, i);
  28614. }
  28615. // result
  28616. VertexData.ComputeNormals(positions, indices, normals);
  28617. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28618. var vertexData = new VertexData();
  28619. vertexData.indices = indices;
  28620. vertexData.positions = positions;
  28621. vertexData.normals = normals;
  28622. vertexData.uvs = uvs;
  28623. return vertexData;
  28624. };
  28625. VertexData.CreateIcoSphere = function (options) {
  28626. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28627. var radius = options.radius || 1;
  28628. var flat = (options.flat === undefined) ? true : options.flat;
  28629. var subdivisions = options.subdivisions || 4;
  28630. var radiusX = options.radiusX || radius;
  28631. var radiusY = options.radiusY || radius;
  28632. var radiusZ = options.radiusZ || radius;
  28633. var t = (1 + Math.sqrt(5)) / 2;
  28634. // 12 vertex x,y,z
  28635. var ico_vertices = [
  28636. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  28637. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  28638. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  28639. ];
  28640. // index of 3 vertex makes a face of icopshere
  28641. var ico_indices = [
  28642. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  28643. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  28644. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  28645. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  28646. ];
  28647. // vertex for uv have aliased position, not for UV
  28648. var vertices_unalias_id = [
  28649. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  28650. // vertex alias
  28651. 0,
  28652. 2,
  28653. 3,
  28654. 3,
  28655. 3,
  28656. 4,
  28657. 7,
  28658. 8,
  28659. 9,
  28660. 9,
  28661. 10,
  28662. 11 // 23: B + 12
  28663. ];
  28664. // uv as integer step (not pixels !)
  28665. var ico_vertexuv = [
  28666. 5, 1, 3, 1, 6, 4, 0, 0,
  28667. 5, 3, 4, 2, 2, 2, 4, 0,
  28668. 2, 0, 1, 1, 6, 0, 6, 2,
  28669. // vertex alias (for same vertex on different faces)
  28670. 0, 4,
  28671. 3, 3,
  28672. 4, 4,
  28673. 3, 1,
  28674. 4, 2,
  28675. 4, 4,
  28676. 0, 2,
  28677. 1, 1,
  28678. 2, 2,
  28679. 3, 3,
  28680. 1, 3,
  28681. 2, 4 // 23: B + 12
  28682. ];
  28683. // Vertices[0, 1, ...9, A, B] : position on UV plane
  28684. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  28685. // First island of uv mapping
  28686. // v = 4h 3+ 2
  28687. // v = 3h 9+ 4
  28688. // v = 2h 9+ 5 B
  28689. // v = 1h 9 1 0
  28690. // v = 0h 3 8 7 A
  28691. // u = 0 1 2 3 4 5 6 *a
  28692. // Second island of uv mapping
  28693. // v = 4h 0+ B+ 4+
  28694. // v = 3h A+ 2+
  28695. // v = 2h 7+ 6 3+
  28696. // v = 1h 8+ 3+
  28697. // v = 0h
  28698. // u = 0 1 2 3 4 5 6 *a
  28699. // Face layout on texture UV mapping
  28700. // ============
  28701. // \ 4 /\ 16 / ======
  28702. // \ / \ / /\ 11 /
  28703. // \/ 7 \/ / \ /
  28704. // ======= / 10 \/
  28705. // /\ 17 /\ =======
  28706. // / \ / \ \ 15 /\
  28707. // / 8 \/ 12 \ \ / \
  28708. // ============ \/ 6 \
  28709. // \ 18 /\ ============
  28710. // \ / \ \ 5 /\ 0 /
  28711. // \/ 13 \ \ / \ /
  28712. // ======= \/ 1 \/
  28713. // =============
  28714. // /\ 19 /\ 2 /\
  28715. // / \ / \ / \
  28716. // / 14 \/ 9 \/ 3 \
  28717. // ===================
  28718. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  28719. var ustep = 138 / 1024;
  28720. var vstep = 239 / 1024;
  28721. var uoffset = 60 / 1024;
  28722. var voffset = 26 / 1024;
  28723. // Second island should have margin, not to touch the first island
  28724. // avoid any borderline artefact in pixel rounding
  28725. var island_u_offset = -40 / 1024;
  28726. var island_v_offset = +20 / 1024;
  28727. // face is either island 0 or 1 :
  28728. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  28729. var island = [
  28730. 0, 0, 0, 0, 1,
  28731. 0, 0, 1, 1, 0,
  28732. 0, 0, 1, 1, 0,
  28733. 0, 1, 1, 1, 0 // 15 - 19
  28734. ];
  28735. var indices = [];
  28736. var positions = [];
  28737. var normals = [];
  28738. var uvs = [];
  28739. var current_indice = 0;
  28740. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  28741. var face_vertex_pos = new Array(3);
  28742. var face_vertex_uv = new Array(3);
  28743. var v012;
  28744. for (v012 = 0; v012 < 3; v012++) {
  28745. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  28746. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  28747. }
  28748. // create all with normals
  28749. for (var face = 0; face < 20; face++) {
  28750. // 3 vertex per face
  28751. for (v012 = 0; v012 < 3; v012++) {
  28752. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  28753. var v_id = ico_indices[3 * face + v012];
  28754. // vertex have 3D position (x,y,z)
  28755. 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]);
  28756. // Normalize to get normal, then scale to radius
  28757. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  28758. // uv Coordinates from vertex ID
  28759. 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);
  28760. }
  28761. // Subdivide the face (interpolate pos, norm, uv)
  28762. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  28763. // - norm is linear interpolation of vertex corner normal
  28764. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  28765. // - uv is linear interpolation
  28766. //
  28767. // Topology is as below for sub-divide by 2
  28768. // vertex shown as v0,v1,v2
  28769. // interp index is i1 to progress in range [v0,v1[
  28770. // interp index is i2 to progress in range [v0,v2[
  28771. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  28772. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28773. //
  28774. //
  28775. // i2 v2
  28776. // ^ ^
  28777. // / / \
  28778. // / / \
  28779. // / / \
  28780. // / / (0,1) \
  28781. // / #---------\
  28782. // / / \ (0,0)'/ \
  28783. // / / \ / \
  28784. // / / \ / \
  28785. // / / (0,0) \ / (1,0) \
  28786. // / #---------#---------\
  28787. // v0 v1
  28788. //
  28789. // --------------------> i1
  28790. //
  28791. // interp of (i1,i2):
  28792. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  28793. // along i1 : lerp(x0,x1, i1/(S-i2))
  28794. //
  28795. // centroid of triangle is needed to get help normal computation
  28796. // (c1,c2) are used for centroid location
  28797. var interp_vertex = function (i1, i2, c1, c2) {
  28798. // vertex is interpolated from
  28799. // - face_vertex_pos[0..2]
  28800. // - face_vertex_uv[0..2]
  28801. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  28802. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  28803. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  28804. pos_interp.normalize();
  28805. var vertex_normal;
  28806. if (flat) {
  28807. // in flat mode, recalculate normal as face centroid normal
  28808. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  28809. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  28810. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  28811. }
  28812. else {
  28813. // in smooth mode, recalculate normal from each single vertex position
  28814. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  28815. }
  28816. // Vertex normal need correction due to X,Y,Z radius scaling
  28817. vertex_normal.x /= radiusX;
  28818. vertex_normal.y /= radiusY;
  28819. vertex_normal.z /= radiusZ;
  28820. vertex_normal.normalize();
  28821. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  28822. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  28823. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  28824. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  28825. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  28826. uvs.push(uv_interp.x, uv_interp.y);
  28827. // push each vertex has member of a face
  28828. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  28829. indices.push(current_indice);
  28830. current_indice++;
  28831. };
  28832. for (var i2 = 0; i2 < subdivisions; i2++) {
  28833. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  28834. // face : (i1,i2) for /\ :
  28835. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  28836. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28837. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28838. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  28839. if (i1 + i2 + 1 < subdivisions) {
  28840. // face : (i1,i2)' for \/ :
  28841. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  28842. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28843. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28844. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  28845. }
  28846. }
  28847. }
  28848. }
  28849. // Sides
  28850. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28851. // Result
  28852. var vertexData = new VertexData();
  28853. vertexData.indices = indices;
  28854. vertexData.positions = positions;
  28855. vertexData.normals = normals;
  28856. vertexData.uvs = uvs;
  28857. return vertexData;
  28858. };
  28859. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  28860. VertexData.CreatePolyhedron = function (options) {
  28861. // provided polyhedron types :
  28862. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  28863. // 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)
  28864. var polyhedra = [];
  28865. 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]] };
  28866. 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]] };
  28867. polyhedra[2] = {
  28868. 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]],
  28869. 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]]
  28870. };
  28871. polyhedra[3] = {
  28872. 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]],
  28873. 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]]
  28874. };
  28875. polyhedra[4] = {
  28876. 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]],
  28877. 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]]
  28878. };
  28879. 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]] };
  28880. 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]] };
  28881. 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]] };
  28882. 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]] };
  28883. 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]] };
  28884. 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]] };
  28885. 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]] };
  28886. 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]] };
  28887. 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]] };
  28888. polyhedra[14] = {
  28889. 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]],
  28890. 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]]
  28891. };
  28892. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  28893. var size = options.size;
  28894. var sizeX = options.sizeX || size || 1;
  28895. var sizeY = options.sizeY || size || 1;
  28896. var sizeZ = options.sizeZ || size || 1;
  28897. var data = options.custom || polyhedra[type];
  28898. var nbfaces = data.face.length;
  28899. var faceUV = options.faceUV || new Array(nbfaces);
  28900. var faceColors = options.faceColors;
  28901. var flat = (options.flat === undefined) ? true : options.flat;
  28902. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28903. var positions = [];
  28904. var indices = [];
  28905. var normals = [];
  28906. var uvs = [];
  28907. var colors = [];
  28908. var index = 0;
  28909. var faceIdx = 0; // face cursor in the array "indexes"
  28910. var indexes = [];
  28911. var i = 0;
  28912. var f = 0;
  28913. var u, v, ang, x, y, tmp;
  28914. // default face colors and UV if undefined
  28915. if (flat) {
  28916. for (f = 0; f < nbfaces; f++) {
  28917. if (faceColors && faceColors[f] === undefined) {
  28918. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28919. }
  28920. if (faceUV && faceUV[f] === undefined) {
  28921. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28922. }
  28923. }
  28924. }
  28925. if (!flat) {
  28926. for (i = 0; i < data.vertex.length; i++) {
  28927. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  28928. uvs.push(0, 0);
  28929. }
  28930. for (f = 0; f < nbfaces; f++) {
  28931. for (i = 0; i < data.face[f].length - 2; i++) {
  28932. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  28933. }
  28934. }
  28935. }
  28936. else {
  28937. for (f = 0; f < nbfaces; f++) {
  28938. var fl = data.face[f].length; // number of vertices of the current face
  28939. ang = 2 * Math.PI / fl;
  28940. x = 0.5 * Math.tan(ang / 2);
  28941. y = 0.5;
  28942. // positions, uvs, colors
  28943. for (i = 0; i < fl; i++) {
  28944. // positions
  28945. 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);
  28946. indexes.push(index);
  28947. index++;
  28948. // uvs
  28949. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  28950. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  28951. uvs.push(u, v);
  28952. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  28953. y = x * Math.sin(ang) + y * Math.cos(ang);
  28954. x = tmp;
  28955. // colors
  28956. if (faceColors) {
  28957. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  28958. }
  28959. }
  28960. // indices from indexes
  28961. for (i = 0; i < fl - 2; i++) {
  28962. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  28963. }
  28964. faceIdx += fl;
  28965. }
  28966. }
  28967. VertexData.ComputeNormals(positions, indices, normals);
  28968. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  28969. var vertexData = new VertexData();
  28970. vertexData.positions = positions;
  28971. vertexData.indices = indices;
  28972. vertexData.normals = normals;
  28973. vertexData.uvs = uvs;
  28974. if (faceColors && flat) {
  28975. vertexData.colors = colors;
  28976. }
  28977. return vertexData;
  28978. };
  28979. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  28980. VertexData.CreateTorusKnot = function (options) {
  28981. var indices = [];
  28982. var positions = [];
  28983. var normals = [];
  28984. var uvs = [];
  28985. var radius = options.radius || 2;
  28986. var tube = options.tube || 0.5;
  28987. var radialSegments = options.radialSegments || 32;
  28988. var tubularSegments = options.tubularSegments || 32;
  28989. var p = options.p || 2;
  28990. var q = options.q || 3;
  28991. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28992. // Helper
  28993. var getPos = function (angle) {
  28994. var cu = Math.cos(angle);
  28995. var su = Math.sin(angle);
  28996. var quOverP = q / p * angle;
  28997. var cs = Math.cos(quOverP);
  28998. var tx = radius * (2 + cs) * 0.5 * cu;
  28999. var ty = radius * (2 + cs) * su * 0.5;
  29000. var tz = radius * Math.sin(quOverP) * 0.5;
  29001. return new BABYLON.Vector3(tx, ty, tz);
  29002. };
  29003. // Vertices
  29004. var i;
  29005. var j;
  29006. for (i = 0; i <= radialSegments; i++) {
  29007. var modI = i % radialSegments;
  29008. var u = modI / radialSegments * 2 * p * Math.PI;
  29009. var p1 = getPos(u);
  29010. var p2 = getPos(u + 0.01);
  29011. var tang = p2.subtract(p1);
  29012. var n = p2.add(p1);
  29013. var bitan = BABYLON.Vector3.Cross(tang, n);
  29014. n = BABYLON.Vector3.Cross(bitan, tang);
  29015. bitan.normalize();
  29016. n.normalize();
  29017. for (j = 0; j < tubularSegments; j++) {
  29018. var modJ = j % tubularSegments;
  29019. var v = modJ / tubularSegments * 2 * Math.PI;
  29020. var cx = -tube * Math.cos(v);
  29021. var cy = tube * Math.sin(v);
  29022. positions.push(p1.x + cx * n.x + cy * bitan.x);
  29023. positions.push(p1.y + cx * n.y + cy * bitan.y);
  29024. positions.push(p1.z + cx * n.z + cy * bitan.z);
  29025. uvs.push(i / radialSegments);
  29026. uvs.push(j / tubularSegments);
  29027. }
  29028. }
  29029. for (i = 0; i < radialSegments; i++) {
  29030. for (j = 0; j < tubularSegments; j++) {
  29031. var jNext = (j + 1) % tubularSegments;
  29032. var a = i * tubularSegments + j;
  29033. var b = (i + 1) * tubularSegments + j;
  29034. var c = (i + 1) * tubularSegments + jNext;
  29035. var d = i * tubularSegments + jNext;
  29036. indices.push(d);
  29037. indices.push(b);
  29038. indices.push(a);
  29039. indices.push(d);
  29040. indices.push(c);
  29041. indices.push(b);
  29042. }
  29043. }
  29044. // Normals
  29045. VertexData.ComputeNormals(positions, indices, normals);
  29046. // Sides
  29047. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  29048. // Result
  29049. var vertexData = new VertexData();
  29050. vertexData.indices = indices;
  29051. vertexData.positions = positions;
  29052. vertexData.normals = normals;
  29053. vertexData.uvs = uvs;
  29054. return vertexData;
  29055. };
  29056. // Tools
  29057. /**
  29058. * @param {any} - positions (number[] or Float32Array)
  29059. * @param {any} - indices (number[] or Uint16Array)
  29060. * @param {any} - normals (number[] or Float32Array)
  29061. */
  29062. VertexData.ComputeNormals = function (positions, indices, normals) {
  29063. var index = 0;
  29064. var p1p2x = 0.0;
  29065. var p1p2y = 0.0;
  29066. var p1p2z = 0.0;
  29067. var p3p2x = 0.0;
  29068. var p3p2y = 0.0;
  29069. var p3p2z = 0.0;
  29070. var faceNormalx = 0.0;
  29071. var faceNormaly = 0.0;
  29072. var faceNormalz = 0.0;
  29073. var length = 0.0;
  29074. var i1 = 0;
  29075. var i2 = 0;
  29076. var i3 = 0;
  29077. for (index = 0; index < positions.length; index++) {
  29078. normals[index] = 0.0;
  29079. }
  29080. // indice triplet = 1 face
  29081. var nbFaces = indices.length / 3;
  29082. for (index = 0; index < nbFaces; index++) {
  29083. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  29084. i2 = indices[index * 3 + 1];
  29085. i3 = indices[index * 3 + 2];
  29086. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  29087. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  29088. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  29089. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  29090. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  29091. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  29092. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  29093. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  29094. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  29095. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29096. length = (length === 0) ? 1.0 : length;
  29097. faceNormalx /= length; // normalize this normal
  29098. faceNormaly /= length;
  29099. faceNormalz /= length;
  29100. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  29101. normals[i1 * 3 + 1] += faceNormaly;
  29102. normals[i1 * 3 + 2] += faceNormalz;
  29103. normals[i2 * 3] += faceNormalx;
  29104. normals[i2 * 3 + 1] += faceNormaly;
  29105. normals[i2 * 3 + 2] += faceNormalz;
  29106. normals[i3 * 3] += faceNormalx;
  29107. normals[i3 * 3 + 1] += faceNormaly;
  29108. normals[i3 * 3 + 2] += faceNormalz;
  29109. }
  29110. // last normalization of each normal
  29111. for (index = 0; index < normals.length / 3; index++) {
  29112. faceNormalx = normals[index * 3];
  29113. faceNormaly = normals[index * 3 + 1];
  29114. faceNormalz = normals[index * 3 + 2];
  29115. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  29116. length = (length === 0) ? 1.0 : length;
  29117. faceNormalx /= length;
  29118. faceNormaly /= length;
  29119. faceNormalz /= length;
  29120. normals[index * 3] = faceNormalx;
  29121. normals[index * 3 + 1] = faceNormaly;
  29122. normals[index * 3 + 2] = faceNormalz;
  29123. }
  29124. };
  29125. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  29126. var li = indices.length;
  29127. var ln = normals.length;
  29128. var i;
  29129. var n;
  29130. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29131. switch (sideOrientation) {
  29132. case BABYLON.Mesh.FRONTSIDE:
  29133. // nothing changed
  29134. break;
  29135. case BABYLON.Mesh.BACKSIDE:
  29136. var tmp;
  29137. // indices
  29138. for (i = 0; i < li; i += 3) {
  29139. tmp = indices[i];
  29140. indices[i] = indices[i + 2];
  29141. indices[i + 2] = tmp;
  29142. }
  29143. // normals
  29144. for (n = 0; n < ln; n++) {
  29145. normals[n] = -normals[n];
  29146. }
  29147. break;
  29148. case BABYLON.Mesh.DOUBLESIDE:
  29149. // positions
  29150. var lp = positions.length;
  29151. var l = lp / 3;
  29152. for (var p = 0; p < lp; p++) {
  29153. positions[lp + p] = positions[p];
  29154. }
  29155. // indices
  29156. for (i = 0; i < li; i += 3) {
  29157. indices[i + li] = indices[i + 2] + l;
  29158. indices[i + 1 + li] = indices[i + 1] + l;
  29159. indices[i + 2 + li] = indices[i] + l;
  29160. }
  29161. // normals
  29162. for (n = 0; n < ln; n++) {
  29163. normals[ln + n] = -normals[n];
  29164. }
  29165. // uvs
  29166. var lu = uvs.length;
  29167. for (var u = 0; u < lu; u++) {
  29168. uvs[u + lu] = uvs[u];
  29169. }
  29170. break;
  29171. }
  29172. };
  29173. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  29174. var vertexData = new VertexData();
  29175. // positions
  29176. var positions = parsedVertexData.positions;
  29177. if (positions) {
  29178. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  29179. }
  29180. // normals
  29181. var normals = parsedVertexData.normals;
  29182. if (normals) {
  29183. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  29184. }
  29185. // uvs
  29186. var uvs = parsedVertexData.uvs;
  29187. if (uvs) {
  29188. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  29189. }
  29190. // uv2s
  29191. var uv2s = parsedVertexData.uv2s;
  29192. if (uv2s) {
  29193. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  29194. }
  29195. // uv3s
  29196. var uv3s = parsedVertexData.uv3s;
  29197. if (uv3s) {
  29198. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  29199. }
  29200. // uv4s
  29201. var uv4s = parsedVertexData.uv4s;
  29202. if (uv4s) {
  29203. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  29204. }
  29205. // uv5s
  29206. var uv5s = parsedVertexData.uv5s;
  29207. if (uv5s) {
  29208. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  29209. }
  29210. // uv6s
  29211. var uv6s = parsedVertexData.uv6s;
  29212. if (uv6s) {
  29213. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  29214. }
  29215. // colors
  29216. var colors = parsedVertexData.colors;
  29217. if (colors) {
  29218. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  29219. }
  29220. // matricesIndices
  29221. var matricesIndices = parsedVertexData.matricesIndices;
  29222. if (matricesIndices) {
  29223. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  29224. }
  29225. // matricesWeights
  29226. var matricesWeights = parsedVertexData.matricesWeights;
  29227. if (matricesWeights) {
  29228. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  29229. }
  29230. // indices
  29231. var indices = parsedVertexData.indices;
  29232. if (indices) {
  29233. vertexData.indices = indices;
  29234. }
  29235. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  29236. };
  29237. return VertexData;
  29238. })();
  29239. BABYLON.VertexData = VertexData;
  29240. })(BABYLON || (BABYLON = {}));
  29241. var BABYLON;
  29242. (function (BABYLON) {
  29243. var Tags = (function () {
  29244. function Tags() {
  29245. }
  29246. Tags.EnableFor = function (obj) {
  29247. obj._tags = obj._tags || {};
  29248. obj.hasTags = function () {
  29249. return Tags.HasTags(obj);
  29250. };
  29251. obj.addTags = function (tagsString) {
  29252. return Tags.AddTagsTo(obj, tagsString);
  29253. };
  29254. obj.removeTags = function (tagsString) {
  29255. return Tags.RemoveTagsFrom(obj, tagsString);
  29256. };
  29257. obj.matchesTagsQuery = function (tagsQuery) {
  29258. return Tags.MatchesQuery(obj, tagsQuery);
  29259. };
  29260. };
  29261. Tags.DisableFor = function (obj) {
  29262. delete obj._tags;
  29263. delete obj.hasTags;
  29264. delete obj.addTags;
  29265. delete obj.removeTags;
  29266. delete obj.matchesTagsQuery;
  29267. };
  29268. Tags.HasTags = function (obj) {
  29269. if (!obj._tags) {
  29270. return false;
  29271. }
  29272. return !BABYLON.Tools.IsEmpty(obj._tags);
  29273. };
  29274. Tags.GetTags = function (obj, asString) {
  29275. if (asString === void 0) { asString = true; }
  29276. if (!obj._tags) {
  29277. return null;
  29278. }
  29279. if (asString) {
  29280. var tagsArray = [];
  29281. for (var tag in obj._tags) {
  29282. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  29283. tagsArray.push(tag);
  29284. }
  29285. }
  29286. return tagsArray.join(" ");
  29287. }
  29288. else {
  29289. return obj._tags;
  29290. }
  29291. };
  29292. // the tags 'true' and 'false' are reserved and cannot be used as tags
  29293. // a tag cannot start with '||', '&&', and '!'
  29294. // it cannot contain whitespaces
  29295. Tags.AddTagsTo = function (obj, tagsString) {
  29296. if (!tagsString) {
  29297. return;
  29298. }
  29299. if (typeof tagsString !== "string") {
  29300. return;
  29301. }
  29302. var tags = tagsString.split(" ");
  29303. for (var t in tags) {
  29304. Tags._AddTagTo(obj, tags[t]);
  29305. }
  29306. };
  29307. Tags._AddTagTo = function (obj, tag) {
  29308. tag = tag.trim();
  29309. if (tag === "" || tag === "true" || tag === "false") {
  29310. return;
  29311. }
  29312. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  29313. return;
  29314. }
  29315. Tags.EnableFor(obj);
  29316. obj._tags[tag] = true;
  29317. };
  29318. Tags.RemoveTagsFrom = function (obj, tagsString) {
  29319. if (!Tags.HasTags(obj)) {
  29320. return;
  29321. }
  29322. var tags = tagsString.split(" ");
  29323. for (var t in tags) {
  29324. Tags._RemoveTagFrom(obj, tags[t]);
  29325. }
  29326. };
  29327. Tags._RemoveTagFrom = function (obj, tag) {
  29328. delete obj._tags[tag];
  29329. };
  29330. Tags.MatchesQuery = function (obj, tagsQuery) {
  29331. if (tagsQuery === undefined) {
  29332. return true;
  29333. }
  29334. if (tagsQuery === "") {
  29335. return Tags.HasTags(obj);
  29336. }
  29337. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  29338. };
  29339. return Tags;
  29340. })();
  29341. BABYLON.Tags = Tags;
  29342. })(BABYLON || (BABYLON = {}));
  29343. var BABYLON;
  29344. (function (BABYLON) {
  29345. var Internals;
  29346. (function (Internals) {
  29347. var AndOrNotEvaluator = (function () {
  29348. function AndOrNotEvaluator() {
  29349. }
  29350. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  29351. if (!query.match(/\([^\(\)]*\)/g)) {
  29352. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  29353. }
  29354. else {
  29355. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  29356. // remove parenthesis
  29357. r = r.slice(1, r.length - 1);
  29358. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  29359. });
  29360. }
  29361. if (query === "true") {
  29362. return true;
  29363. }
  29364. if (query === "false") {
  29365. return false;
  29366. }
  29367. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  29368. };
  29369. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  29370. evaluateCallback = evaluateCallback || (function (r) {
  29371. return r === "true" ? true : false;
  29372. });
  29373. var result;
  29374. var or = parenthesisContent.split("||");
  29375. for (var i in or) {
  29376. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  29377. var and = ori.split("&&");
  29378. if (and.length > 1) {
  29379. for (var j = 0; j < and.length; ++j) {
  29380. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  29381. if (andj !== "true" && andj !== "false") {
  29382. if (andj[0] === "!") {
  29383. result = !evaluateCallback(andj.substring(1));
  29384. }
  29385. else {
  29386. result = evaluateCallback(andj);
  29387. }
  29388. }
  29389. else {
  29390. result = andj === "true" ? true : false;
  29391. }
  29392. if (!result) {
  29393. ori = "false";
  29394. break;
  29395. }
  29396. }
  29397. }
  29398. if (result || ori === "true") {
  29399. result = true;
  29400. break;
  29401. }
  29402. // result equals false (or undefined)
  29403. if (ori !== "true" && ori !== "false") {
  29404. if (ori[0] === "!") {
  29405. result = !evaluateCallback(ori.substring(1));
  29406. }
  29407. else {
  29408. result = evaluateCallback(ori);
  29409. }
  29410. }
  29411. else {
  29412. result = ori === "true" ? true : false;
  29413. }
  29414. }
  29415. // the whole parenthesis scope is replaced by 'true' or 'false'
  29416. return result ? "true" : "false";
  29417. };
  29418. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  29419. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  29420. // remove whitespaces
  29421. r = r.replace(/[\s]/g, function () { return ""; });
  29422. return r.length % 2 ? "!" : "";
  29423. });
  29424. booleanString = booleanString.trim();
  29425. if (booleanString === "!true") {
  29426. booleanString = "false";
  29427. }
  29428. else if (booleanString === "!false") {
  29429. booleanString = "true";
  29430. }
  29431. return booleanString;
  29432. };
  29433. return AndOrNotEvaluator;
  29434. })();
  29435. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  29436. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  29437. })(BABYLON || (BABYLON = {}));
  29438. var BABYLON;
  29439. (function (BABYLON) {
  29440. var PostProcessRenderPass = (function () {
  29441. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  29442. this._enabled = true;
  29443. this._refCount = 0;
  29444. this._name = name;
  29445. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  29446. this.setRenderList(renderList);
  29447. this._renderTexture.onBeforeRender = beforeRender;
  29448. this._renderTexture.onAfterRender = afterRender;
  29449. this._scene = scene;
  29450. this._renderList = renderList;
  29451. }
  29452. // private
  29453. PostProcessRenderPass.prototype._incRefCount = function () {
  29454. if (this._refCount === 0) {
  29455. this._scene.customRenderTargets.push(this._renderTexture);
  29456. }
  29457. return ++this._refCount;
  29458. };
  29459. PostProcessRenderPass.prototype._decRefCount = function () {
  29460. this._refCount--;
  29461. if (this._refCount <= 0) {
  29462. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  29463. }
  29464. return this._refCount;
  29465. };
  29466. PostProcessRenderPass.prototype._update = function () {
  29467. this.setRenderList(this._renderList);
  29468. };
  29469. // public
  29470. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  29471. this._renderTexture.renderList = renderList;
  29472. };
  29473. PostProcessRenderPass.prototype.getRenderTexture = function () {
  29474. return this._renderTexture;
  29475. };
  29476. return PostProcessRenderPass;
  29477. })();
  29478. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  29479. })(BABYLON || (BABYLON = {}));
  29480. var BABYLON;
  29481. (function (BABYLON) {
  29482. var PostProcessRenderEffect = (function () {
  29483. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  29484. this._engine = engine;
  29485. this._name = name;
  29486. this._singleInstance = singleInstance || true;
  29487. this._getPostProcess = getPostProcess;
  29488. this._cameras = [];
  29489. this._indicesForCamera = [];
  29490. this._postProcesses = {};
  29491. this._renderPasses = {};
  29492. this._renderEffectAsPasses = {};
  29493. }
  29494. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  29495. get: function () {
  29496. for (var index in this._postProcesses) {
  29497. if (!this._postProcesses[index].isSupported) {
  29498. return false;
  29499. }
  29500. }
  29501. return true;
  29502. },
  29503. enumerable: true,
  29504. configurable: true
  29505. });
  29506. PostProcessRenderEffect.prototype._update = function () {
  29507. for (var renderPassName in this._renderPasses) {
  29508. this._renderPasses[renderPassName]._update();
  29509. }
  29510. };
  29511. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  29512. this._renderPasses[renderPass._name] = renderPass;
  29513. this._linkParameters();
  29514. };
  29515. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  29516. delete this._renderPasses[renderPass._name];
  29517. this._linkParameters();
  29518. };
  29519. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  29520. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  29521. this._linkParameters();
  29522. };
  29523. PostProcessRenderEffect.prototype.getPass = function (passName) {
  29524. for (var renderPassName in this._renderPasses) {
  29525. if (renderPassName === passName) {
  29526. return this._renderPasses[passName];
  29527. }
  29528. }
  29529. };
  29530. PostProcessRenderEffect.prototype.emptyPasses = function () {
  29531. this._renderPasses = {};
  29532. this._linkParameters();
  29533. };
  29534. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  29535. var cameraKey;
  29536. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29537. for (var i = 0; i < _cam.length; i++) {
  29538. var camera = _cam[i];
  29539. var cameraName = camera.name;
  29540. if (this._singleInstance) {
  29541. cameraKey = 0;
  29542. }
  29543. else {
  29544. cameraKey = cameraName;
  29545. }
  29546. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  29547. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  29548. if (!this._indicesForCamera[cameraName]) {
  29549. this._indicesForCamera[cameraName] = [];
  29550. }
  29551. this._indicesForCamera[cameraName].push(index);
  29552. if (this._cameras.indexOf(camera) === -1) {
  29553. this._cameras[cameraName] = camera;
  29554. }
  29555. for (var passName in this._renderPasses) {
  29556. this._renderPasses[passName]._incRefCount();
  29557. }
  29558. }
  29559. this._linkParameters();
  29560. };
  29561. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  29562. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29563. for (var i = 0; i < _cam.length; i++) {
  29564. var camera = _cam[i];
  29565. var cameraName = camera.name;
  29566. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  29567. var index = this._cameras.indexOf(cameraName);
  29568. this._indicesForCamera.splice(index, 1);
  29569. this._cameras.splice(index, 1);
  29570. for (var passName in this._renderPasses) {
  29571. this._renderPasses[passName]._decRefCount();
  29572. }
  29573. }
  29574. };
  29575. PostProcessRenderEffect.prototype._enable = function (cameras) {
  29576. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29577. for (var i = 0; i < _cam.length; i++) {
  29578. var camera = _cam[i];
  29579. var cameraName = camera.name;
  29580. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  29581. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  29582. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  29583. }
  29584. }
  29585. for (var passName in this._renderPasses) {
  29586. this._renderPasses[passName]._incRefCount();
  29587. }
  29588. }
  29589. };
  29590. PostProcessRenderEffect.prototype._disable = function (cameras) {
  29591. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29592. for (var i = 0; i < _cam.length; i++) {
  29593. var camera = _cam[i];
  29594. var cameraName = camera.Name;
  29595. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  29596. for (var passName in this._renderPasses) {
  29597. this._renderPasses[passName]._decRefCount();
  29598. }
  29599. }
  29600. };
  29601. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  29602. if (this._singleInstance) {
  29603. return this._postProcesses[0];
  29604. }
  29605. else {
  29606. return this._postProcesses[camera.name];
  29607. }
  29608. };
  29609. PostProcessRenderEffect.prototype._linkParameters = function () {
  29610. var _this = this;
  29611. for (var index in this._postProcesses) {
  29612. if (this.applyParameters) {
  29613. this.applyParameters(this._postProcesses[index]);
  29614. }
  29615. this._postProcesses[index].onBeforeRender = function (effect) {
  29616. _this._linkTextures(effect);
  29617. };
  29618. }
  29619. };
  29620. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  29621. for (var renderPassName in this._renderPasses) {
  29622. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  29623. }
  29624. for (var renderEffectName in this._renderEffectAsPasses) {
  29625. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  29626. }
  29627. };
  29628. return PostProcessRenderEffect;
  29629. })();
  29630. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  29631. })(BABYLON || (BABYLON = {}));
  29632. var BABYLON;
  29633. (function (BABYLON) {
  29634. var PostProcessRenderPipeline = (function () {
  29635. function PostProcessRenderPipeline(engine, name) {
  29636. this._engine = engine;
  29637. this._name = name;
  29638. this._renderEffects = {};
  29639. this._renderEffectsForIsolatedPass = {};
  29640. this._cameras = [];
  29641. }
  29642. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  29643. get: function () {
  29644. for (var renderEffectName in this._renderEffects) {
  29645. if (!this._renderEffects[renderEffectName].isSupported) {
  29646. return false;
  29647. }
  29648. }
  29649. return true;
  29650. },
  29651. enumerable: true,
  29652. configurable: true
  29653. });
  29654. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  29655. this._renderEffects[renderEffect._name] = renderEffect;
  29656. };
  29657. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  29658. var renderEffects = this._renderEffects[renderEffectName];
  29659. if (!renderEffects) {
  29660. return;
  29661. }
  29662. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  29663. };
  29664. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  29665. var renderEffects = this._renderEffects[renderEffectName];
  29666. if (!renderEffects) {
  29667. return;
  29668. }
  29669. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  29670. };
  29671. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  29672. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29673. var indicesToDelete = [];
  29674. var i;
  29675. for (i = 0; i < _cam.length; i++) {
  29676. var camera = _cam[i];
  29677. var cameraName = camera.name;
  29678. if (this._cameras.indexOf(camera) === -1) {
  29679. this._cameras[cameraName] = camera;
  29680. }
  29681. else if (unique) {
  29682. indicesToDelete.push(i);
  29683. }
  29684. }
  29685. for (i = 0; i < indicesToDelete.length; i++) {
  29686. cameras.splice(indicesToDelete[i], 1);
  29687. }
  29688. for (var renderEffectName in this._renderEffects) {
  29689. this._renderEffects[renderEffectName]._attachCameras(_cam);
  29690. }
  29691. };
  29692. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  29693. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29694. for (var renderEffectName in this._renderEffects) {
  29695. this._renderEffects[renderEffectName]._detachCameras(_cam);
  29696. }
  29697. for (var i = 0; i < _cam.length; i++) {
  29698. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  29699. }
  29700. };
  29701. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  29702. var _this = this;
  29703. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29704. var pass = null;
  29705. var renderEffectName;
  29706. for (renderEffectName in this._renderEffects) {
  29707. pass = this._renderEffects[renderEffectName].getPass(passName);
  29708. if (pass != null) {
  29709. break;
  29710. }
  29711. }
  29712. if (pass === null) {
  29713. return;
  29714. }
  29715. for (renderEffectName in this._renderEffects) {
  29716. this._renderEffects[renderEffectName]._disable(_cam);
  29717. }
  29718. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  29719. for (var i = 0; i < _cam.length; i++) {
  29720. var camera = _cam[i];
  29721. var cameraName = camera.name;
  29722. 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); });
  29723. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  29724. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  29725. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  29726. }
  29727. };
  29728. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  29729. var _this = this;
  29730. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  29731. for (var i = 0; i < _cam.length; i++) {
  29732. var camera = _cam[i];
  29733. var cameraName = camera.name;
  29734. 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); });
  29735. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  29736. }
  29737. for (var renderEffectName in this._renderEffects) {
  29738. this._renderEffects[renderEffectName]._enable(_cam);
  29739. }
  29740. };
  29741. PostProcessRenderPipeline.prototype._update = function () {
  29742. for (var renderEffectName in this._renderEffects) {
  29743. this._renderEffects[renderEffectName]._update();
  29744. }
  29745. for (var i = 0; i < this._cameras.length; i++) {
  29746. var cameraName = this._cameras[i].name;
  29747. if (this._renderEffectsForIsolatedPass[cameraName]) {
  29748. this._renderEffectsForIsolatedPass[cameraName]._update();
  29749. }
  29750. }
  29751. };
  29752. PostProcessRenderPipeline.prototype.dispose = function () {
  29753. // Must be implemented by children
  29754. };
  29755. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  29756. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  29757. return PostProcessRenderPipeline;
  29758. })();
  29759. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  29760. })(BABYLON || (BABYLON = {}));
  29761. var BABYLON;
  29762. (function (BABYLON) {
  29763. var PostProcessRenderPipelineManager = (function () {
  29764. function PostProcessRenderPipelineManager() {
  29765. this._renderPipelines = {};
  29766. }
  29767. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  29768. this._renderPipelines[renderPipeline._name] = renderPipeline;
  29769. };
  29770. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  29771. var renderPipeline = this._renderPipelines[renderPipelineName];
  29772. if (!renderPipeline) {
  29773. return;
  29774. }
  29775. renderPipeline._attachCameras(cameras, unique);
  29776. };
  29777. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  29778. var renderPipeline = this._renderPipelines[renderPipelineName];
  29779. if (!renderPipeline) {
  29780. return;
  29781. }
  29782. renderPipeline._detachCameras(cameras);
  29783. };
  29784. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  29785. var renderPipeline = this._renderPipelines[renderPipelineName];
  29786. if (!renderPipeline) {
  29787. return;
  29788. }
  29789. renderPipeline._enableEffect(renderEffectName, cameras);
  29790. };
  29791. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  29792. var renderPipeline = this._renderPipelines[renderPipelineName];
  29793. if (!renderPipeline) {
  29794. return;
  29795. }
  29796. renderPipeline._disableEffect(renderEffectName, cameras);
  29797. };
  29798. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  29799. var renderPipeline = this._renderPipelines[renderPipelineName];
  29800. if (!renderPipeline) {
  29801. return;
  29802. }
  29803. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  29804. };
  29805. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  29806. var renderPipeline = this._renderPipelines[renderPipelineName];
  29807. if (!renderPipeline) {
  29808. return;
  29809. }
  29810. renderPipeline._disableDisplayOnlyPass(cameras);
  29811. };
  29812. PostProcessRenderPipelineManager.prototype.update = function () {
  29813. for (var renderPipelineName in this._renderPipelines) {
  29814. var pipeline = this._renderPipelines[renderPipelineName];
  29815. if (!pipeline.isSupported) {
  29816. pipeline.dispose();
  29817. delete this._renderPipelines[renderPipelineName];
  29818. }
  29819. else {
  29820. pipeline._update();
  29821. }
  29822. }
  29823. };
  29824. return PostProcessRenderPipelineManager;
  29825. })();
  29826. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  29827. })(BABYLON || (BABYLON = {}));
  29828. var BABYLON;
  29829. (function (BABYLON) {
  29830. var BoundingBoxRenderer = (function () {
  29831. function BoundingBoxRenderer(scene) {
  29832. this.frontColor = new BABYLON.Color3(1, 1, 1);
  29833. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  29834. this.showBackLines = true;
  29835. this.renderList = new BABYLON.SmartArray(32);
  29836. this._scene = scene;
  29837. }
  29838. BoundingBoxRenderer.prototype._prepareRessources = function () {
  29839. if (this._colorShader) {
  29840. return;
  29841. }
  29842. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  29843. attributes: ["position"],
  29844. uniforms: ["worldViewProjection", "color"]
  29845. });
  29846. var engine = this._scene.getEngine();
  29847. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  29848. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  29849. 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]);
  29850. };
  29851. BoundingBoxRenderer.prototype.reset = function () {
  29852. this.renderList.reset();
  29853. };
  29854. BoundingBoxRenderer.prototype.render = function () {
  29855. if (this.renderList.length === 0) {
  29856. return;
  29857. }
  29858. this._prepareRessources();
  29859. if (!this._colorShader.isReady()) {
  29860. return;
  29861. }
  29862. var engine = this._scene.getEngine();
  29863. engine.setDepthWrite(false);
  29864. this._colorShader._preBind();
  29865. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  29866. var boundingBox = this.renderList.data[boundingBoxIndex];
  29867. var min = boundingBox.minimum;
  29868. var max = boundingBox.maximum;
  29869. var diff = max.subtract(min);
  29870. var median = min.add(diff.scale(0.5));
  29871. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  29872. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  29873. .multiply(boundingBox.getWorldMatrix());
  29874. // VBOs
  29875. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  29876. if (this.showBackLines) {
  29877. // Back
  29878. engine.setDepthFunctionToGreaterOrEqual();
  29879. this._scene.resetCachedMaterial();
  29880. this._colorShader.setColor4("color", this.backColor.toColor4());
  29881. this._colorShader.bind(worldMatrix);
  29882. // Draw order
  29883. engine.draw(false, 0, 24);
  29884. }
  29885. // Front
  29886. engine.setDepthFunctionToLess();
  29887. this._scene.resetCachedMaterial();
  29888. this._colorShader.setColor4("color", this.frontColor.toColor4());
  29889. this._colorShader.bind(worldMatrix);
  29890. // Draw order
  29891. engine.draw(false, 0, 24);
  29892. }
  29893. this._colorShader.unbind();
  29894. engine.setDepthFunctionToLessOrEqual();
  29895. engine.setDepthWrite(true);
  29896. };
  29897. BoundingBoxRenderer.prototype.dispose = function () {
  29898. if (!this._colorShader) {
  29899. return;
  29900. }
  29901. this._colorShader.dispose();
  29902. this._vb.dispose();
  29903. this._scene.getEngine()._releaseBuffer(this._ib);
  29904. };
  29905. return BoundingBoxRenderer;
  29906. })();
  29907. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  29908. })(BABYLON || (BABYLON = {}));
  29909. var BABYLON;
  29910. (function (BABYLON) {
  29911. var Condition = (function () {
  29912. function Condition(actionManager) {
  29913. this._actionManager = actionManager;
  29914. }
  29915. Condition.prototype.isValid = function () {
  29916. return true;
  29917. };
  29918. Condition.prototype._getProperty = function (propertyPath) {
  29919. return this._actionManager._getProperty(propertyPath);
  29920. };
  29921. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  29922. return this._actionManager._getEffectiveTarget(target, propertyPath);
  29923. };
  29924. return Condition;
  29925. })();
  29926. BABYLON.Condition = Condition;
  29927. var ValueCondition = (function (_super) {
  29928. __extends(ValueCondition, _super);
  29929. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  29930. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  29931. _super.call(this, actionManager);
  29932. this.propertyPath = propertyPath;
  29933. this.value = value;
  29934. this.operator = operator;
  29935. this._target = this._getEffectiveTarget(target, this.propertyPath);
  29936. this._property = this._getProperty(this.propertyPath);
  29937. }
  29938. Object.defineProperty(ValueCondition, "IsEqual", {
  29939. get: function () {
  29940. return ValueCondition._IsEqual;
  29941. },
  29942. enumerable: true,
  29943. configurable: true
  29944. });
  29945. Object.defineProperty(ValueCondition, "IsDifferent", {
  29946. get: function () {
  29947. return ValueCondition._IsDifferent;
  29948. },
  29949. enumerable: true,
  29950. configurable: true
  29951. });
  29952. Object.defineProperty(ValueCondition, "IsGreater", {
  29953. get: function () {
  29954. return ValueCondition._IsGreater;
  29955. },
  29956. enumerable: true,
  29957. configurable: true
  29958. });
  29959. Object.defineProperty(ValueCondition, "IsLesser", {
  29960. get: function () {
  29961. return ValueCondition._IsLesser;
  29962. },
  29963. enumerable: true,
  29964. configurable: true
  29965. });
  29966. // Methods
  29967. ValueCondition.prototype.isValid = function () {
  29968. switch (this.operator) {
  29969. case ValueCondition.IsGreater:
  29970. return this._target[this._property] > this.value;
  29971. case ValueCondition.IsLesser:
  29972. return this._target[this._property] < this.value;
  29973. case ValueCondition.IsEqual:
  29974. case ValueCondition.IsDifferent:
  29975. var check;
  29976. if (this.value.equals) {
  29977. check = this.value.equals(this._target[this._property]);
  29978. }
  29979. else {
  29980. check = this.value === this._target[this._property];
  29981. }
  29982. return this.operator === ValueCondition.IsEqual ? check : !check;
  29983. }
  29984. return false;
  29985. };
  29986. // Statics
  29987. ValueCondition._IsEqual = 0;
  29988. ValueCondition._IsDifferent = 1;
  29989. ValueCondition._IsGreater = 2;
  29990. ValueCondition._IsLesser = 3;
  29991. return ValueCondition;
  29992. })(Condition);
  29993. BABYLON.ValueCondition = ValueCondition;
  29994. var PredicateCondition = (function (_super) {
  29995. __extends(PredicateCondition, _super);
  29996. function PredicateCondition(actionManager, predicate) {
  29997. _super.call(this, actionManager);
  29998. this.predicate = predicate;
  29999. }
  30000. PredicateCondition.prototype.isValid = function () {
  30001. return this.predicate();
  30002. };
  30003. return PredicateCondition;
  30004. })(Condition);
  30005. BABYLON.PredicateCondition = PredicateCondition;
  30006. var StateCondition = (function (_super) {
  30007. __extends(StateCondition, _super);
  30008. function StateCondition(actionManager, target, value) {
  30009. _super.call(this, actionManager);
  30010. this.value = value;
  30011. this._target = target;
  30012. }
  30013. // Methods
  30014. StateCondition.prototype.isValid = function () {
  30015. return this._target.state === this.value;
  30016. };
  30017. return StateCondition;
  30018. })(Condition);
  30019. BABYLON.StateCondition = StateCondition;
  30020. })(BABYLON || (BABYLON = {}));
  30021. var BABYLON;
  30022. (function (BABYLON) {
  30023. var Action = (function () {
  30024. function Action(triggerOptions, condition) {
  30025. this.triggerOptions = triggerOptions;
  30026. if (triggerOptions.parameter) {
  30027. this.trigger = triggerOptions.trigger;
  30028. this._triggerParameter = triggerOptions.parameter;
  30029. }
  30030. else {
  30031. this.trigger = triggerOptions;
  30032. }
  30033. this._nextActiveAction = this;
  30034. this._condition = condition;
  30035. }
  30036. // Methods
  30037. Action.prototype._prepare = function () {
  30038. };
  30039. Action.prototype.getTriggerParameter = function () {
  30040. return this._triggerParameter;
  30041. };
  30042. Action.prototype._executeCurrent = function (evt) {
  30043. if (this._nextActiveAction._condition) {
  30044. var condition = this._nextActiveAction._condition;
  30045. var currentRenderId = this._actionManager.getScene().getRenderId();
  30046. // We cache the current evaluation for the current frame
  30047. if (condition._evaluationId === currentRenderId) {
  30048. if (!condition._currentResult) {
  30049. return;
  30050. }
  30051. }
  30052. else {
  30053. condition._evaluationId = currentRenderId;
  30054. if (!condition.isValid()) {
  30055. condition._currentResult = false;
  30056. return;
  30057. }
  30058. condition._currentResult = true;
  30059. }
  30060. }
  30061. this._nextActiveAction.execute(evt);
  30062. this.skipToNextActiveAction();
  30063. };
  30064. Action.prototype.execute = function (evt) {
  30065. };
  30066. Action.prototype.skipToNextActiveAction = function () {
  30067. if (this._nextActiveAction._child) {
  30068. if (!this._nextActiveAction._child._actionManager) {
  30069. this._nextActiveAction._child._actionManager = this._actionManager;
  30070. }
  30071. this._nextActiveAction = this._nextActiveAction._child;
  30072. }
  30073. else {
  30074. this._nextActiveAction = this;
  30075. }
  30076. };
  30077. Action.prototype.then = function (action) {
  30078. this._child = action;
  30079. action._actionManager = this._actionManager;
  30080. action._prepare();
  30081. return action;
  30082. };
  30083. Action.prototype._getProperty = function (propertyPath) {
  30084. return this._actionManager._getProperty(propertyPath);
  30085. };
  30086. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  30087. return this._actionManager._getEffectiveTarget(target, propertyPath);
  30088. };
  30089. return Action;
  30090. })();
  30091. BABYLON.Action = Action;
  30092. })(BABYLON || (BABYLON = {}));
  30093. var BABYLON;
  30094. (function (BABYLON) {
  30095. /**
  30096. * ActionEvent is the event beint sent when an action is triggered.
  30097. */
  30098. var ActionEvent = (function () {
  30099. /**
  30100. * @constructor
  30101. * @param source The mesh or sprite that triggered the action.
  30102. * @param pointerX The X mouse cursor position at the time of the event
  30103. * @param pointerY The Y mouse cursor position at the time of the event
  30104. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  30105. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  30106. */
  30107. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  30108. this.source = source;
  30109. this.pointerX = pointerX;
  30110. this.pointerY = pointerY;
  30111. this.meshUnderPointer = meshUnderPointer;
  30112. this.sourceEvent = sourceEvent;
  30113. this.additionalData = additionalData;
  30114. }
  30115. /**
  30116. * Helper function to auto-create an ActionEvent from a source mesh.
  30117. * @param source The source mesh that triggered the event
  30118. * @param evt {Event} The original (browser) event
  30119. */
  30120. ActionEvent.CreateNew = function (source, evt, additionalData) {
  30121. var scene = source.getScene();
  30122. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  30123. };
  30124. /**
  30125. * Helper function to auto-create an ActionEvent from a source mesh.
  30126. * @param source The source sprite that triggered the event
  30127. * @param scene Scene associated with the sprite
  30128. * @param evt {Event} The original (browser) event
  30129. */
  30130. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  30131. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  30132. };
  30133. /**
  30134. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  30135. * @param scene the scene where the event occurred
  30136. * @param evt {Event} The original (browser) event
  30137. */
  30138. ActionEvent.CreateNewFromScene = function (scene, evt) {
  30139. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  30140. };
  30141. return ActionEvent;
  30142. })();
  30143. BABYLON.ActionEvent = ActionEvent;
  30144. /**
  30145. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  30146. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  30147. */
  30148. var ActionManager = (function () {
  30149. function ActionManager(scene) {
  30150. // Members
  30151. this.actions = new Array();
  30152. this._scene = scene;
  30153. scene._actionManagers.push(this);
  30154. }
  30155. Object.defineProperty(ActionManager, "NothingTrigger", {
  30156. get: function () {
  30157. return ActionManager._NothingTrigger;
  30158. },
  30159. enumerable: true,
  30160. configurable: true
  30161. });
  30162. Object.defineProperty(ActionManager, "OnPickTrigger", {
  30163. get: function () {
  30164. return ActionManager._OnPickTrigger;
  30165. },
  30166. enumerable: true,
  30167. configurable: true
  30168. });
  30169. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  30170. get: function () {
  30171. return ActionManager._OnLeftPickTrigger;
  30172. },
  30173. enumerable: true,
  30174. configurable: true
  30175. });
  30176. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  30177. get: function () {
  30178. return ActionManager._OnRightPickTrigger;
  30179. },
  30180. enumerable: true,
  30181. configurable: true
  30182. });
  30183. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  30184. get: function () {
  30185. return ActionManager._OnCenterPickTrigger;
  30186. },
  30187. enumerable: true,
  30188. configurable: true
  30189. });
  30190. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  30191. get: function () {
  30192. return ActionManager._OnPickDownTrigger;
  30193. },
  30194. enumerable: true,
  30195. configurable: true
  30196. });
  30197. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  30198. get: function () {
  30199. return ActionManager._OnPickUpTrigger;
  30200. },
  30201. enumerable: true,
  30202. configurable: true
  30203. });
  30204. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  30205. /// This trigger will only be raised if you also declared a OnPickDown
  30206. get: function () {
  30207. return ActionManager._OnPickOutTrigger;
  30208. },
  30209. enumerable: true,
  30210. configurable: true
  30211. });
  30212. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  30213. get: function () {
  30214. return ActionManager._OnLongPressTrigger;
  30215. },
  30216. enumerable: true,
  30217. configurable: true
  30218. });
  30219. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  30220. get: function () {
  30221. return ActionManager._OnPointerOverTrigger;
  30222. },
  30223. enumerable: true,
  30224. configurable: true
  30225. });
  30226. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  30227. get: function () {
  30228. return ActionManager._OnPointerOutTrigger;
  30229. },
  30230. enumerable: true,
  30231. configurable: true
  30232. });
  30233. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  30234. get: function () {
  30235. return ActionManager._OnEveryFrameTrigger;
  30236. },
  30237. enumerable: true,
  30238. configurable: true
  30239. });
  30240. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  30241. get: function () {
  30242. return ActionManager._OnIntersectionEnterTrigger;
  30243. },
  30244. enumerable: true,
  30245. configurable: true
  30246. });
  30247. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  30248. get: function () {
  30249. return ActionManager._OnIntersectionExitTrigger;
  30250. },
  30251. enumerable: true,
  30252. configurable: true
  30253. });
  30254. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  30255. get: function () {
  30256. return ActionManager._OnKeyDownTrigger;
  30257. },
  30258. enumerable: true,
  30259. configurable: true
  30260. });
  30261. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  30262. get: function () {
  30263. return ActionManager._OnKeyUpTrigger;
  30264. },
  30265. enumerable: true,
  30266. configurable: true
  30267. });
  30268. // Methods
  30269. ActionManager.prototype.dispose = function () {
  30270. var index = this._scene._actionManagers.indexOf(this);
  30271. if (index > -1) {
  30272. this._scene._actionManagers.splice(index, 1);
  30273. }
  30274. };
  30275. ActionManager.prototype.getScene = function () {
  30276. return this._scene;
  30277. };
  30278. /**
  30279. * Does this action manager handles actions of any of the given triggers
  30280. * @param {number[]} triggers - the triggers to be tested
  30281. * @return {boolean} whether one (or more) of the triggers is handeled
  30282. */
  30283. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  30284. for (var index = 0; index < this.actions.length; index++) {
  30285. var action = this.actions[index];
  30286. if (triggers.indexOf(action.trigger) > -1) {
  30287. return true;
  30288. }
  30289. }
  30290. return false;
  30291. };
  30292. /**
  30293. * Does this action manager handles actions of a given trigger
  30294. * @param {number} trigger - the trigger to be tested
  30295. * @return {boolean} whether the trigger is handeled
  30296. */
  30297. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  30298. for (var index = 0; index < this.actions.length; index++) {
  30299. var action = this.actions[index];
  30300. if (action.trigger === trigger) {
  30301. return true;
  30302. }
  30303. }
  30304. return false;
  30305. };
  30306. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  30307. /**
  30308. * Does this action manager has pointer triggers
  30309. * @return {boolean} whether or not it has pointer triggers
  30310. */
  30311. get: function () {
  30312. for (var index = 0; index < this.actions.length; index++) {
  30313. var action = this.actions[index];
  30314. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  30315. return true;
  30316. }
  30317. }
  30318. return false;
  30319. },
  30320. enumerable: true,
  30321. configurable: true
  30322. });
  30323. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  30324. /**
  30325. * Does this action manager has pick triggers
  30326. * @return {boolean} whether or not it has pick triggers
  30327. */
  30328. get: function () {
  30329. for (var index = 0; index < this.actions.length; index++) {
  30330. var action = this.actions[index];
  30331. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  30332. return true;
  30333. }
  30334. }
  30335. return false;
  30336. },
  30337. enumerable: true,
  30338. configurable: true
  30339. });
  30340. /**
  30341. * Registers an action to this action manager
  30342. * @param {BABYLON.Action} action - the action to be registered
  30343. * @return {BABYLON.Action} the action amended (prepared) after registration
  30344. */
  30345. ActionManager.prototype.registerAction = function (action) {
  30346. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  30347. if (this.getScene().actionManager !== this) {
  30348. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  30349. return null;
  30350. }
  30351. }
  30352. this.actions.push(action);
  30353. action._actionManager = this;
  30354. action._prepare();
  30355. return action;
  30356. };
  30357. /**
  30358. * Process a specific trigger
  30359. * @param {number} trigger - the trigger to process
  30360. * @param evt {BABYLON.ActionEvent} the event details to be processed
  30361. */
  30362. ActionManager.prototype.processTrigger = function (trigger, evt) {
  30363. for (var index = 0; index < this.actions.length; index++) {
  30364. var action = this.actions[index];
  30365. if (action.trigger === trigger) {
  30366. if (trigger === ActionManager.OnKeyUpTrigger
  30367. || trigger === ActionManager.OnKeyDownTrigger) {
  30368. var parameter = action.getTriggerParameter();
  30369. if (parameter) {
  30370. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  30371. var actualkey = String.fromCharCode(unicode).toLowerCase();
  30372. if (actualkey !== parameter.toLowerCase()) {
  30373. continue;
  30374. }
  30375. }
  30376. }
  30377. action._executeCurrent(evt);
  30378. }
  30379. }
  30380. };
  30381. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  30382. var properties = propertyPath.split(".");
  30383. for (var index = 0; index < properties.length - 1; index++) {
  30384. target = target[properties[index]];
  30385. }
  30386. return target;
  30387. };
  30388. ActionManager.prototype._getProperty = function (propertyPath) {
  30389. var properties = propertyPath.split(".");
  30390. return properties[properties.length - 1];
  30391. };
  30392. ActionManager.Parse = function (parsedActions, object, scene) {
  30393. var actionManager = new BABYLON.ActionManager(scene);
  30394. if (object === null)
  30395. scene.actionManager = actionManager;
  30396. else
  30397. object.actionManager = actionManager;
  30398. // instanciate a new object
  30399. var instanciate = function (name, params) {
  30400. var newInstance = Object.create(BABYLON[name].prototype);
  30401. newInstance.constructor.apply(newInstance, params);
  30402. return newInstance;
  30403. };
  30404. var parseParameter = function (name, value, target, propertyPath) {
  30405. if (propertyPath === null) {
  30406. // String, boolean or float
  30407. var floatValue = parseFloat(value);
  30408. if (value === "true" || value === "false")
  30409. return value === "true";
  30410. else
  30411. return isNaN(floatValue) ? value : floatValue;
  30412. }
  30413. var effectiveTarget = propertyPath.split(".");
  30414. var values = value.split(",");
  30415. // Get effective Target
  30416. for (var i = 0; i < effectiveTarget.length; i++) {
  30417. target = target[effectiveTarget[i]];
  30418. }
  30419. // Return appropriate value with its type
  30420. if (typeof (target) === "boolean")
  30421. return values[0] === "true";
  30422. if (typeof (target) === "string")
  30423. return values[0];
  30424. // Parameters with multiple values such as Vector3 etc.
  30425. var split = new Array();
  30426. for (var i = 0; i < values.length; i++)
  30427. split.push(parseFloat(values[i]));
  30428. if (target instanceof BABYLON.Vector3)
  30429. return BABYLON.Vector3.FromArray(split);
  30430. if (target instanceof BABYLON.Vector4)
  30431. return BABYLON.Vector4.FromArray(split);
  30432. if (target instanceof BABYLON.Color3)
  30433. return BABYLON.Color3.FromArray(split);
  30434. if (target instanceof BABYLON.Color4)
  30435. return BABYLON.Color4.FromArray(split);
  30436. return parseFloat(values[0]);
  30437. };
  30438. // traverse graph per trigger
  30439. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  30440. if (combineArray === void 0) { combineArray = null; }
  30441. if (parsedAction.detached)
  30442. return;
  30443. var parameters = new Array();
  30444. var target = null;
  30445. var propertyPath = null;
  30446. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  30447. // Parameters
  30448. if (parsedAction.type === 2)
  30449. parameters.push(actionManager);
  30450. else
  30451. parameters.push(trigger);
  30452. if (combine) {
  30453. var actions = new Array();
  30454. for (var j = 0; j < parsedAction.combine.length; j++) {
  30455. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  30456. }
  30457. parameters.push(actions);
  30458. }
  30459. else {
  30460. for (var i = 0; i < parsedAction.properties.length; i++) {
  30461. var value = parsedAction.properties[i].value;
  30462. var name = parsedAction.properties[i].name;
  30463. var targetType = parsedAction.properties[i].targetType;
  30464. if (name === "target")
  30465. if (targetType !== null && targetType === "SceneProperties")
  30466. value = target = scene;
  30467. else
  30468. value = target = scene.getNodeByName(value);
  30469. else if (name === "parent")
  30470. value = scene.getNodeByName(value);
  30471. else if (name === "sound")
  30472. value = scene.getSoundByName(value);
  30473. else if (name !== "propertyPath") {
  30474. if (parsedAction.type === 2 && name === "operator")
  30475. value = BABYLON.ValueCondition[value];
  30476. else
  30477. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  30478. }
  30479. else {
  30480. propertyPath = value;
  30481. }
  30482. parameters.push(value);
  30483. }
  30484. }
  30485. if (combineArray === null) {
  30486. parameters.push(condition);
  30487. }
  30488. else {
  30489. parameters.push(null);
  30490. }
  30491. // If interpolate value action
  30492. if (parsedAction.name === "InterpolateValueAction") {
  30493. var param = parameters[parameters.length - 2];
  30494. parameters[parameters.length - 1] = param;
  30495. parameters[parameters.length - 2] = condition;
  30496. }
  30497. // Action or condition(s) and not CombineAction
  30498. var newAction = instanciate(parsedAction.name, parameters);
  30499. if (newAction instanceof BABYLON.Condition && condition !== null) {
  30500. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  30501. if (action)
  30502. action.then(nothing);
  30503. else
  30504. actionManager.registerAction(nothing);
  30505. action = nothing;
  30506. }
  30507. if (combineArray === null) {
  30508. if (newAction instanceof BABYLON.Condition) {
  30509. condition = newAction;
  30510. newAction = action;
  30511. }
  30512. else {
  30513. condition = null;
  30514. if (action)
  30515. action.then(newAction);
  30516. else
  30517. actionManager.registerAction(newAction);
  30518. }
  30519. }
  30520. else {
  30521. combineArray.push(newAction);
  30522. }
  30523. for (var i = 0; i < parsedAction.children.length; i++)
  30524. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  30525. };
  30526. // triggers
  30527. for (var i = 0; i < parsedActions.children.length; i++) {
  30528. var triggerParams;
  30529. var trigger = parsedActions.children[i];
  30530. if (trigger.properties.length > 0) {
  30531. var param = trigger.properties[0].value;
  30532. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  30533. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  30534. }
  30535. else
  30536. triggerParams = BABYLON.ActionManager[trigger.name];
  30537. for (var j = 0; j < trigger.children.length; j++) {
  30538. if (!trigger.detached)
  30539. traverse(trigger.children[j], triggerParams, null, null);
  30540. }
  30541. }
  30542. };
  30543. // Statics
  30544. ActionManager._NothingTrigger = 0;
  30545. ActionManager._OnPickTrigger = 1;
  30546. ActionManager._OnLeftPickTrigger = 2;
  30547. ActionManager._OnRightPickTrigger = 3;
  30548. ActionManager._OnCenterPickTrigger = 4;
  30549. ActionManager._OnPickDownTrigger = 5;
  30550. ActionManager._OnPickUpTrigger = 6;
  30551. ActionManager._OnLongPressTrigger = 7;
  30552. ActionManager._OnPointerOverTrigger = 8;
  30553. ActionManager._OnPointerOutTrigger = 9;
  30554. ActionManager._OnEveryFrameTrigger = 10;
  30555. ActionManager._OnIntersectionEnterTrigger = 11;
  30556. ActionManager._OnIntersectionExitTrigger = 12;
  30557. ActionManager._OnKeyDownTrigger = 13;
  30558. ActionManager._OnKeyUpTrigger = 14;
  30559. ActionManager._OnPickOutTrigger = 15;
  30560. ActionManager.DragMovementThreshold = 10; // in pixels
  30561. ActionManager.LongPressDelay = 500; // in milliseconds
  30562. return ActionManager;
  30563. })();
  30564. BABYLON.ActionManager = ActionManager;
  30565. })(BABYLON || (BABYLON = {}));
  30566. var BABYLON;
  30567. (function (BABYLON) {
  30568. var InterpolateValueAction = (function (_super) {
  30569. __extends(InterpolateValueAction, _super);
  30570. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  30571. if (duration === void 0) { duration = 1000; }
  30572. _super.call(this, triggerOptions, condition);
  30573. this.propertyPath = propertyPath;
  30574. this.value = value;
  30575. this.duration = duration;
  30576. this.stopOtherAnimations = stopOtherAnimations;
  30577. this.onInterpolationDone = onInterpolationDone;
  30578. this._target = target;
  30579. }
  30580. InterpolateValueAction.prototype._prepare = function () {
  30581. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  30582. this._property = this._getProperty(this.propertyPath);
  30583. };
  30584. InterpolateValueAction.prototype.execute = function () {
  30585. var scene = this._actionManager.getScene();
  30586. var keys = [
  30587. {
  30588. frame: 0,
  30589. value: this._target[this._property]
  30590. }, {
  30591. frame: 100,
  30592. value: this.value
  30593. }
  30594. ];
  30595. var dataType;
  30596. if (typeof this.value === "number") {
  30597. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  30598. }
  30599. else if (this.value instanceof BABYLON.Color3) {
  30600. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  30601. }
  30602. else if (this.value instanceof BABYLON.Vector3) {
  30603. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  30604. }
  30605. else if (this.value instanceof BABYLON.Matrix) {
  30606. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  30607. }
  30608. else if (this.value instanceof BABYLON.Quaternion) {
  30609. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  30610. }
  30611. else {
  30612. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  30613. return;
  30614. }
  30615. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  30616. animation.setKeys(keys);
  30617. if (this.stopOtherAnimations) {
  30618. scene.stopAnimation(this._target);
  30619. }
  30620. scene.beginDirectAnimation(this._target, [animation], 0, 100, false, 1, this.onInterpolationDone);
  30621. };
  30622. return InterpolateValueAction;
  30623. })(BABYLON.Action);
  30624. BABYLON.InterpolateValueAction = InterpolateValueAction;
  30625. })(BABYLON || (BABYLON = {}));
  30626. var BABYLON;
  30627. (function (BABYLON) {
  30628. var SwitchBooleanAction = (function (_super) {
  30629. __extends(SwitchBooleanAction, _super);
  30630. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  30631. _super.call(this, triggerOptions, condition);
  30632. this.propertyPath = propertyPath;
  30633. this._target = target;
  30634. }
  30635. SwitchBooleanAction.prototype._prepare = function () {
  30636. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  30637. this._property = this._getProperty(this.propertyPath);
  30638. };
  30639. SwitchBooleanAction.prototype.execute = function () {
  30640. this._target[this._property] = !this._target[this._property];
  30641. };
  30642. return SwitchBooleanAction;
  30643. })(BABYLON.Action);
  30644. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  30645. var SetStateAction = (function (_super) {
  30646. __extends(SetStateAction, _super);
  30647. function SetStateAction(triggerOptions, target, value, condition) {
  30648. _super.call(this, triggerOptions, condition);
  30649. this.value = value;
  30650. this._target = target;
  30651. }
  30652. SetStateAction.prototype.execute = function () {
  30653. this._target.state = this.value;
  30654. };
  30655. return SetStateAction;
  30656. })(BABYLON.Action);
  30657. BABYLON.SetStateAction = SetStateAction;
  30658. var SetValueAction = (function (_super) {
  30659. __extends(SetValueAction, _super);
  30660. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  30661. _super.call(this, triggerOptions, condition);
  30662. this.propertyPath = propertyPath;
  30663. this.value = value;
  30664. this._target = target;
  30665. }
  30666. SetValueAction.prototype._prepare = function () {
  30667. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  30668. this._property = this._getProperty(this.propertyPath);
  30669. };
  30670. SetValueAction.prototype.execute = function () {
  30671. this._target[this._property] = this.value;
  30672. };
  30673. return SetValueAction;
  30674. })(BABYLON.Action);
  30675. BABYLON.SetValueAction = SetValueAction;
  30676. var IncrementValueAction = (function (_super) {
  30677. __extends(IncrementValueAction, _super);
  30678. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  30679. _super.call(this, triggerOptions, condition);
  30680. this.propertyPath = propertyPath;
  30681. this.value = value;
  30682. this._target = target;
  30683. }
  30684. IncrementValueAction.prototype._prepare = function () {
  30685. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  30686. this._property = this._getProperty(this.propertyPath);
  30687. if (typeof this._target[this._property] !== "number") {
  30688. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  30689. }
  30690. };
  30691. IncrementValueAction.prototype.execute = function () {
  30692. this._target[this._property] += this.value;
  30693. };
  30694. return IncrementValueAction;
  30695. })(BABYLON.Action);
  30696. BABYLON.IncrementValueAction = IncrementValueAction;
  30697. var PlayAnimationAction = (function (_super) {
  30698. __extends(PlayAnimationAction, _super);
  30699. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  30700. _super.call(this, triggerOptions, condition);
  30701. this.from = from;
  30702. this.to = to;
  30703. this.loop = loop;
  30704. this._target = target;
  30705. }
  30706. PlayAnimationAction.prototype._prepare = function () {
  30707. };
  30708. PlayAnimationAction.prototype.execute = function () {
  30709. var scene = this._actionManager.getScene();
  30710. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  30711. };
  30712. return PlayAnimationAction;
  30713. })(BABYLON.Action);
  30714. BABYLON.PlayAnimationAction = PlayAnimationAction;
  30715. var StopAnimationAction = (function (_super) {
  30716. __extends(StopAnimationAction, _super);
  30717. function StopAnimationAction(triggerOptions, target, condition) {
  30718. _super.call(this, triggerOptions, condition);
  30719. this._target = target;
  30720. }
  30721. StopAnimationAction.prototype._prepare = function () {
  30722. };
  30723. StopAnimationAction.prototype.execute = function () {
  30724. var scene = this._actionManager.getScene();
  30725. scene.stopAnimation(this._target);
  30726. };
  30727. return StopAnimationAction;
  30728. })(BABYLON.Action);
  30729. BABYLON.StopAnimationAction = StopAnimationAction;
  30730. var DoNothingAction = (function (_super) {
  30731. __extends(DoNothingAction, _super);
  30732. function DoNothingAction(triggerOptions, condition) {
  30733. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  30734. _super.call(this, triggerOptions, condition);
  30735. }
  30736. DoNothingAction.prototype.execute = function () {
  30737. };
  30738. return DoNothingAction;
  30739. })(BABYLON.Action);
  30740. BABYLON.DoNothingAction = DoNothingAction;
  30741. var CombineAction = (function (_super) {
  30742. __extends(CombineAction, _super);
  30743. function CombineAction(triggerOptions, children, condition) {
  30744. _super.call(this, triggerOptions, condition);
  30745. this.children = children;
  30746. }
  30747. CombineAction.prototype._prepare = function () {
  30748. for (var index = 0; index < this.children.length; index++) {
  30749. this.children[index]._actionManager = this._actionManager;
  30750. this.children[index]._prepare();
  30751. }
  30752. };
  30753. CombineAction.prototype.execute = function (evt) {
  30754. for (var index = 0; index < this.children.length; index++) {
  30755. this.children[index].execute(evt);
  30756. }
  30757. };
  30758. return CombineAction;
  30759. })(BABYLON.Action);
  30760. BABYLON.CombineAction = CombineAction;
  30761. var ExecuteCodeAction = (function (_super) {
  30762. __extends(ExecuteCodeAction, _super);
  30763. function ExecuteCodeAction(triggerOptions, func, condition) {
  30764. _super.call(this, triggerOptions, condition);
  30765. this.func = func;
  30766. }
  30767. ExecuteCodeAction.prototype.execute = function (evt) {
  30768. this.func(evt);
  30769. };
  30770. return ExecuteCodeAction;
  30771. })(BABYLON.Action);
  30772. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  30773. var SetParentAction = (function (_super) {
  30774. __extends(SetParentAction, _super);
  30775. function SetParentAction(triggerOptions, target, parent, condition) {
  30776. _super.call(this, triggerOptions, condition);
  30777. this._target = target;
  30778. this._parent = parent;
  30779. }
  30780. SetParentAction.prototype._prepare = function () {
  30781. };
  30782. SetParentAction.prototype.execute = function () {
  30783. if (this._target.parent === this._parent) {
  30784. return;
  30785. }
  30786. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  30787. invertParentWorldMatrix.invert();
  30788. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  30789. this._target.parent = this._parent;
  30790. };
  30791. return SetParentAction;
  30792. })(BABYLON.Action);
  30793. BABYLON.SetParentAction = SetParentAction;
  30794. var PlaySoundAction = (function (_super) {
  30795. __extends(PlaySoundAction, _super);
  30796. function PlaySoundAction(triggerOptions, sound, condition) {
  30797. _super.call(this, triggerOptions, condition);
  30798. this._sound = sound;
  30799. }
  30800. PlaySoundAction.prototype._prepare = function () {
  30801. };
  30802. PlaySoundAction.prototype.execute = function () {
  30803. if (this._sound !== undefined)
  30804. this._sound.play();
  30805. };
  30806. return PlaySoundAction;
  30807. })(BABYLON.Action);
  30808. BABYLON.PlaySoundAction = PlaySoundAction;
  30809. var StopSoundAction = (function (_super) {
  30810. __extends(StopSoundAction, _super);
  30811. function StopSoundAction(triggerOptions, sound, condition) {
  30812. _super.call(this, triggerOptions, condition);
  30813. this._sound = sound;
  30814. }
  30815. StopSoundAction.prototype._prepare = function () {
  30816. };
  30817. StopSoundAction.prototype.execute = function () {
  30818. if (this._sound !== undefined)
  30819. this._sound.stop();
  30820. };
  30821. return StopSoundAction;
  30822. })(BABYLON.Action);
  30823. BABYLON.StopSoundAction = StopSoundAction;
  30824. })(BABYLON || (BABYLON = {}));
  30825. var BABYLON;
  30826. (function (BABYLON) {
  30827. var Geometry = (function () {
  30828. function Geometry(id, scene, vertexData, updatable, mesh) {
  30829. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30830. this._totalVertices = 0;
  30831. this._isDisposed = false;
  30832. this.id = id;
  30833. this._engine = scene.getEngine();
  30834. this._meshes = [];
  30835. this._scene = scene;
  30836. //Init vertex buffer cache
  30837. this._vertexBuffers = {};
  30838. this._indices = [];
  30839. // vertexData
  30840. if (vertexData) {
  30841. this.setAllVerticesData(vertexData, updatable);
  30842. }
  30843. else {
  30844. this._totalVertices = 0;
  30845. this._indices = [];
  30846. }
  30847. // applyToMesh
  30848. if (mesh) {
  30849. if (mesh instanceof BABYLON.LinesMesh) {
  30850. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  30851. this.updateExtend();
  30852. }
  30853. this.applyToMesh(mesh);
  30854. mesh.computeWorldMatrix(true);
  30855. }
  30856. }
  30857. Object.defineProperty(Geometry.prototype, "boundingBias", {
  30858. /**
  30859. * 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
  30860. * @returns The Bias Vector
  30861. */
  30862. get: function () {
  30863. return this._boundingBias;
  30864. },
  30865. set: function (value) {
  30866. if (this._boundingBias && this._boundingBias.equals(value)) {
  30867. return;
  30868. }
  30869. this._boundingBias = value.clone();
  30870. this.updateBoundingInfo(true, null);
  30871. },
  30872. enumerable: true,
  30873. configurable: true
  30874. });
  30875. Object.defineProperty(Geometry.prototype, "extend", {
  30876. get: function () {
  30877. return this._extend;
  30878. },
  30879. enumerable: true,
  30880. configurable: true
  30881. });
  30882. Geometry.prototype.getScene = function () {
  30883. return this._scene;
  30884. };
  30885. Geometry.prototype.getEngine = function () {
  30886. return this._engine;
  30887. };
  30888. Geometry.prototype.isReady = function () {
  30889. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  30890. };
  30891. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  30892. vertexData.applyToGeometry(this, updatable);
  30893. this.notifyUpdate();
  30894. };
  30895. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  30896. if (this._vertexBuffers[kind]) {
  30897. this._vertexBuffers[kind].dispose();
  30898. }
  30899. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  30900. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30901. stride = this._vertexBuffers[kind].getStrideSize();
  30902. this._totalVertices = data.length / stride;
  30903. this.updateExtend(data);
  30904. var meshes = this._meshes;
  30905. var numOfMeshes = meshes.length;
  30906. for (var index = 0; index < numOfMeshes; index++) {
  30907. var mesh = meshes[index];
  30908. mesh._resetPointsArrayCache();
  30909. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30910. mesh._createGlobalSubMesh();
  30911. mesh.computeWorldMatrix(true);
  30912. }
  30913. }
  30914. this.notifyUpdate(kind);
  30915. };
  30916. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  30917. var vertexBuffer = this.getVertexBuffer(kind);
  30918. if (!vertexBuffer) {
  30919. return;
  30920. }
  30921. vertexBuffer.updateDirectly(data, offset);
  30922. this.notifyUpdate(kind);
  30923. };
  30924. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  30925. var vertexBuffer = this.getVertexBuffer(kind);
  30926. if (!vertexBuffer) {
  30927. return;
  30928. }
  30929. vertexBuffer.update(data);
  30930. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30931. var stride = vertexBuffer.getStrideSize();
  30932. this._totalVertices = data.length / stride;
  30933. this.updateBoundingInfo(updateExtends, data);
  30934. }
  30935. this.notifyUpdate(kind);
  30936. };
  30937. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  30938. if (updateExtends) {
  30939. this.updateExtend(data);
  30940. }
  30941. var meshes = this._meshes;
  30942. var numOfMeshes = meshes.length;
  30943. for (var index = 0; index < numOfMeshes; index++) {
  30944. var mesh = meshes[index];
  30945. mesh._resetPointsArrayCache();
  30946. if (updateExtends) {
  30947. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30948. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30949. var subMesh = mesh.subMeshes[subIndex];
  30950. subMesh.refreshBoundingInfo();
  30951. }
  30952. }
  30953. }
  30954. };
  30955. Geometry.prototype.getTotalVertices = function () {
  30956. if (!this.isReady()) {
  30957. return 0;
  30958. }
  30959. return this._totalVertices;
  30960. };
  30961. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  30962. var vertexBuffer = this.getVertexBuffer(kind);
  30963. if (!vertexBuffer) {
  30964. return null;
  30965. }
  30966. var orig = vertexBuffer.getData();
  30967. if (!copyWhenShared || this._meshes.length === 1) {
  30968. return orig;
  30969. }
  30970. else {
  30971. var len = orig.length;
  30972. var copy = [];
  30973. for (var i = 0; i < len; i++) {
  30974. copy.push(orig[i]);
  30975. }
  30976. return copy;
  30977. }
  30978. };
  30979. Geometry.prototype.getVertexBuffer = function (kind) {
  30980. if (!this.isReady()) {
  30981. return null;
  30982. }
  30983. return this._vertexBuffers[kind];
  30984. };
  30985. Geometry.prototype.getVertexBuffers = function () {
  30986. if (!this.isReady()) {
  30987. return null;
  30988. }
  30989. return this._vertexBuffers;
  30990. };
  30991. Geometry.prototype.isVerticesDataPresent = function (kind) {
  30992. if (!this._vertexBuffers) {
  30993. if (this._delayInfo) {
  30994. return this._delayInfo.indexOf(kind) !== -1;
  30995. }
  30996. return false;
  30997. }
  30998. return this._vertexBuffers[kind] !== undefined;
  30999. };
  31000. Geometry.prototype.getVerticesDataKinds = function () {
  31001. var result = [];
  31002. var kind;
  31003. if (!this._vertexBuffers && this._delayInfo) {
  31004. for (kind in this._delayInfo) {
  31005. result.push(kind);
  31006. }
  31007. }
  31008. else {
  31009. for (kind in this._vertexBuffers) {
  31010. result.push(kind);
  31011. }
  31012. }
  31013. return result;
  31014. };
  31015. Geometry.prototype.setIndices = function (indices, totalVertices) {
  31016. if (this._indexBuffer) {
  31017. this._engine._releaseBuffer(this._indexBuffer);
  31018. }
  31019. this._indices = indices;
  31020. if (this._meshes.length !== 0 && this._indices) {
  31021. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31022. }
  31023. if (totalVertices !== undefined) {
  31024. this._totalVertices = totalVertices;
  31025. }
  31026. var meshes = this._meshes;
  31027. var numOfMeshes = meshes.length;
  31028. for (var index = 0; index < numOfMeshes; index++) {
  31029. meshes[index]._createGlobalSubMesh();
  31030. }
  31031. this.notifyUpdate();
  31032. };
  31033. Geometry.prototype.getTotalIndices = function () {
  31034. if (!this.isReady()) {
  31035. return 0;
  31036. }
  31037. return this._indices.length;
  31038. };
  31039. Geometry.prototype.getIndices = function (copyWhenShared) {
  31040. if (!this.isReady()) {
  31041. return null;
  31042. }
  31043. var orig = this._indices;
  31044. if (!copyWhenShared || this._meshes.length === 1) {
  31045. return orig;
  31046. }
  31047. else {
  31048. var len = orig.length;
  31049. var copy = [];
  31050. for (var i = 0; i < len; i++) {
  31051. copy.push(orig[i]);
  31052. }
  31053. return copy;
  31054. }
  31055. };
  31056. Geometry.prototype.getIndexBuffer = function () {
  31057. if (!this.isReady()) {
  31058. return null;
  31059. }
  31060. return this._indexBuffer;
  31061. };
  31062. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31063. var meshes = this._meshes;
  31064. var index = meshes.indexOf(mesh);
  31065. if (index === -1) {
  31066. return;
  31067. }
  31068. for (var kind in this._vertexBuffers) {
  31069. this._vertexBuffers[kind].dispose();
  31070. }
  31071. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  31072. this._indexBuffer = null;
  31073. }
  31074. meshes.splice(index, 1);
  31075. mesh._geometry = null;
  31076. if (meshes.length === 0 && shouldDispose) {
  31077. this.dispose();
  31078. }
  31079. };
  31080. Geometry.prototype.applyToMesh = function (mesh) {
  31081. if (mesh._geometry === this) {
  31082. return;
  31083. }
  31084. var previousGeometry = mesh._geometry;
  31085. if (previousGeometry) {
  31086. previousGeometry.releaseForMesh(mesh);
  31087. }
  31088. var meshes = this._meshes;
  31089. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31090. mesh._geometry = this;
  31091. this._scene.pushGeometry(this);
  31092. meshes.push(mesh);
  31093. if (this.isReady()) {
  31094. this._applyToMesh(mesh);
  31095. }
  31096. else {
  31097. mesh._boundingInfo = this._boundingInfo;
  31098. }
  31099. };
  31100. Geometry.prototype.updateExtend = function (data) {
  31101. if (data === void 0) { data = null; }
  31102. if (!data) {
  31103. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31104. }
  31105. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias);
  31106. };
  31107. Geometry.prototype._applyToMesh = function (mesh) {
  31108. var numOfMeshes = this._meshes.length;
  31109. // vertexBuffers
  31110. for (var kind in this._vertexBuffers) {
  31111. if (numOfMeshes === 1) {
  31112. this._vertexBuffers[kind].create();
  31113. }
  31114. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  31115. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31116. mesh._resetPointsArrayCache();
  31117. if (!this._extend) {
  31118. this.updateExtend(this._vertexBuffers[kind].getData());
  31119. }
  31120. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31121. mesh._createGlobalSubMesh();
  31122. //bounding info was just created again, world matrix should be applied again.
  31123. mesh._updateBoundingInfo();
  31124. }
  31125. }
  31126. // indexBuffer
  31127. if (numOfMeshes === 1 && this._indices) {
  31128. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31129. }
  31130. if (this._indexBuffer) {
  31131. this._indexBuffer.references = numOfMeshes;
  31132. }
  31133. };
  31134. Geometry.prototype.notifyUpdate = function (kind) {
  31135. if (this.onGeometryUpdated) {
  31136. this.onGeometryUpdated(this, kind);
  31137. }
  31138. };
  31139. Geometry.prototype.load = function (scene, onLoaded) {
  31140. var _this = this;
  31141. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31142. return;
  31143. }
  31144. if (this.isReady()) {
  31145. if (onLoaded) {
  31146. onLoaded();
  31147. }
  31148. return;
  31149. }
  31150. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31151. scene._addPendingData(this);
  31152. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31153. _this._delayLoadingFunction(JSON.parse(data), _this);
  31154. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31155. _this._delayInfo = [];
  31156. scene._removePendingData(_this);
  31157. var meshes = _this._meshes;
  31158. var numOfMeshes = meshes.length;
  31159. for (var index = 0; index < numOfMeshes; index++) {
  31160. _this._applyToMesh(meshes[index]);
  31161. }
  31162. if (onLoaded) {
  31163. onLoaded();
  31164. }
  31165. }, function () { }, scene.database);
  31166. };
  31167. Geometry.prototype.isDisposed = function () {
  31168. return this._isDisposed;
  31169. };
  31170. Geometry.prototype.dispose = function () {
  31171. var meshes = this._meshes;
  31172. var numOfMeshes = meshes.length;
  31173. var index;
  31174. for (index = 0; index < numOfMeshes; index++) {
  31175. this.releaseForMesh(meshes[index]);
  31176. }
  31177. this._meshes = [];
  31178. for (var kind in this._vertexBuffers) {
  31179. this._vertexBuffers[kind].dispose();
  31180. }
  31181. this._vertexBuffers = [];
  31182. this._totalVertices = 0;
  31183. if (this._indexBuffer) {
  31184. this._engine._releaseBuffer(this._indexBuffer);
  31185. }
  31186. this._indexBuffer = null;
  31187. this._indices = [];
  31188. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31189. this.delayLoadingFile = null;
  31190. this._delayLoadingFunction = null;
  31191. this._delayInfo = [];
  31192. this._boundingInfo = null;
  31193. this._scene.removeGeometry(this);
  31194. this._isDisposed = true;
  31195. };
  31196. Geometry.prototype.copy = function (id) {
  31197. var vertexData = new BABYLON.VertexData();
  31198. vertexData.indices = [];
  31199. var indices = this.getIndices();
  31200. for (var index = 0; index < indices.length; index++) {
  31201. vertexData.indices.push(indices[index]);
  31202. }
  31203. var updatable = false;
  31204. var stopChecking = false;
  31205. var kind;
  31206. for (kind in this._vertexBuffers) {
  31207. // using slice() to make a copy of the array and not just reference it
  31208. var data = this.getVerticesData(kind);
  31209. if (data instanceof Float32Array) {
  31210. vertexData.set(new Float32Array(data), kind);
  31211. }
  31212. else {
  31213. vertexData.set(data.slice(0), kind);
  31214. }
  31215. if (!stopChecking) {
  31216. updatable = this.getVertexBuffer(kind).isUpdatable();
  31217. stopChecking = !updatable;
  31218. }
  31219. }
  31220. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  31221. geometry.delayLoadState = this.delayLoadState;
  31222. geometry.delayLoadingFile = this.delayLoadingFile;
  31223. geometry._delayLoadingFunction = this._delayLoadingFunction;
  31224. for (kind in this._delayInfo) {
  31225. geometry._delayInfo = geometry._delayInfo || [];
  31226. geometry._delayInfo.push(kind);
  31227. }
  31228. // Bounding info
  31229. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31230. return geometry;
  31231. };
  31232. Geometry.prototype.serialize = function () {
  31233. var serializationObject = {};
  31234. serializationObject.id = this.id;
  31235. if (BABYLON.Tags.HasTags(this)) {
  31236. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31237. }
  31238. return serializationObject;
  31239. };
  31240. Geometry.prototype.serializeVerticeData = function () {
  31241. var serializationObject = this.serialize();
  31242. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31243. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31244. }
  31245. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31246. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31247. }
  31248. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31249. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  31250. }
  31251. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31252. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  31253. }
  31254. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31255. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  31256. }
  31257. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31258. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  31259. }
  31260. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31261. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  31262. }
  31263. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31264. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  31265. }
  31266. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31267. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  31268. }
  31269. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31270. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31271. serializationObject.matricesIndices._isExpanded = true;
  31272. }
  31273. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31274. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31275. }
  31276. serializationObject.indices = this.getIndices();
  31277. return serializationObject;
  31278. };
  31279. // Statics
  31280. Geometry.ExtractFromMesh = function (mesh, id) {
  31281. var geometry = mesh._geometry;
  31282. if (!geometry) {
  31283. return null;
  31284. }
  31285. return geometry.copy(id);
  31286. };
  31287. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  31288. // be aware Math.random() could cause collisions
  31289. Geometry.RandomId = function () {
  31290. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  31291. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  31292. return v.toString(16);
  31293. });
  31294. };
  31295. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  31296. var scene = mesh.getScene();
  31297. // Geometry
  31298. var geometryId = parsedGeometry.geometryId;
  31299. if (geometryId) {
  31300. var geometry = scene.getGeometryByID(geometryId);
  31301. if (geometry) {
  31302. geometry.applyToMesh(mesh);
  31303. }
  31304. }
  31305. else if (parsedGeometry instanceof ArrayBuffer) {
  31306. var binaryInfo = mesh._binaryInfo;
  31307. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  31308. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  31309. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  31310. }
  31311. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  31312. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  31313. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  31314. }
  31315. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  31316. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  31317. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  31318. }
  31319. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  31320. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  31321. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  31322. }
  31323. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  31324. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  31325. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  31326. }
  31327. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  31328. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  31329. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  31330. }
  31331. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  31332. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  31333. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  31334. }
  31335. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  31336. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  31337. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  31338. }
  31339. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  31340. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  31341. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  31342. }
  31343. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  31344. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  31345. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  31346. }
  31347. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  31348. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  31349. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  31350. }
  31351. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31352. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31353. mesh.setIndices(indicesData);
  31354. }
  31355. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31356. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31357. mesh.subMeshes = [];
  31358. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31359. var materialIndex = subMeshesData[(i * 5) + 0];
  31360. var verticesStart = subMeshesData[(i * 5) + 1];
  31361. var verticesCount = subMeshesData[(i * 5) + 2];
  31362. var indexStart = subMeshesData[(i * 5) + 3];
  31363. var indexCount = subMeshesData[(i * 5) + 4];
  31364. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31365. }
  31366. }
  31367. }
  31368. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31369. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  31370. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  31371. if (parsedGeometry.uvs) {
  31372. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  31373. }
  31374. if (parsedGeometry.uvs2) {
  31375. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  31376. }
  31377. if (parsedGeometry.uvs3) {
  31378. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  31379. }
  31380. if (parsedGeometry.uvs4) {
  31381. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  31382. }
  31383. if (parsedGeometry.uvs5) {
  31384. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  31385. }
  31386. if (parsedGeometry.uvs6) {
  31387. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  31388. }
  31389. if (parsedGeometry.colors) {
  31390. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  31391. }
  31392. if (parsedGeometry.matricesIndices) {
  31393. if (!parsedGeometry.matricesIndices._isExpanded) {
  31394. var floatIndices = [];
  31395. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  31396. var matricesIndex = parsedGeometry.matricesIndices[i];
  31397. floatIndices.push(matricesIndex & 0x000000FF);
  31398. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31399. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31400. floatIndices.push(matricesIndex >> 24);
  31401. }
  31402. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  31403. }
  31404. else {
  31405. delete parsedGeometry.matricesIndices._isExpanded;
  31406. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  31407. }
  31408. }
  31409. if (parsedGeometry.matricesIndicesExtra) {
  31410. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  31411. var floatIndices = [];
  31412. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  31413. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  31414. floatIndices.push(matricesIndex & 0x000000FF);
  31415. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31416. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31417. floatIndices.push(matricesIndex >> 24);
  31418. }
  31419. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  31420. }
  31421. else {
  31422. delete parsedGeometry.matricesIndices._isExpanded;
  31423. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  31424. }
  31425. }
  31426. if (parsedGeometry.matricesWeights) {
  31427. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  31428. }
  31429. if (parsedGeometry.matricesWeightsExtra) {
  31430. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  31431. }
  31432. mesh.setIndices(parsedGeometry.indices);
  31433. }
  31434. // SubMeshes
  31435. if (parsedGeometry.subMeshes) {
  31436. mesh.subMeshes = [];
  31437. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  31438. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  31439. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  31440. }
  31441. }
  31442. // Flat shading
  31443. if (mesh._shouldGenerateFlatShading) {
  31444. mesh.convertToFlatShadedMesh();
  31445. delete mesh._shouldGenerateFlatShading;
  31446. }
  31447. // Update
  31448. mesh.computeWorldMatrix(true);
  31449. // Octree
  31450. if (scene['_selectionOctree']) {
  31451. scene['_selectionOctree'].addMesh(mesh);
  31452. }
  31453. };
  31454. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  31455. if (scene.getGeometryByID(parsedVertexData.id)) {
  31456. return null; // null since geometry could be something else than a box...
  31457. }
  31458. var geometry = new Geometry(parsedVertexData.id, scene);
  31459. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  31460. if (parsedVertexData.delayLoadingFile) {
  31461. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31462. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  31463. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  31464. geometry._delayInfo = [];
  31465. if (parsedVertexData.hasUVs) {
  31466. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  31467. }
  31468. if (parsedVertexData.hasUVs2) {
  31469. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  31470. }
  31471. if (parsedVertexData.hasUVs3) {
  31472. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  31473. }
  31474. if (parsedVertexData.hasUVs4) {
  31475. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  31476. }
  31477. if (parsedVertexData.hasUVs5) {
  31478. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  31479. }
  31480. if (parsedVertexData.hasUVs6) {
  31481. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  31482. }
  31483. if (parsedVertexData.hasColors) {
  31484. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  31485. }
  31486. if (parsedVertexData.hasMatricesIndices) {
  31487. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31488. }
  31489. if (parsedVertexData.hasMatricesWeights) {
  31490. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31491. }
  31492. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  31493. }
  31494. else {
  31495. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  31496. }
  31497. scene.pushGeometry(geometry, true);
  31498. return geometry;
  31499. };
  31500. return Geometry;
  31501. })();
  31502. BABYLON.Geometry = Geometry;
  31503. /////// Primitives //////////////////////////////////////////////
  31504. var Geometry;
  31505. (function (Geometry) {
  31506. var Primitives;
  31507. (function (Primitives) {
  31508. /// Abstract class
  31509. var _Primitive = (function (_super) {
  31510. __extends(_Primitive, _super);
  31511. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  31512. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  31513. this._canBeRegenerated = _canBeRegenerated;
  31514. this._beingRegenerated = true;
  31515. this.regenerate();
  31516. this._beingRegenerated = false;
  31517. }
  31518. _Primitive.prototype.canBeRegenerated = function () {
  31519. return this._canBeRegenerated;
  31520. };
  31521. _Primitive.prototype.regenerate = function () {
  31522. if (!this._canBeRegenerated) {
  31523. return;
  31524. }
  31525. this._beingRegenerated = true;
  31526. this.setAllVerticesData(this._regenerateVertexData(), false);
  31527. this._beingRegenerated = false;
  31528. };
  31529. _Primitive.prototype.asNewGeometry = function (id) {
  31530. return _super.prototype.copy.call(this, id);
  31531. };
  31532. // overrides
  31533. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  31534. if (!this._beingRegenerated) {
  31535. return;
  31536. }
  31537. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  31538. };
  31539. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  31540. if (!this._beingRegenerated) {
  31541. return;
  31542. }
  31543. _super.prototype.setVerticesData.call(this, kind, data, false);
  31544. };
  31545. // to override
  31546. // protected
  31547. _Primitive.prototype._regenerateVertexData = function () {
  31548. throw new Error("Abstract method");
  31549. };
  31550. _Primitive.prototype.copy = function (id) {
  31551. throw new Error("Must be overriden in sub-classes.");
  31552. };
  31553. _Primitive.prototype.serialize = function () {
  31554. var serializationObject = _super.prototype.serialize.call(this);
  31555. serializationObject.canBeRegenerated = this.canBeRegenerated();
  31556. return serializationObject;
  31557. };
  31558. return _Primitive;
  31559. })(Geometry);
  31560. Primitives._Primitive = _Primitive;
  31561. var Ribbon = (function (_super) {
  31562. __extends(Ribbon, _super);
  31563. // Members
  31564. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  31565. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31566. _super.call(this, id, scene, canBeRegenerated, mesh);
  31567. this.pathArray = pathArray;
  31568. this.closeArray = closeArray;
  31569. this.closePath = closePath;
  31570. this.offset = offset;
  31571. this.side = side;
  31572. }
  31573. Ribbon.prototype._regenerateVertexData = function () {
  31574. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  31575. };
  31576. Ribbon.prototype.copy = function (id) {
  31577. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  31578. };
  31579. return Ribbon;
  31580. })(_Primitive);
  31581. Primitives.Ribbon = Ribbon;
  31582. var Box = (function (_super) {
  31583. __extends(Box, _super);
  31584. // Members
  31585. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  31586. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31587. _super.call(this, id, scene, canBeRegenerated, mesh);
  31588. this.size = size;
  31589. this.side = side;
  31590. }
  31591. Box.prototype._regenerateVertexData = function () {
  31592. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  31593. };
  31594. Box.prototype.copy = function (id) {
  31595. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  31596. };
  31597. Box.prototype.serialize = function () {
  31598. var serializationObject = _super.prototype.serialize.call(this);
  31599. serializationObject.size = this.size;
  31600. return serializationObject;
  31601. };
  31602. Box.Parse = function (parsedBox, scene) {
  31603. if (scene.getGeometryByID(parsedBox.id)) {
  31604. return null; // null since geometry could be something else than a box...
  31605. }
  31606. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  31607. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  31608. scene.pushGeometry(box, true);
  31609. return box;
  31610. };
  31611. return Box;
  31612. })(_Primitive);
  31613. Primitives.Box = Box;
  31614. var Sphere = (function (_super) {
  31615. __extends(Sphere, _super);
  31616. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  31617. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31618. _super.call(this, id, scene, canBeRegenerated, mesh);
  31619. this.segments = segments;
  31620. this.diameter = diameter;
  31621. this.side = side;
  31622. }
  31623. Sphere.prototype._regenerateVertexData = function () {
  31624. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  31625. };
  31626. Sphere.prototype.copy = function (id) {
  31627. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  31628. };
  31629. Sphere.prototype.serialize = function () {
  31630. var serializationObject = _super.prototype.serialize.call(this);
  31631. serializationObject.segments = this.segments;
  31632. serializationObject.diameter = this.diameter;
  31633. return serializationObject;
  31634. };
  31635. Sphere.Parse = function (parsedSphere, scene) {
  31636. if (scene.getGeometryByID(parsedSphere.id)) {
  31637. return null; // null since geometry could be something else than a sphere...
  31638. }
  31639. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  31640. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  31641. scene.pushGeometry(sphere, true);
  31642. return sphere;
  31643. };
  31644. return Sphere;
  31645. })(_Primitive);
  31646. Primitives.Sphere = Sphere;
  31647. var Disc = (function (_super) {
  31648. __extends(Disc, _super);
  31649. // Members
  31650. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  31651. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31652. _super.call(this, id, scene, canBeRegenerated, mesh);
  31653. this.radius = radius;
  31654. this.tessellation = tessellation;
  31655. this.side = side;
  31656. }
  31657. Disc.prototype._regenerateVertexData = function () {
  31658. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  31659. };
  31660. Disc.prototype.copy = function (id) {
  31661. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  31662. };
  31663. return Disc;
  31664. })(_Primitive);
  31665. Primitives.Disc = Disc;
  31666. var Cylinder = (function (_super) {
  31667. __extends(Cylinder, _super);
  31668. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  31669. if (subdivisions === void 0) { subdivisions = 1; }
  31670. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31671. _super.call(this, id, scene, canBeRegenerated, mesh);
  31672. this.height = height;
  31673. this.diameterTop = diameterTop;
  31674. this.diameterBottom = diameterBottom;
  31675. this.tessellation = tessellation;
  31676. this.subdivisions = subdivisions;
  31677. this.side = side;
  31678. }
  31679. Cylinder.prototype._regenerateVertexData = function () {
  31680. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  31681. };
  31682. Cylinder.prototype.copy = function (id) {
  31683. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  31684. };
  31685. Cylinder.prototype.serialize = function () {
  31686. var serializationObject = _super.prototype.serialize.call(this);
  31687. serializationObject.height = this.height;
  31688. serializationObject.diameterTop = this.diameterTop;
  31689. serializationObject.diameterBottom = this.diameterBottom;
  31690. serializationObject.tessellation = this.tessellation;
  31691. return serializationObject;
  31692. };
  31693. Cylinder.Parse = function (parsedCylinder, scene) {
  31694. if (scene.getGeometryByID(parsedCylinder.id)) {
  31695. return null; // null since geometry could be something else than a cylinder...
  31696. }
  31697. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  31698. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  31699. scene.pushGeometry(cylinder, true);
  31700. return cylinder;
  31701. };
  31702. return Cylinder;
  31703. })(_Primitive);
  31704. Primitives.Cylinder = Cylinder;
  31705. var Torus = (function (_super) {
  31706. __extends(Torus, _super);
  31707. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  31708. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31709. _super.call(this, id, scene, canBeRegenerated, mesh);
  31710. this.diameter = diameter;
  31711. this.thickness = thickness;
  31712. this.tessellation = tessellation;
  31713. this.side = side;
  31714. }
  31715. Torus.prototype._regenerateVertexData = function () {
  31716. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  31717. };
  31718. Torus.prototype.copy = function (id) {
  31719. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  31720. };
  31721. Torus.prototype.serialize = function () {
  31722. var serializationObject = _super.prototype.serialize.call(this);
  31723. serializationObject.diameter = this.diameter;
  31724. serializationObject.thickness = this.thickness;
  31725. serializationObject.tessellation = this.tessellation;
  31726. return serializationObject;
  31727. };
  31728. Torus.Parse = function (parsedTorus, scene) {
  31729. if (scene.getGeometryByID(parsedTorus.id)) {
  31730. return null; // null since geometry could be something else than a torus...
  31731. }
  31732. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  31733. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  31734. scene.pushGeometry(torus, true);
  31735. return torus;
  31736. };
  31737. return Torus;
  31738. })(_Primitive);
  31739. Primitives.Torus = Torus;
  31740. var Ground = (function (_super) {
  31741. __extends(Ground, _super);
  31742. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  31743. _super.call(this, id, scene, canBeRegenerated, mesh);
  31744. this.width = width;
  31745. this.height = height;
  31746. this.subdivisions = subdivisions;
  31747. }
  31748. Ground.prototype._regenerateVertexData = function () {
  31749. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  31750. };
  31751. Ground.prototype.copy = function (id) {
  31752. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  31753. };
  31754. Ground.prototype.serialize = function () {
  31755. var serializationObject = _super.prototype.serialize.call(this);
  31756. serializationObject.width = this.width;
  31757. serializationObject.height = this.height;
  31758. serializationObject.subdivisions = this.subdivisions;
  31759. return serializationObject;
  31760. };
  31761. Ground.Parse = function (parsedGround, scene) {
  31762. if (scene.getGeometryByID(parsedGround.id)) {
  31763. return null; // null since geometry could be something else than a ground...
  31764. }
  31765. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  31766. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  31767. scene.pushGeometry(ground, true);
  31768. return ground;
  31769. };
  31770. return Ground;
  31771. })(_Primitive);
  31772. Primitives.Ground = Ground;
  31773. var TiledGround = (function (_super) {
  31774. __extends(TiledGround, _super);
  31775. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  31776. _super.call(this, id, scene, canBeRegenerated, mesh);
  31777. this.xmin = xmin;
  31778. this.zmin = zmin;
  31779. this.xmax = xmax;
  31780. this.zmax = zmax;
  31781. this.subdivisions = subdivisions;
  31782. this.precision = precision;
  31783. }
  31784. TiledGround.prototype._regenerateVertexData = function () {
  31785. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  31786. };
  31787. TiledGround.prototype.copy = function (id) {
  31788. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  31789. };
  31790. return TiledGround;
  31791. })(_Primitive);
  31792. Primitives.TiledGround = TiledGround;
  31793. var Plane = (function (_super) {
  31794. __extends(Plane, _super);
  31795. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  31796. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31797. _super.call(this, id, scene, canBeRegenerated, mesh);
  31798. this.size = size;
  31799. this.side = side;
  31800. }
  31801. Plane.prototype._regenerateVertexData = function () {
  31802. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  31803. };
  31804. Plane.prototype.copy = function (id) {
  31805. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  31806. };
  31807. Plane.prototype.serialize = function () {
  31808. var serializationObject = _super.prototype.serialize.call(this);
  31809. serializationObject.size = this.size;
  31810. return serializationObject;
  31811. };
  31812. Plane.Parse = function (parsedPlane, scene) {
  31813. if (scene.getGeometryByID(parsedPlane.id)) {
  31814. return null; // null since geometry could be something else than a ground...
  31815. }
  31816. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  31817. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  31818. scene.pushGeometry(plane, true);
  31819. return plane;
  31820. };
  31821. return Plane;
  31822. })(_Primitive);
  31823. Primitives.Plane = Plane;
  31824. var TorusKnot = (function (_super) {
  31825. __extends(TorusKnot, _super);
  31826. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  31827. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31828. _super.call(this, id, scene, canBeRegenerated, mesh);
  31829. this.radius = radius;
  31830. this.tube = tube;
  31831. this.radialSegments = radialSegments;
  31832. this.tubularSegments = tubularSegments;
  31833. this.p = p;
  31834. this.q = q;
  31835. this.side = side;
  31836. }
  31837. TorusKnot.prototype._regenerateVertexData = function () {
  31838. 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 });
  31839. };
  31840. TorusKnot.prototype.copy = function (id) {
  31841. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  31842. };
  31843. TorusKnot.prototype.serialize = function () {
  31844. var serializationObject = _super.prototype.serialize.call(this);
  31845. serializationObject.radius = this.radius;
  31846. serializationObject.tube = this.tube;
  31847. serializationObject.radialSegments = this.radialSegments;
  31848. serializationObject.tubularSegments = this.tubularSegments;
  31849. serializationObject.p = this.p;
  31850. serializationObject.q = this.q;
  31851. return serializationObject;
  31852. };
  31853. ;
  31854. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  31855. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  31856. return null; // null since geometry could be something else than a ground...
  31857. }
  31858. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  31859. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  31860. scene.pushGeometry(torusKnot, true);
  31861. return torusKnot;
  31862. };
  31863. return TorusKnot;
  31864. })(_Primitive);
  31865. Primitives.TorusKnot = TorusKnot;
  31866. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  31867. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  31868. })(BABYLON || (BABYLON = {}));
  31869. var BABYLON;
  31870. (function (BABYLON) {
  31871. var GroundMesh = (function (_super) {
  31872. __extends(GroundMesh, _super);
  31873. function GroundMesh(name, scene) {
  31874. _super.call(this, name, scene);
  31875. this.generateOctree = false;
  31876. this._worldInverse = new BABYLON.Matrix();
  31877. }
  31878. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  31879. get: function () {
  31880. return this._subdivisions;
  31881. },
  31882. enumerable: true,
  31883. configurable: true
  31884. });
  31885. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  31886. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  31887. this._subdivisions = chunksCount;
  31888. this.subdivide(this._subdivisions);
  31889. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  31890. };
  31891. /**
  31892. * Returns a height (y) value in the Worl system :
  31893. * the ground altitude at the coordinates (x, z) expressed in the World system.
  31894. * Returns the ground y position if (x, z) are outside the ground surface.
  31895. * Not pertinent if the ground is rotated.
  31896. */
  31897. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  31898. // express x and y in the ground local system
  31899. x -= this.position.x;
  31900. z -= this.position.z;
  31901. x /= this.scaling.x;
  31902. z /= this.scaling.z;
  31903. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  31904. return this.position.y;
  31905. }
  31906. if (!this._heightQuads || this._heightQuads.length == 0) {
  31907. this._initHeightQuads();
  31908. this._computeHeightQuads();
  31909. }
  31910. var facet = this._getFacetAt(x, z);
  31911. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  31912. // return y in the World system
  31913. return y * this.scaling.y + this.position.y;
  31914. };
  31915. /**
  31916. * Returns a normalized vector (Vector3) orthogonal to the ground
  31917. * at the ground coordinates (x, z) expressed in the World system.
  31918. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  31919. * Not pertinent if the ground is rotated.
  31920. */
  31921. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  31922. var normal = new BABYLON.Vector3(0, 1, 0);
  31923. this.getNormalAtCoordinatesToRef(x, z, normal);
  31924. return normal;
  31925. };
  31926. /**
  31927. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  31928. * at the ground coordinates (x, z) expressed in the World system.
  31929. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  31930. * Not pertinent if the ground is rotated.
  31931. */
  31932. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  31933. // express x and y in the ground local system
  31934. x -= this.position.x;
  31935. z -= this.position.z;
  31936. x /= this.scaling.x;
  31937. z /= this.scaling.z;
  31938. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  31939. return;
  31940. }
  31941. if (!this._heightQuads || this._heightQuads.length == 0) {
  31942. this._initHeightQuads();
  31943. this._computeHeightQuads();
  31944. }
  31945. var facet = this._getFacetAt(x, z);
  31946. ref.x = facet.x;
  31947. ref.y = facet.y;
  31948. ref.z = facet.z;
  31949. };
  31950. /**
  31951. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  31952. * if the ground has been updated.
  31953. * This can be used in the render loop
  31954. */
  31955. GroundMesh.prototype.updateCoordinateHeights = function () {
  31956. if (!this._heightQuads || this._heightQuads.length == 0) {
  31957. this._initHeightQuads();
  31958. }
  31959. this._computeHeightQuads();
  31960. };
  31961. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  31962. GroundMesh.prototype._getFacetAt = function (x, z) {
  31963. // retrieve col and row from x, z coordinates in the ground local system
  31964. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  31965. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  31966. var quad = this._heightQuads[row * this._subdivisions + col];
  31967. var facet;
  31968. if (z < quad.slope.x * x + quad.slope.y) {
  31969. facet = quad.facet1;
  31970. }
  31971. else {
  31972. facet = quad.facet2;
  31973. }
  31974. return facet;
  31975. };
  31976. // Creates and populates the heightMap array with "facet" elements :
  31977. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  31978. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  31979. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  31980. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  31981. GroundMesh.prototype._initHeightQuads = function () {
  31982. this._heightQuads = new Array();
  31983. for (var row = 0; row < this._subdivisions; row++) {
  31984. for (var col = 0; col < this._subdivisions; col++) {
  31985. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  31986. this._heightQuads[row * this._subdivisions + col] = quad;
  31987. }
  31988. }
  31989. };
  31990. // Compute each quad element values and update the the heightMap array :
  31991. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  31992. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  31993. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  31994. GroundMesh.prototype._computeHeightQuads = function () {
  31995. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31996. var v1 = BABYLON.Tmp.Vector3[0];
  31997. var v2 = BABYLON.Tmp.Vector3[1];
  31998. var v3 = BABYLON.Tmp.Vector3[2];
  31999. var v4 = BABYLON.Tmp.Vector3[3];
  32000. var v1v2 = BABYLON.Tmp.Vector3[4];
  32001. var v1v3 = BABYLON.Tmp.Vector3[5];
  32002. var v1v4 = BABYLON.Tmp.Vector3[6];
  32003. var norm1 = BABYLON.Tmp.Vector3[7];
  32004. var norm2 = BABYLON.Tmp.Vector3[8];
  32005. var i = 0;
  32006. var j = 0;
  32007. var k = 0;
  32008. var cd = 0; // 2D slope coefficient : z = cd * x + h
  32009. var h = 0;
  32010. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  32011. var d2 = 0;
  32012. for (var row = 0; row < this._subdivisions; row++) {
  32013. for (var col = 0; col < this._subdivisions; col++) {
  32014. i = col * 3;
  32015. j = row * (this._subdivisions + 1) * 3;
  32016. k = (row + 1) * (this._subdivisions + 1) * 3;
  32017. v1.x = positions[j + i];
  32018. v1.y = positions[j + i + 1];
  32019. v1.z = positions[j + i + 2];
  32020. v2.x = positions[j + i + 3];
  32021. v2.y = positions[j + i + 4];
  32022. v2.z = positions[j + i + 5];
  32023. v3.x = positions[k + i];
  32024. v3.y = positions[k + i + 1];
  32025. v3.z = positions[k + i + 2];
  32026. v4.x = positions[k + i + 3];
  32027. v4.y = positions[k + i + 4];
  32028. v4.z = positions[k + i + 5];
  32029. // 2D slope V1V4
  32030. cd = (v4.z - v1.z) / (v4.x - v1.x);
  32031. h = v1.z - cd * v1.x; // v1 belongs to the slope
  32032. // facet equations :
  32033. // we compute each facet normal vector
  32034. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  32035. // we compute the value d by applying the equation to v1 which belongs to the plane
  32036. // then we store the facet equation in a Vector4
  32037. v2.subtractToRef(v1, v1v2);
  32038. v3.subtractToRef(v1, v1v3);
  32039. v4.subtractToRef(v1, v1v4);
  32040. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1);
  32041. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  32042. norm1.normalize();
  32043. norm2.normalize();
  32044. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  32045. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  32046. var quad = this._heightQuads[row * this._subdivisions + col];
  32047. quad.slope.copyFromFloats(cd, h);
  32048. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  32049. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  32050. }
  32051. }
  32052. };
  32053. return GroundMesh;
  32054. })(BABYLON.Mesh);
  32055. BABYLON.GroundMesh = GroundMesh;
  32056. })(BABYLON || (BABYLON = {}));
  32057. var BABYLON;
  32058. (function (BABYLON) {
  32059. var LinesMesh = (function (_super) {
  32060. __extends(LinesMesh, _super);
  32061. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  32062. if (parent === void 0) { parent = null; }
  32063. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  32064. this.color = new BABYLON.Color3(1, 1, 1);
  32065. this.alpha = 1;
  32066. this._intersectionThreshold = 0.1;
  32067. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  32068. attributes: ["position"],
  32069. uniforms: ["worldViewProjection", "color"],
  32070. needAlphaBlending: true
  32071. });
  32072. }
  32073. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  32074. /**
  32075. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  32076. * This margin is expressed in world space coordinates, so its value may vary.
  32077. * Default value is 0.1
  32078. * @returns the intersection Threshold value.
  32079. */
  32080. get: function () {
  32081. return this._intersectionThreshold;
  32082. },
  32083. /**
  32084. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  32085. * This margin is expressed in world space coordinates, so its value may vary.
  32086. * @param value the new threshold to apply
  32087. */
  32088. set: function (value) {
  32089. if (this._intersectionThreshold === value) {
  32090. return;
  32091. }
  32092. this._intersectionThreshold = value;
  32093. if (this.geometry) {
  32094. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  32095. }
  32096. },
  32097. enumerable: true,
  32098. configurable: true
  32099. });
  32100. Object.defineProperty(LinesMesh.prototype, "material", {
  32101. get: function () {
  32102. return this._colorShader;
  32103. },
  32104. enumerable: true,
  32105. configurable: true
  32106. });
  32107. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  32108. get: function () {
  32109. return true;
  32110. },
  32111. enumerable: true,
  32112. configurable: true
  32113. });
  32114. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  32115. get: function () {
  32116. return false;
  32117. },
  32118. enumerable: true,
  32119. configurable: true
  32120. });
  32121. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  32122. var engine = this.getScene().getEngine();
  32123. var indexToBind = this._geometry.getIndexBuffer();
  32124. // VBOs
  32125. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  32126. // Color
  32127. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  32128. };
  32129. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  32130. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  32131. return;
  32132. }
  32133. var engine = this.getScene().getEngine();
  32134. // Draw order
  32135. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  32136. };
  32137. LinesMesh.prototype.dispose = function (doNotRecurse) {
  32138. this._colorShader.dispose();
  32139. _super.prototype.dispose.call(this, doNotRecurse);
  32140. };
  32141. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  32142. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  32143. };
  32144. return LinesMesh;
  32145. })(BABYLON.Mesh);
  32146. BABYLON.LinesMesh = LinesMesh;
  32147. })(BABYLON || (BABYLON = {}));
  32148. var BABYLON;
  32149. (function (BABYLON) {
  32150. var DebugLayer = (function () {
  32151. function DebugLayer(scene) {
  32152. var _this = this;
  32153. this._transformationMatrix = BABYLON.Matrix.Identity();
  32154. this._enabled = false;
  32155. this._labelsEnabled = false;
  32156. this._displayStatistics = true;
  32157. this._displayTree = false;
  32158. this._displayLogs = false;
  32159. this._skeletonViewers = new Array();
  32160. this._identityMatrix = BABYLON.Matrix.Identity();
  32161. this.axisRatio = 0.02;
  32162. this.accentColor = "orange";
  32163. this._scene = scene;
  32164. this._syncPositions = function () {
  32165. var engine = _this._scene.getEngine();
  32166. var canvasRect = engine.getRenderingCanvasClientRect();
  32167. if (_this._showUI) {
  32168. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  32169. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  32170. _this._statsDiv.style.width = "400px";
  32171. _this._statsDiv.style.height = "auto";
  32172. _this._statsSubsetDiv.style.maxHeight = "240px";
  32173. _this._optionsDiv.style.left = "0px";
  32174. _this._optionsDiv.style.top = "10px";
  32175. _this._optionsDiv.style.width = "200px";
  32176. _this._optionsDiv.style.height = "auto";
  32177. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  32178. _this._logDiv.style.left = "0px";
  32179. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  32180. _this._logDiv.style.width = "600px";
  32181. _this._logDiv.style.height = "160px";
  32182. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  32183. _this._treeDiv.style.top = "10px";
  32184. _this._treeDiv.style.width = "300px";
  32185. _this._treeDiv.style.height = "auto";
  32186. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  32187. }
  32188. _this._globalDiv.style.left = canvasRect.left + "px";
  32189. _this._globalDiv.style.top = canvasRect.top + "px";
  32190. _this._drawingCanvas.style.left = "0px";
  32191. _this._drawingCanvas.style.top = "0px";
  32192. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  32193. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  32194. var devicePixelRatio = window.devicePixelRatio || 1;
  32195. var context = _this._drawingContext;
  32196. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  32197. context.mozBackingStorePixelRatio ||
  32198. context.msBackingStorePixelRatio ||
  32199. context.oBackingStorePixelRatio ||
  32200. context.backingStorePixelRatio || 1;
  32201. _this._ratio = devicePixelRatio / backingStoreRatio;
  32202. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  32203. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  32204. };
  32205. this._onCanvasClick = function (evt) {
  32206. _this._clickPosition = {
  32207. x: evt.clientX * _this._ratio,
  32208. y: evt.clientY * _this._ratio
  32209. };
  32210. };
  32211. this._syncUI = function () {
  32212. if (_this._showUI) {
  32213. if (_this._displayStatistics) {
  32214. _this._displayStats();
  32215. _this._statsDiv.style.display = "";
  32216. }
  32217. else {
  32218. _this._statsDiv.style.display = "none";
  32219. }
  32220. if (_this._displayLogs) {
  32221. _this._logDiv.style.display = "";
  32222. }
  32223. else {
  32224. _this._logDiv.style.display = "none";
  32225. }
  32226. if (_this._displayTree) {
  32227. _this._treeDiv.style.display = "";
  32228. if (_this._needToRefreshMeshesTree) {
  32229. _this._needToRefreshMeshesTree = false;
  32230. _this._refreshMeshesTreeContent();
  32231. }
  32232. }
  32233. else {
  32234. _this._treeDiv.style.display = "none";
  32235. }
  32236. }
  32237. };
  32238. this._syncData = function () {
  32239. if (_this._labelsEnabled || !_this._showUI) {
  32240. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  32241. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  32242. var engine = _this._scene.getEngine();
  32243. var viewport = _this._camera.viewport;
  32244. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  32245. // Meshes
  32246. var meshes = _this._camera.getActiveMeshes();
  32247. var index;
  32248. var projectedPosition;
  32249. for (index = 0; index < meshes.length; index++) {
  32250. var mesh = meshes.data[index];
  32251. var position = mesh.getBoundingInfo().boundingSphere.center;
  32252. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  32253. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  32254. _this._renderAxis(projectedPosition, mesh, globalViewport);
  32255. }
  32256. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  32257. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  32258. }
  32259. }
  32260. // Cameras
  32261. var cameras = _this._scene.cameras;
  32262. for (index = 0; index < cameras.length; index++) {
  32263. var camera = cameras[index];
  32264. if (camera === _this._camera) {
  32265. continue;
  32266. }
  32267. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  32268. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  32269. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  32270. _this._camera.detachControl(engine.getRenderingCanvas());
  32271. _this._camera = camera;
  32272. _this._camera.attachControl(engine.getRenderingCanvas());
  32273. }, function () { return "purple"; });
  32274. }
  32275. }
  32276. // Lights
  32277. var lights = _this._scene.lights;
  32278. for (index = 0; index < lights.length; index++) {
  32279. var light = lights[index];
  32280. if (light.position) {
  32281. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  32282. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  32283. _this._renderLabel(light.name, projectedPosition, -20, function () {
  32284. light.setEnabled(!light.isEnabled());
  32285. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  32286. }
  32287. }
  32288. }
  32289. }
  32290. _this._clickPosition = undefined;
  32291. };
  32292. }
  32293. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  32294. while (this._treeSubsetDiv.hasChildNodes()) {
  32295. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  32296. }
  32297. // Add meshes
  32298. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  32299. sortedArray.sort(function (a, b) {
  32300. if (a.name === b.name) {
  32301. return 0;
  32302. }
  32303. return (a.name > b.name) ? 1 : -1;
  32304. });
  32305. for (var index = 0; index < sortedArray.length; index++) {
  32306. var mesh = sortedArray[index];
  32307. if (!mesh.isEnabled()) {
  32308. continue;
  32309. }
  32310. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  32311. m.isVisible = element.checked;
  32312. }, mesh);
  32313. }
  32314. };
  32315. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  32316. this._drawingContext.beginPath();
  32317. this._drawingContext.moveTo(zero.x, zero.y);
  32318. this._drawingContext.lineTo(unit.x, unit.y);
  32319. this._drawingContext.strokeStyle = color;
  32320. this._drawingContext.lineWidth = 4;
  32321. this._drawingContext.stroke();
  32322. this._drawingContext.font = "normal 14px Segoe UI";
  32323. this._drawingContext.fillStyle = color;
  32324. this._drawingContext.fillText(label, unitText.x, unitText.y);
  32325. };
  32326. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  32327. var position = mesh.getBoundingInfo().boundingSphere.center;
  32328. var worldMatrix = mesh.getWorldMatrix();
  32329. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  32330. var unit = (unprojectedVector.subtract(position)).length();
  32331. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32332. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32333. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  32334. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32335. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  32336. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  32337. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  32338. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  32339. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  32340. };
  32341. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  32342. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  32343. this._drawingContext.font = "normal 12px Segoe UI";
  32344. var textMetrics = this._drawingContext.measureText(text);
  32345. var centerX = projectedPosition.x - textMetrics.width / 2;
  32346. var centerY = projectedPosition.y;
  32347. var clientRect = this._drawingCanvas.getBoundingClientRect();
  32348. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  32349. onClick();
  32350. }
  32351. this._drawingContext.beginPath();
  32352. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  32353. this._drawingContext.fillStyle = getFillStyle();
  32354. this._drawingContext.globalAlpha = 0.5;
  32355. this._drawingContext.fill();
  32356. this._drawingContext.globalAlpha = 1.0;
  32357. this._drawingContext.strokeStyle = '#FFFFFF';
  32358. this._drawingContext.lineWidth = 1;
  32359. this._drawingContext.stroke();
  32360. this._drawingContext.fillStyle = "#FFFFFF";
  32361. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  32362. this._drawingContext.beginPath();
  32363. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  32364. this._drawingContext.fill();
  32365. }
  32366. };
  32367. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  32368. if (!this._clickPosition) {
  32369. return false;
  32370. }
  32371. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  32372. return false;
  32373. }
  32374. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  32375. return false;
  32376. }
  32377. return true;
  32378. };
  32379. DebugLayer.prototype.isVisible = function () {
  32380. return this._enabled;
  32381. };
  32382. DebugLayer.prototype.hide = function () {
  32383. if (!this._enabled) {
  32384. return;
  32385. }
  32386. this._enabled = false;
  32387. var engine = this._scene.getEngine();
  32388. this._scene.unregisterBeforeRender(this._syncData);
  32389. this._scene.unregisterAfterRender(this._syncUI);
  32390. this._rootElement.removeChild(this._globalDiv);
  32391. this._scene.forceShowBoundingBoxes = false;
  32392. this._scene.forceWireframe = false;
  32393. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  32394. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  32395. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  32396. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  32397. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  32398. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  32399. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  32400. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  32401. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  32402. this._scene.shadowsEnabled = true;
  32403. this._scene.particlesEnabled = true;
  32404. this._scene.postProcessesEnabled = true;
  32405. this._scene.collisionsEnabled = true;
  32406. this._scene.lightsEnabled = true;
  32407. this._scene.texturesEnabled = true;
  32408. this._scene.lensFlaresEnabled = true;
  32409. this._scene.proceduralTexturesEnabled = true;
  32410. this._scene.renderTargetsEnabled = true;
  32411. this._scene.probesEnabled = true;
  32412. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  32413. this._clearSkeletonViewers();
  32414. };
  32415. DebugLayer.prototype._clearSkeletonViewers = function () {
  32416. for (var index = 0; index < this._skeletonViewers.length; index++) {
  32417. this._skeletonViewers[index].dispose();
  32418. }
  32419. this._skeletonViewers = [];
  32420. };
  32421. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  32422. if (showUI === void 0) { showUI = true; }
  32423. if (camera === void 0) { camera = null; }
  32424. if (rootElement === void 0) { rootElement = null; }
  32425. if (this._enabled) {
  32426. return;
  32427. }
  32428. this._enabled = true;
  32429. if (camera) {
  32430. this._camera = camera;
  32431. }
  32432. else {
  32433. this._camera = this._scene.activeCamera;
  32434. }
  32435. this._showUI = showUI;
  32436. var engine = this._scene.getEngine();
  32437. this._globalDiv = document.createElement("div");
  32438. this._rootElement = rootElement || document.body;
  32439. this._rootElement.appendChild(this._globalDiv);
  32440. this._generateDOMelements();
  32441. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  32442. this._syncPositions();
  32443. this._scene.registerBeforeRender(this._syncData);
  32444. this._scene.registerAfterRender(this._syncUI);
  32445. };
  32446. DebugLayer.prototype._clearLabels = function () {
  32447. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  32448. for (var index = 0; index < this._scene.meshes.length; index++) {
  32449. var mesh = this._scene.meshes[index];
  32450. mesh.renderOverlay = false;
  32451. }
  32452. };
  32453. DebugLayer.prototype._generateheader = function (root, text) {
  32454. var header = document.createElement("div");
  32455. header.innerHTML = text + "&nbsp;";
  32456. header.style.textAlign = "right";
  32457. header.style.width = "100%";
  32458. header.style.color = "white";
  32459. header.style.backgroundColor = "Black";
  32460. header.style.padding = "5px 5px 4px 0px";
  32461. header.style.marginLeft = "-5px";
  32462. header.style.fontWeight = "bold";
  32463. root.appendChild(header);
  32464. };
  32465. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  32466. var label = document.createElement("label");
  32467. label.style.display = "inline";
  32468. label.innerHTML = title;
  32469. label.style.color = color;
  32470. root.appendChild(label);
  32471. root.appendChild(document.createElement("br"));
  32472. };
  32473. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  32474. if (tag === void 0) { tag = null; }
  32475. var label = document.createElement("label");
  32476. label.style.display = "inline";
  32477. var boundingBoxesCheckbox = document.createElement("input");
  32478. boundingBoxesCheckbox.type = "checkbox";
  32479. boundingBoxesCheckbox.checked = initialState;
  32480. boundingBoxesCheckbox.style.display = "inline";
  32481. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  32482. boundingBoxesCheckbox.style.verticalAlign = "sub";
  32483. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  32484. task(evt.target, tag);
  32485. });
  32486. label.appendChild(boundingBoxesCheckbox);
  32487. var container = document.createElement("span");
  32488. var leftPart = document.createElement("span");
  32489. var rightPart = document.createElement("span");
  32490. rightPart.style.cssFloat = "right";
  32491. leftPart.innerHTML = leftTitle;
  32492. rightPart.innerHTML = rightTitle;
  32493. rightPart.style.fontSize = "12px";
  32494. rightPart.style.maxWidth = "200px";
  32495. container.appendChild(leftPart);
  32496. container.appendChild(rightPart);
  32497. label.appendChild(container);
  32498. root.appendChild(label);
  32499. root.appendChild(document.createElement("br"));
  32500. };
  32501. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  32502. if (tag === void 0) { tag = null; }
  32503. var label = document.createElement("label");
  32504. label.style.display = "inline";
  32505. var checkBox = document.createElement("input");
  32506. checkBox.type = "checkbox";
  32507. checkBox.checked = initialState;
  32508. checkBox.style.display = "inline";
  32509. checkBox.style.margin = "0px 5px 0px 0px";
  32510. checkBox.style.verticalAlign = "sub";
  32511. checkBox.addEventListener("change", function (evt) {
  32512. task(evt.target, tag);
  32513. });
  32514. label.appendChild(checkBox);
  32515. label.appendChild(document.createTextNode(title));
  32516. root.appendChild(label);
  32517. root.appendChild(document.createElement("br"));
  32518. };
  32519. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  32520. if (tag === void 0) { tag = null; }
  32521. var button = document.createElement("button");
  32522. button.innerHTML = title;
  32523. button.style.height = "24px";
  32524. button.style.width = "150px";
  32525. button.style.marginBottom = "5px";
  32526. button.style.color = "#444444";
  32527. button.style.border = "1px solid white";
  32528. button.className = "debugLayerButton";
  32529. button.addEventListener("click", function (evt) {
  32530. task(evt.target, tag);
  32531. });
  32532. root.appendChild(button);
  32533. root.appendChild(document.createElement("br"));
  32534. };
  32535. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  32536. if (tag === void 0) { tag = null; }
  32537. var label = document.createElement("label");
  32538. label.style.display = "inline";
  32539. var boundingBoxesRadio = document.createElement("input");
  32540. boundingBoxesRadio.type = "radio";
  32541. boundingBoxesRadio.name = name;
  32542. boundingBoxesRadio.checked = initialState;
  32543. boundingBoxesRadio.style.display = "inline";
  32544. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  32545. boundingBoxesRadio.style.verticalAlign = "sub";
  32546. boundingBoxesRadio.addEventListener("change", function (evt) {
  32547. task(evt.target, tag);
  32548. });
  32549. label.appendChild(boundingBoxesRadio);
  32550. label.appendChild(document.createTextNode(title));
  32551. root.appendChild(label);
  32552. root.appendChild(document.createElement("br"));
  32553. };
  32554. DebugLayer.prototype._generateDOMelements = function () {
  32555. var _this = this;
  32556. this._globalDiv.id = "DebugLayer";
  32557. this._globalDiv.style.position = "absolute";
  32558. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  32559. this._globalDiv.style.fontSize = "14px";
  32560. this._globalDiv.style.color = "white";
  32561. // Drawing canvas
  32562. this._drawingCanvas = document.createElement("canvas");
  32563. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  32564. this._drawingCanvas.style.position = "absolute";
  32565. this._drawingCanvas.style.pointerEvents = "none";
  32566. this._drawingCanvas.style.backgroundColor = "transparent";
  32567. this._drawingContext = this._drawingCanvas.getContext("2d");
  32568. this._globalDiv.appendChild(this._drawingCanvas);
  32569. if (this._showUI) {
  32570. var background = "rgba(128, 128, 128, 0.4)";
  32571. var border = "rgb(180, 180, 180) solid 1px";
  32572. // Stats
  32573. this._statsDiv = document.createElement("div");
  32574. this._statsDiv.id = "DebugLayerStats";
  32575. this._statsDiv.style.border = border;
  32576. this._statsDiv.style.position = "absolute";
  32577. this._statsDiv.style.background = background;
  32578. this._statsDiv.style.padding = "0px 0px 0px 5px";
  32579. this._generateheader(this._statsDiv, "STATISTICS");
  32580. this._statsSubsetDiv = document.createElement("div");
  32581. this._statsSubsetDiv.style.paddingTop = "5px";
  32582. this._statsSubsetDiv.style.paddingBottom = "5px";
  32583. this._statsSubsetDiv.style.overflowY = "auto";
  32584. this._statsDiv.appendChild(this._statsSubsetDiv);
  32585. // Tree
  32586. this._treeDiv = document.createElement("div");
  32587. this._treeDiv.id = "DebugLayerTree";
  32588. this._treeDiv.style.border = border;
  32589. this._treeDiv.style.position = "absolute";
  32590. this._treeDiv.style.background = background;
  32591. this._treeDiv.style.padding = "0px 0px 0px 5px";
  32592. this._treeDiv.style.display = "none";
  32593. this._generateheader(this._treeDiv, "MESHES TREE");
  32594. this._treeSubsetDiv = document.createElement("div");
  32595. this._treeSubsetDiv.style.paddingTop = "5px";
  32596. this._treeSubsetDiv.style.paddingRight = "5px";
  32597. this._treeSubsetDiv.style.overflowY = "auto";
  32598. this._treeSubsetDiv.style.maxHeight = "300px";
  32599. this._treeDiv.appendChild(this._treeSubsetDiv);
  32600. this._needToRefreshMeshesTree = true;
  32601. // Logs
  32602. this._logDiv = document.createElement("div");
  32603. this._logDiv.style.border = border;
  32604. this._logDiv.id = "DebugLayerLogs";
  32605. this._logDiv.style.position = "absolute";
  32606. this._logDiv.style.background = background;
  32607. this._logDiv.style.padding = "0px 0px 0px 5px";
  32608. this._logDiv.style.display = "none";
  32609. this._generateheader(this._logDiv, "LOGS");
  32610. this._logSubsetDiv = document.createElement("div");
  32611. this._logSubsetDiv.style.height = "127px";
  32612. this._logSubsetDiv.style.paddingTop = "5px";
  32613. this._logSubsetDiv.style.overflowY = "auto";
  32614. this._logSubsetDiv.style.fontSize = "12px";
  32615. this._logSubsetDiv.style.fontFamily = "consolas";
  32616. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  32617. this._logDiv.appendChild(this._logSubsetDiv);
  32618. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  32619. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  32620. };
  32621. // Options
  32622. this._optionsDiv = document.createElement("div");
  32623. this._optionsDiv.id = "DebugLayerOptions";
  32624. this._optionsDiv.style.border = border;
  32625. this._optionsDiv.style.position = "absolute";
  32626. this._optionsDiv.style.background = background;
  32627. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  32628. this._optionsDiv.style.overflowY = "auto";
  32629. this._generateheader(this._optionsDiv, "OPTIONS");
  32630. this._optionsSubsetDiv = document.createElement("div");
  32631. this._optionsSubsetDiv.style.paddingTop = "5px";
  32632. this._optionsSubsetDiv.style.paddingBottom = "5px";
  32633. this._optionsSubsetDiv.style.overflowY = "auto";
  32634. this._optionsSubsetDiv.style.maxHeight = "200px";
  32635. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  32636. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  32637. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  32638. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  32639. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  32640. _this._displayTree = element.checked;
  32641. _this._needToRefreshMeshesTree = true;
  32642. });
  32643. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32644. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  32645. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  32646. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  32647. _this._labelsEnabled = element.checked;
  32648. if (!_this._labelsEnabled) {
  32649. _this._clearLabels();
  32650. }
  32651. });
  32652. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  32653. if (element.checked) {
  32654. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  32655. }
  32656. else {
  32657. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  32658. }
  32659. });
  32660. ;
  32661. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32662. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  32663. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  32664. if (element.checked) {
  32665. _this._scene.forceWireframe = false;
  32666. _this._scene.forcePointsCloud = false;
  32667. }
  32668. });
  32669. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  32670. if (element.checked) {
  32671. _this._scene.forceWireframe = true;
  32672. _this._scene.forcePointsCloud = false;
  32673. }
  32674. });
  32675. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  32676. if (element.checked) {
  32677. _this._scene.forceWireframe = false;
  32678. _this._scene.forcePointsCloud = true;
  32679. }
  32680. });
  32681. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32682. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  32683. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  32684. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  32685. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  32686. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  32687. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  32688. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  32689. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  32690. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  32691. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  32692. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  32693. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32694. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  32695. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  32696. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  32697. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  32698. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  32699. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  32700. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  32701. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  32702. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  32703. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  32704. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  32705. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  32706. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  32707. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  32708. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  32709. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  32710. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32711. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  32712. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  32713. if (element.checked) {
  32714. _this._scene.headphone = true;
  32715. }
  32716. });
  32717. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  32718. if (element.checked) {
  32719. _this._scene.headphone = false;
  32720. }
  32721. });
  32722. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  32723. _this._scene.audioEnabled = !element.checked;
  32724. });
  32725. }
  32726. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32727. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  32728. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  32729. if (!element.checked) {
  32730. _this._clearSkeletonViewers();
  32731. return;
  32732. }
  32733. for (var index = 0; index < _this._scene.meshes.length; index++) {
  32734. var mesh = _this._scene.meshes[index];
  32735. if (mesh.skeleton) {
  32736. var found = false;
  32737. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  32738. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  32739. found = true;
  32740. break;
  32741. }
  32742. }
  32743. if (found) {
  32744. continue;
  32745. }
  32746. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  32747. viewer.isEnabled = true;
  32748. _this._skeletonViewers.push(viewer);
  32749. }
  32750. }
  32751. });
  32752. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32753. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  32754. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  32755. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  32756. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  32757. if (_this._camera) {
  32758. console.log(_this._camera);
  32759. }
  32760. else {
  32761. console.warn("No camera defined, or debug layer created before camera creation!");
  32762. }
  32763. });
  32764. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  32765. this._globalDiv.appendChild(this._statsDiv);
  32766. this._globalDiv.appendChild(this._logDiv);
  32767. this._globalDiv.appendChild(this._optionsDiv);
  32768. this._globalDiv.appendChild(this._treeDiv);
  32769. }
  32770. };
  32771. DebugLayer.prototype._displayStats = function () {
  32772. var scene = this._scene;
  32773. var engine = scene.getEngine();
  32774. var glInfo = engine.getGlInfo();
  32775. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  32776. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  32777. + "<b>Count</b><br>"
  32778. + "Total meshes: " + scene.meshes.length + "<br>"
  32779. + "Total lights: " + scene.lights.length + "<br>"
  32780. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  32781. + "Total materials: " + scene.materials.length + "<br>"
  32782. + "Total textures: " + scene.textures.length + "<br>"
  32783. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  32784. + "Active indices: " + scene.getActiveIndices() + "<br>"
  32785. + "Active bones: " + scene.getActiveBones() + "<br>"
  32786. + "Active particles: " + scene.getActiveParticles() + "<br>"
  32787. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  32788. + "<b>Duration</b><br>"
  32789. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  32790. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  32791. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  32792. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  32793. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  32794. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  32795. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  32796. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  32797. + "</div>"
  32798. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  32799. + "<b>Extensions</b><br>"
  32800. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  32801. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  32802. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  32803. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  32804. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  32805. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  32806. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  32807. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  32808. + "</div><br>"
  32809. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  32810. + "<b>Caps.</b><br>"
  32811. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  32812. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  32813. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  32814. + "<b>Info</b><br>"
  32815. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  32816. + glInfo.version + "<br>"
  32817. + "</div><br>"
  32818. + glInfo.renderer + "<br>";
  32819. if (this.customStatsFunction) {
  32820. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  32821. }
  32822. };
  32823. return DebugLayer;
  32824. })();
  32825. BABYLON.DebugLayer = DebugLayer;
  32826. })(BABYLON || (BABYLON = {}));
  32827. var BABYLON;
  32828. (function (BABYLON) {
  32829. var DefaultLoadingScreen = (function () {
  32830. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  32831. var _this = this;
  32832. if (_loadingText === void 0) { _loadingText = ""; }
  32833. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  32834. this._renderingCanvas = _renderingCanvas;
  32835. this._loadingText = _loadingText;
  32836. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  32837. // Resize
  32838. this._resizeLoadingUI = function () {
  32839. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  32840. _this._loadingDiv.style.position = "absolute";
  32841. _this._loadingDiv.style.left = canvasRect.left + "px";
  32842. _this._loadingDiv.style.top = canvasRect.top + "px";
  32843. _this._loadingDiv.style.width = canvasRect.width + "px";
  32844. _this._loadingDiv.style.height = canvasRect.height + "px";
  32845. };
  32846. }
  32847. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  32848. var _this = this;
  32849. if (this._loadingDiv) {
  32850. // Do not add a loading screen if there is already one
  32851. return;
  32852. }
  32853. this._loadingDiv = document.createElement("div");
  32854. this._loadingDiv.id = "babylonjsLoadingDiv";
  32855. this._loadingDiv.style.opacity = "0";
  32856. this._loadingDiv.style.transition = "opacity 1.5s ease";
  32857. // Loading text
  32858. this._loadingTextDiv = document.createElement("div");
  32859. this._loadingTextDiv.style.position = "absolute";
  32860. this._loadingTextDiv.style.left = "0";
  32861. this._loadingTextDiv.style.top = "50%";
  32862. this._loadingTextDiv.style.marginTop = "80px";
  32863. this._loadingTextDiv.style.width = "100%";
  32864. this._loadingTextDiv.style.height = "20px";
  32865. this._loadingTextDiv.style.fontFamily = "Arial";
  32866. this._loadingTextDiv.style.fontSize = "14px";
  32867. this._loadingTextDiv.style.color = "white";
  32868. this._loadingTextDiv.style.textAlign = "center";
  32869. this._loadingTextDiv.innerHTML = "Loading";
  32870. this._loadingDiv.appendChild(this._loadingTextDiv);
  32871. //set the predefined text
  32872. this._loadingTextDiv.innerHTML = this._loadingText;
  32873. // Loading img
  32874. var imgBack = new Image();
  32875. 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==";
  32876. imgBack.style.position = "absolute";
  32877. imgBack.style.left = "50%";
  32878. imgBack.style.top = "50%";
  32879. imgBack.style.marginLeft = "-50px";
  32880. imgBack.style.marginTop = "-50px";
  32881. imgBack.style.transition = "transform 1.0s ease";
  32882. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  32883. var deg = 360;
  32884. var onTransitionEnd = function () {
  32885. deg += 360;
  32886. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  32887. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  32888. };
  32889. imgBack.addEventListener("transitionend", onTransitionEnd);
  32890. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  32891. this._loadingDiv.appendChild(imgBack);
  32892. // front image
  32893. var imgFront = new Image();
  32894. 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=";
  32895. imgFront.style.position = "absolute";
  32896. imgFront.style.left = "50%";
  32897. imgFront.style.top = "50%";
  32898. imgFront.style.marginLeft = "-50px";
  32899. imgFront.style.marginTop = "-50px";
  32900. this._loadingDiv.appendChild(imgFront);
  32901. this._resizeLoadingUI();
  32902. window.addEventListener("resize", this._resizeLoadingUI);
  32903. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  32904. document.body.appendChild(this._loadingDiv);
  32905. setTimeout(function () {
  32906. _this._loadingDiv.style.opacity = "1";
  32907. imgBack.style.transform = "rotateZ(360deg)";
  32908. imgBack.style.webkitTransform = "rotateZ(360deg)";
  32909. }, 0);
  32910. };
  32911. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  32912. var _this = this;
  32913. if (!this._loadingDiv) {
  32914. return;
  32915. }
  32916. var onTransitionEnd = function () {
  32917. if (!_this._loadingDiv) {
  32918. return;
  32919. }
  32920. document.body.removeChild(_this._loadingDiv);
  32921. window.removeEventListener("resize", _this._resizeLoadingUI);
  32922. _this._loadingDiv = null;
  32923. };
  32924. this._loadingDiv.style.opacity = "0";
  32925. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  32926. };
  32927. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  32928. set: function (text) {
  32929. this._loadingText = text;
  32930. if (this._loadingTextDiv) {
  32931. this._loadingTextDiv.innerHTML = this._loadingText;
  32932. }
  32933. },
  32934. enumerable: true,
  32935. configurable: true
  32936. });
  32937. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  32938. get: function () {
  32939. return this._loadingDivBackgroundColor;
  32940. },
  32941. set: function (color) {
  32942. this._loadingDivBackgroundColor = color;
  32943. if (!this._loadingDiv) {
  32944. return;
  32945. }
  32946. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  32947. },
  32948. enumerable: true,
  32949. configurable: true
  32950. });
  32951. return DefaultLoadingScreen;
  32952. })();
  32953. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  32954. })(BABYLON || (BABYLON = {}));
  32955. var BABYLON;
  32956. (function (BABYLON) {
  32957. var AudioEngine = (function () {
  32958. function AudioEngine() {
  32959. this._audioContext = null;
  32960. this._audioContextInitialized = false;
  32961. this.canUseWebAudio = false;
  32962. this.WarnedWebAudioUnsupported = false;
  32963. this.unlocked = false;
  32964. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  32965. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  32966. this.canUseWebAudio = true;
  32967. }
  32968. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  32969. this._unlockiOSaudio();
  32970. }
  32971. else {
  32972. this.unlocked = true;
  32973. }
  32974. }
  32975. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  32976. get: function () {
  32977. if (!this._audioContextInitialized) {
  32978. this._initializeAudioContext();
  32979. }
  32980. return this._audioContext;
  32981. },
  32982. enumerable: true,
  32983. configurable: true
  32984. });
  32985. AudioEngine.prototype._unlockiOSaudio = function () {
  32986. var _this = this;
  32987. var unlockaudio = function () {
  32988. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  32989. var source = _this.audioContext.createBufferSource();
  32990. source.buffer = buffer;
  32991. source.connect(_this.audioContext.destination);
  32992. source.start(0);
  32993. setTimeout(function () {
  32994. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  32995. _this.unlocked = true;
  32996. window.removeEventListener('touchend', unlockaudio, false);
  32997. if (_this.onAudioUnlocked) {
  32998. _this.onAudioUnlocked();
  32999. }
  33000. }
  33001. }, 0);
  33002. };
  33003. window.addEventListener('touchend', unlockaudio, false);
  33004. };
  33005. AudioEngine.prototype._initializeAudioContext = function () {
  33006. try {
  33007. if (this.canUseWebAudio) {
  33008. this._audioContext = new AudioContext();
  33009. // create a global volume gain node
  33010. this.masterGain = this._audioContext.createGain();
  33011. this.masterGain.gain.value = 1;
  33012. this.masterGain.connect(this._audioContext.destination);
  33013. this._audioContextInitialized = true;
  33014. }
  33015. }
  33016. catch (e) {
  33017. this.canUseWebAudio = false;
  33018. BABYLON.Tools.Error("Web Audio: " + e.message);
  33019. }
  33020. };
  33021. AudioEngine.prototype.dispose = function () {
  33022. if (this.canUseWebAudio && this._audioContextInitialized) {
  33023. if (this._connectedAnalyser) {
  33024. this._connectedAnalyser.stopDebugCanvas();
  33025. this._connectedAnalyser.dispose();
  33026. this.masterGain.disconnect();
  33027. this.masterGain.connect(this._audioContext.destination);
  33028. this._connectedAnalyser = null;
  33029. }
  33030. this.masterGain.gain.value = 1;
  33031. }
  33032. this.WarnedWebAudioUnsupported = false;
  33033. };
  33034. AudioEngine.prototype.getGlobalVolume = function () {
  33035. if (this.canUseWebAudio && this._audioContextInitialized) {
  33036. return this.masterGain.gain.value;
  33037. }
  33038. else {
  33039. return -1;
  33040. }
  33041. };
  33042. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  33043. if (this.canUseWebAudio && this._audioContextInitialized) {
  33044. this.masterGain.gain.value = newVolume;
  33045. }
  33046. };
  33047. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  33048. if (this._connectedAnalyser) {
  33049. this._connectedAnalyser.stopDebugCanvas();
  33050. }
  33051. if (this.canUseWebAudio && this._audioContextInitialized) {
  33052. this._connectedAnalyser = analyser;
  33053. this.masterGain.disconnect();
  33054. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  33055. }
  33056. };
  33057. return AudioEngine;
  33058. })();
  33059. BABYLON.AudioEngine = AudioEngine;
  33060. })(BABYLON || (BABYLON = {}));
  33061. var BABYLON;
  33062. (function (BABYLON) {
  33063. var Sound = (function () {
  33064. /**
  33065. * Create a sound and attach it to a scene
  33066. * @param name Name of your sound
  33067. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  33068. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  33069. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  33070. */
  33071. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  33072. var _this = this;
  33073. this.autoplay = false;
  33074. this.loop = false;
  33075. this.useCustomAttenuation = false;
  33076. this.spatialSound = false;
  33077. this.refDistance = 1;
  33078. this.rolloffFactor = 1;
  33079. this.maxDistance = 100;
  33080. this.distanceModel = "linear";
  33081. this._panningModel = "equalpower";
  33082. this._playbackRate = 1;
  33083. this._streaming = false;
  33084. this._startTime = 0;
  33085. this._startOffset = 0;
  33086. this._position = BABYLON.Vector3.Zero();
  33087. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  33088. this._volume = 1;
  33089. this._isLoaded = false;
  33090. this._isReadyToPlay = false;
  33091. this.isPlaying = false;
  33092. this.isPaused = false;
  33093. this._isDirectional = false;
  33094. // Used if you'd like to create a directional sound.
  33095. // If not set, the sound will be omnidirectional
  33096. this._coneInnerAngle = 360;
  33097. this._coneOuterAngle = 360;
  33098. this._coneOuterGain = 0;
  33099. this._isOutputConnected = false;
  33100. this.name = name;
  33101. this._scene = scene;
  33102. this._readyToPlayCallback = readyToPlayCallback;
  33103. // Default custom attenuation function is a linear attenuation
  33104. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  33105. if (currentDistance < maxDistance) {
  33106. return currentVolume * (1 - currentDistance / maxDistance);
  33107. }
  33108. else {
  33109. return 0;
  33110. }
  33111. };
  33112. if (options) {
  33113. this.autoplay = options.autoplay || false;
  33114. this.loop = options.loop || false;
  33115. // if volume === 0, we need another way to check this option
  33116. if (options.volume !== undefined) {
  33117. this._volume = options.volume;
  33118. }
  33119. this.spatialSound = options.spatialSound || false;
  33120. this.maxDistance = options.maxDistance || 100;
  33121. this.useCustomAttenuation = options.useCustomAttenuation || false;
  33122. this.rolloffFactor = options.rolloffFactor || 1;
  33123. this.refDistance = options.refDistance || 1;
  33124. this.distanceModel = options.distanceModel || "linear";
  33125. this._playbackRate = options.playbackRate || 1;
  33126. this._streaming = options.streaming || false;
  33127. }
  33128. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33129. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  33130. this._soundGain.gain.value = this._volume;
  33131. this._inputAudioNode = this._soundGain;
  33132. this._ouputAudioNode = this._soundGain;
  33133. if (this.spatialSound) {
  33134. this._createSpatialParameters();
  33135. }
  33136. this._scene.mainSoundTrack.AddSound(this);
  33137. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  33138. if (urlOrArrayBuffer) {
  33139. // If it's an URL
  33140. if (typeof (urlOrArrayBuffer) === "string") {
  33141. // Loading sound using XHR2
  33142. if (!this._streaming) {
  33143. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  33144. }
  33145. else {
  33146. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  33147. this._htmlAudioElement.controls = false;
  33148. this._htmlAudioElement.loop = this.loop;
  33149. this._htmlAudioElement.crossOrigin = "anonymous";
  33150. this._htmlAudioElement.preload = "auto";
  33151. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  33152. _this._isReadyToPlay = true;
  33153. if (_this.autoplay) {
  33154. _this.play();
  33155. }
  33156. if (_this._readyToPlayCallback) {
  33157. _this._readyToPlayCallback();
  33158. }
  33159. });
  33160. document.body.appendChild(this._htmlAudioElement);
  33161. }
  33162. }
  33163. else {
  33164. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  33165. if (urlOrArrayBuffer.byteLength > 0) {
  33166. this._soundLoaded(urlOrArrayBuffer);
  33167. }
  33168. }
  33169. else {
  33170. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  33171. }
  33172. }
  33173. }
  33174. }
  33175. else {
  33176. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  33177. this._scene.mainSoundTrack.AddSound(this);
  33178. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  33179. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  33180. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  33181. }
  33182. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  33183. if (this._readyToPlayCallback) {
  33184. window.setTimeout(function () {
  33185. _this._readyToPlayCallback();
  33186. }, 1000);
  33187. }
  33188. }
  33189. }
  33190. Sound.prototype.dispose = function () {
  33191. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  33192. if (this.isPlaying) {
  33193. this.stop();
  33194. }
  33195. this._isReadyToPlay = false;
  33196. if (this.soundTrackId === -1) {
  33197. this._scene.mainSoundTrack.RemoveSound(this);
  33198. }
  33199. else {
  33200. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  33201. }
  33202. if (this._soundGain) {
  33203. this._soundGain.disconnect();
  33204. this._soundGain = null;
  33205. }
  33206. if (this._soundPanner) {
  33207. this._soundPanner.disconnect();
  33208. this._soundPanner = null;
  33209. }
  33210. if (this._soundSource) {
  33211. this._soundSource.disconnect();
  33212. this._soundSource = null;
  33213. }
  33214. this._audioBuffer = null;
  33215. if (this._htmlAudioElement) {
  33216. this._htmlAudioElement.pause();
  33217. this._htmlAudioElement.src = "";
  33218. document.body.removeChild(this._htmlAudioElement);
  33219. }
  33220. if (this._connectedMesh) {
  33221. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33222. this._connectedMesh = null;
  33223. }
  33224. }
  33225. };
  33226. Sound.prototype._soundLoaded = function (audioData) {
  33227. var _this = this;
  33228. this._isLoaded = true;
  33229. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  33230. _this._audioBuffer = buffer;
  33231. _this._isReadyToPlay = true;
  33232. if (_this.autoplay) {
  33233. _this.play();
  33234. }
  33235. if (_this._readyToPlayCallback) {
  33236. _this._readyToPlayCallback();
  33237. }
  33238. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  33239. };
  33240. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  33241. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33242. this._audioBuffer = audioBuffer;
  33243. this._isReadyToPlay = true;
  33244. }
  33245. };
  33246. Sound.prototype.updateOptions = function (options) {
  33247. if (options) {
  33248. this.loop = options.loop || this.loop;
  33249. this.maxDistance = options.maxDistance || this.maxDistance;
  33250. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  33251. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  33252. this.refDistance = options.refDistance || this.refDistance;
  33253. this.distanceModel = options.distanceModel || this.distanceModel;
  33254. this._playbackRate = options.playbackRate || this._playbackRate;
  33255. this._updateSpatialParameters();
  33256. if (this.isPlaying) {
  33257. if (this._streaming) {
  33258. this._htmlAudioElement.playbackRate = this._playbackRate;
  33259. }
  33260. else {
  33261. this._soundSource.playbackRate.value = this._playbackRate;
  33262. }
  33263. }
  33264. }
  33265. };
  33266. Sound.prototype._createSpatialParameters = function () {
  33267. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33268. if (this._scene.headphone) {
  33269. this._panningModel = "HRTF";
  33270. }
  33271. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  33272. this._updateSpatialParameters();
  33273. this._soundPanner.connect(this._ouputAudioNode);
  33274. this._inputAudioNode = this._soundPanner;
  33275. }
  33276. };
  33277. Sound.prototype._updateSpatialParameters = function () {
  33278. if (this.spatialSound) {
  33279. if (this.useCustomAttenuation) {
  33280. // Tricks to disable in a way embedded Web Audio attenuation
  33281. this._soundPanner.distanceModel = "linear";
  33282. this._soundPanner.maxDistance = Number.MAX_VALUE;
  33283. this._soundPanner.refDistance = 1;
  33284. this._soundPanner.rolloffFactor = 1;
  33285. this._soundPanner.panningModel = this._panningModel;
  33286. }
  33287. else {
  33288. this._soundPanner.distanceModel = this.distanceModel;
  33289. this._soundPanner.maxDistance = this.maxDistance;
  33290. this._soundPanner.refDistance = this.refDistance;
  33291. this._soundPanner.rolloffFactor = this.rolloffFactor;
  33292. this._soundPanner.panningModel = this._panningModel;
  33293. }
  33294. }
  33295. };
  33296. Sound.prototype.switchPanningModelToHRTF = function () {
  33297. this._panningModel = "HRTF";
  33298. this._switchPanningModel();
  33299. };
  33300. Sound.prototype.switchPanningModelToEqualPower = function () {
  33301. this._panningModel = "equalpower";
  33302. this._switchPanningModel();
  33303. };
  33304. Sound.prototype._switchPanningModel = function () {
  33305. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33306. this._soundPanner.panningModel = this._panningModel;
  33307. }
  33308. };
  33309. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  33310. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33311. if (this._isOutputConnected) {
  33312. this._ouputAudioNode.disconnect();
  33313. }
  33314. this._ouputAudioNode.connect(soundTrackAudioNode);
  33315. this._isOutputConnected = true;
  33316. }
  33317. };
  33318. /**
  33319. * Transform this sound into a directional source
  33320. * @param coneInnerAngle Size of the inner cone in degree
  33321. * @param coneOuterAngle Size of the outer cone in degree
  33322. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  33323. */
  33324. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  33325. if (coneOuterAngle < coneInnerAngle) {
  33326. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  33327. return;
  33328. }
  33329. this._coneInnerAngle = coneInnerAngle;
  33330. this._coneOuterAngle = coneOuterAngle;
  33331. this._coneOuterGain = coneOuterGain;
  33332. this._isDirectional = true;
  33333. if (this.isPlaying && this.loop) {
  33334. this.stop();
  33335. this.play();
  33336. }
  33337. };
  33338. Sound.prototype.setPosition = function (newPosition) {
  33339. this._position = newPosition;
  33340. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  33341. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33342. }
  33343. };
  33344. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  33345. this._localDirection = newLocalDirection;
  33346. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  33347. this._updateDirection();
  33348. }
  33349. };
  33350. Sound.prototype._updateDirection = function () {
  33351. var mat = this._connectedMesh.getWorldMatrix();
  33352. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  33353. direction.normalize();
  33354. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  33355. };
  33356. Sound.prototype.updateDistanceFromListener = function () {
  33357. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  33358. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  33359. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  33360. }
  33361. };
  33362. Sound.prototype.setAttenuationFunction = function (callback) {
  33363. this._customAttenuationFunction = callback;
  33364. };
  33365. /**
  33366. * Play the sound
  33367. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  33368. */
  33369. Sound.prototype.play = function (time) {
  33370. var _this = this;
  33371. if (this._isReadyToPlay && this._scene.audioEnabled) {
  33372. try {
  33373. if (this._startOffset < 0) {
  33374. time = -this._startOffset;
  33375. this._startOffset = 0;
  33376. }
  33377. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33378. if (!this._soundSource || !this._streamingSource) {
  33379. if (this.spatialSound) {
  33380. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  33381. if (this._isDirectional) {
  33382. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  33383. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  33384. this._soundPanner.coneOuterGain = this._coneOuterGain;
  33385. if (this._connectedMesh) {
  33386. this._updateDirection();
  33387. }
  33388. else {
  33389. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  33390. }
  33391. }
  33392. }
  33393. }
  33394. if (this._streaming) {
  33395. if (!this._streamingSource) {
  33396. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  33397. this._htmlAudioElement.onended = function () { _this._onended(); };
  33398. this._htmlAudioElement.playbackRate = this._playbackRate;
  33399. }
  33400. this._streamingSource.disconnect();
  33401. this._streamingSource.connect(this._inputAudioNode);
  33402. this._htmlAudioElement.play();
  33403. }
  33404. else {
  33405. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  33406. this._soundSource.buffer = this._audioBuffer;
  33407. this._soundSource.connect(this._inputAudioNode);
  33408. this._soundSource.loop = this.loop;
  33409. this._soundSource.playbackRate.value = this._playbackRate;
  33410. this._soundSource.onended = function () { _this._onended(); };
  33411. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  33412. }
  33413. this._startTime = startTime;
  33414. this.isPlaying = true;
  33415. this.isPaused = false;
  33416. }
  33417. catch (ex) {
  33418. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  33419. }
  33420. }
  33421. };
  33422. Sound.prototype._onended = function () {
  33423. this.isPlaying = false;
  33424. if (this.onended) {
  33425. this.onended();
  33426. }
  33427. };
  33428. /**
  33429. * Stop the sound
  33430. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  33431. */
  33432. Sound.prototype.stop = function (time) {
  33433. if (this.isPlaying) {
  33434. if (this._streaming) {
  33435. this._htmlAudioElement.pause();
  33436. // Test needed for Firefox or it will generate an Invalid State Error
  33437. if (this._htmlAudioElement.currentTime > 0) {
  33438. this._htmlAudioElement.currentTime = 0;
  33439. }
  33440. }
  33441. else {
  33442. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  33443. this._soundSource.stop(stopTime);
  33444. if (!this.isPaused) {
  33445. this._startOffset = 0;
  33446. }
  33447. }
  33448. this.isPlaying = false;
  33449. }
  33450. };
  33451. Sound.prototype.pause = function () {
  33452. if (this.isPlaying) {
  33453. this.isPaused = true;
  33454. if (this._streaming) {
  33455. this._htmlAudioElement.pause();
  33456. }
  33457. else {
  33458. this.stop(0);
  33459. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  33460. }
  33461. }
  33462. };
  33463. Sound.prototype.setVolume = function (newVolume, time) {
  33464. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33465. if (time) {
  33466. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  33467. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  33468. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  33469. }
  33470. else {
  33471. this._soundGain.gain.value = newVolume;
  33472. }
  33473. }
  33474. this._volume = newVolume;
  33475. };
  33476. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  33477. this._playbackRate = newPlaybackRate;
  33478. if (this.isPlaying) {
  33479. if (this._streaming) {
  33480. this._htmlAudioElement.playbackRate = this._playbackRate;
  33481. }
  33482. else {
  33483. this._soundSource.playbackRate.value = this._playbackRate;
  33484. }
  33485. }
  33486. };
  33487. Sound.prototype.getVolume = function () {
  33488. return this._volume;
  33489. };
  33490. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  33491. var _this = this;
  33492. if (this._connectedMesh) {
  33493. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  33494. this._registerFunc = null;
  33495. }
  33496. this._connectedMesh = meshToConnectTo;
  33497. if (!this.spatialSound) {
  33498. this.spatialSound = true;
  33499. this._createSpatialParameters();
  33500. if (this.isPlaying && this.loop) {
  33501. this.stop();
  33502. this.play();
  33503. }
  33504. }
  33505. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  33506. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  33507. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  33508. };
  33509. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  33510. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  33511. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  33512. this._updateDirection();
  33513. }
  33514. };
  33515. Sound.prototype.clone = function () {
  33516. var _this = this;
  33517. if (!this._streaming) {
  33518. var setBufferAndRun = function () {
  33519. if (_this._isReadyToPlay) {
  33520. clonedSound._audioBuffer = _this.getAudioBuffer();
  33521. clonedSound._isReadyToPlay = true;
  33522. if (clonedSound.autoplay) {
  33523. clonedSound.play();
  33524. }
  33525. }
  33526. else {
  33527. window.setTimeout(setBufferAndRun, 300);
  33528. }
  33529. };
  33530. var currentOptions = {
  33531. autoplay: this.autoplay, loop: this.loop,
  33532. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  33533. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  33534. refDistance: this.refDistance, distanceModel: this.distanceModel
  33535. };
  33536. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  33537. if (this.useCustomAttenuation) {
  33538. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  33539. }
  33540. clonedSound.setPosition(this._position);
  33541. clonedSound.setPlaybackRate(this._playbackRate);
  33542. setBufferAndRun();
  33543. return clonedSound;
  33544. }
  33545. else {
  33546. return null;
  33547. }
  33548. };
  33549. Sound.prototype.getAudioBuffer = function () {
  33550. return this._audioBuffer;
  33551. };
  33552. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  33553. var soundName = parsedSound.name;
  33554. var soundUrl;
  33555. if (parsedSound.url) {
  33556. soundUrl = rootUrl + parsedSound.url;
  33557. }
  33558. else {
  33559. soundUrl = rootUrl + soundName;
  33560. }
  33561. var options = {
  33562. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  33563. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  33564. rolloffFactor: parsedSound.rolloffFactor,
  33565. refDistance: parsedSound.refDistance,
  33566. distanceModel: parsedSound.distanceModel,
  33567. playbackRate: parsedSound.playbackRate
  33568. };
  33569. var newSound;
  33570. if (!sourceSound) {
  33571. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  33572. scene._addPendingData(newSound);
  33573. }
  33574. else {
  33575. var setBufferAndRun = function () {
  33576. if (sourceSound._isReadyToPlay) {
  33577. newSound._audioBuffer = sourceSound.getAudioBuffer();
  33578. newSound._isReadyToPlay = true;
  33579. if (newSound.autoplay) {
  33580. newSound.play();
  33581. }
  33582. }
  33583. else {
  33584. window.setTimeout(setBufferAndRun, 300);
  33585. }
  33586. };
  33587. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  33588. setBufferAndRun();
  33589. }
  33590. if (parsedSound.position) {
  33591. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  33592. newSound.setPosition(soundPosition);
  33593. }
  33594. if (parsedSound.isDirectional) {
  33595. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  33596. if (parsedSound.localDirectionToMesh) {
  33597. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  33598. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  33599. }
  33600. }
  33601. if (parsedSound.connectedMeshId) {
  33602. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  33603. if (connectedMesh) {
  33604. newSound.attachToMesh(connectedMesh);
  33605. }
  33606. }
  33607. return newSound;
  33608. };
  33609. return Sound;
  33610. })();
  33611. BABYLON.Sound = Sound;
  33612. })(BABYLON || (BABYLON = {}));
  33613. var BABYLON;
  33614. (function (BABYLON) {
  33615. var SoundTrack = (function () {
  33616. function SoundTrack(scene, options) {
  33617. this.id = -1;
  33618. this._isMainTrack = false;
  33619. this._isInitialized = false;
  33620. this._scene = scene;
  33621. this.soundCollection = new Array();
  33622. this._options = options;
  33623. if (!this._isMainTrack) {
  33624. this._scene.soundTracks.push(this);
  33625. this.id = this._scene.soundTracks.length - 1;
  33626. }
  33627. }
  33628. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  33629. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33630. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  33631. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  33632. if (this._options) {
  33633. if (this._options.volume) {
  33634. this._outputAudioNode.gain.value = this._options.volume;
  33635. }
  33636. if (this._options.mainTrack) {
  33637. this._isMainTrack = this._options.mainTrack;
  33638. }
  33639. }
  33640. this._isInitialized = true;
  33641. }
  33642. };
  33643. SoundTrack.prototype.dispose = function () {
  33644. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33645. if (this._connectedAnalyser) {
  33646. this._connectedAnalyser.stopDebugCanvas();
  33647. }
  33648. while (this.soundCollection.length) {
  33649. this.soundCollection[0].dispose();
  33650. }
  33651. if (this._outputAudioNode) {
  33652. this._outputAudioNode.disconnect();
  33653. }
  33654. this._outputAudioNode = null;
  33655. }
  33656. };
  33657. SoundTrack.prototype.AddSound = function (sound) {
  33658. if (!this._isInitialized) {
  33659. this._initializeSoundTrackAudioGraph();
  33660. }
  33661. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33662. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  33663. }
  33664. if (sound.soundTrackId) {
  33665. if (sound.soundTrackId === -1) {
  33666. this._scene.mainSoundTrack.RemoveSound(sound);
  33667. }
  33668. else {
  33669. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  33670. }
  33671. }
  33672. this.soundCollection.push(sound);
  33673. sound.soundTrackId = this.id;
  33674. };
  33675. SoundTrack.prototype.RemoveSound = function (sound) {
  33676. var index = this.soundCollection.indexOf(sound);
  33677. if (index !== -1) {
  33678. this.soundCollection.splice(index, 1);
  33679. }
  33680. };
  33681. SoundTrack.prototype.setVolume = function (newVolume) {
  33682. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33683. this._outputAudioNode.gain.value = newVolume;
  33684. }
  33685. };
  33686. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  33687. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33688. for (var i = 0; i < this.soundCollection.length; i++) {
  33689. this.soundCollection[i].switchPanningModelToHRTF();
  33690. }
  33691. }
  33692. };
  33693. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  33694. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33695. for (var i = 0; i < this.soundCollection.length; i++) {
  33696. this.soundCollection[i].switchPanningModelToEqualPower();
  33697. }
  33698. }
  33699. };
  33700. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  33701. if (this._connectedAnalyser) {
  33702. this._connectedAnalyser.stopDebugCanvas();
  33703. }
  33704. this._connectedAnalyser = analyser;
  33705. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  33706. this._outputAudioNode.disconnect();
  33707. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  33708. }
  33709. };
  33710. return SoundTrack;
  33711. })();
  33712. BABYLON.SoundTrack = SoundTrack;
  33713. })(BABYLON || (BABYLON = {}));
  33714. var BABYLON;
  33715. (function (BABYLON) {
  33716. var SIMDVector3 = (function () {
  33717. function SIMDVector3() {
  33718. }
  33719. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  33720. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  33721. var m0 = SIMD.float32x4.load(transformation.m, 0);
  33722. var m1 = SIMD.float32x4.load(transformation.m, 4);
  33723. var m2 = SIMD.float32x4.load(transformation.m, 8);
  33724. var m3 = SIMD.float32x4.load(transformation.m, 12);
  33725. 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));
  33726. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  33727. SIMD.float32x4.storeXYZ(result._data, 0, r);
  33728. };
  33729. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  33730. var v0 = SIMD.float32x4.splat(x);
  33731. var v1 = SIMD.float32x4.splat(y);
  33732. var v2 = SIMD.float32x4.splat(z);
  33733. var m0 = SIMD.float32x4.load(transformation.m, 0);
  33734. var m1 = SIMD.float32x4.load(transformation.m, 4);
  33735. var m2 = SIMD.float32x4.load(transformation.m, 8);
  33736. var m3 = SIMD.float32x4.load(transformation.m, 12);
  33737. 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));
  33738. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  33739. SIMD.float32x4.storeXYZ(result._data, 0, r);
  33740. };
  33741. return SIMDVector3;
  33742. })();
  33743. BABYLON.SIMDVector3 = SIMDVector3;
  33744. var SIMDMatrix = (function () {
  33745. function SIMDMatrix() {
  33746. }
  33747. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  33748. if (offset === void 0) { offset = 0; }
  33749. var tm = this.m;
  33750. var om = other.m;
  33751. var om0 = SIMD.float32x4.load(om, 0);
  33752. var om1 = SIMD.float32x4.load(om, 4);
  33753. var om2 = SIMD.float32x4.load(om, 8);
  33754. var om3 = SIMD.float32x4.load(om, 12);
  33755. var tm0 = SIMD.float32x4.load(tm, 0);
  33756. 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)))));
  33757. var tm1 = SIMD.float32x4.load(tm, 4);
  33758. 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)))));
  33759. var tm2 = SIMD.float32x4.load(tm, 8);
  33760. 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)))));
  33761. var tm3 = SIMD.float32x4.load(tm, 12);
  33762. 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)))));
  33763. };
  33764. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  33765. var src = this.m;
  33766. var dest = other.m;
  33767. var row0, row1, row2, row3;
  33768. var tmp1;
  33769. var minor0, minor1, minor2, minor3;
  33770. var det;
  33771. // Load the 4 rows
  33772. var src0 = SIMD.float32x4.load(src, 0);
  33773. var src1 = SIMD.float32x4.load(src, 4);
  33774. var src2 = SIMD.float32x4.load(src, 8);
  33775. var src3 = SIMD.float32x4.load(src, 12);
  33776. // Transpose the source matrix. Sort of. Not a true transpose operation
  33777. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  33778. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  33779. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  33780. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  33781. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  33782. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  33783. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  33784. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  33785. // This is a true transposition, but it will lead to an incorrect result
  33786. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  33787. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  33788. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  33789. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  33790. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  33791. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  33792. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  33793. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  33794. // ----
  33795. tmp1 = SIMD.float32x4.mul(row2, row3);
  33796. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33797. minor0 = SIMD.float32x4.mul(row1, tmp1);
  33798. minor1 = SIMD.float32x4.mul(row0, tmp1);
  33799. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33800. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  33801. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  33802. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  33803. // ----
  33804. tmp1 = SIMD.float32x4.mul(row1, row2);
  33805. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33806. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  33807. minor3 = SIMD.float32x4.mul(row0, tmp1);
  33808. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33809. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  33810. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  33811. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  33812. // ----
  33813. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  33814. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33815. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  33816. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  33817. minor2 = SIMD.float32x4.mul(row0, tmp1);
  33818. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33819. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  33820. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  33821. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  33822. // ----
  33823. tmp1 = SIMD.float32x4.mul(row0, row1);
  33824. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33825. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  33826. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  33827. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33828. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  33829. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  33830. // ----
  33831. tmp1 = SIMD.float32x4.mul(row0, row3);
  33832. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33833. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  33834. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  33835. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33836. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  33837. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  33838. // ----
  33839. tmp1 = SIMD.float32x4.mul(row0, row2);
  33840. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  33841. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  33842. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  33843. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  33844. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  33845. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  33846. // Compute determinant
  33847. det = SIMD.float32x4.mul(row0, minor0);
  33848. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  33849. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  33850. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  33851. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  33852. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  33853. // These shuffles aren't necessary if the faulty transposition is done
  33854. // up at the top of this function.
  33855. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  33856. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  33857. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  33858. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  33859. // Compute final values by multiplying with 1/det
  33860. minor0 = SIMD.float32x4.mul(det, minor0);
  33861. minor1 = SIMD.float32x4.mul(det, minor1);
  33862. minor2 = SIMD.float32x4.mul(det, minor2);
  33863. minor3 = SIMD.float32x4.mul(det, minor3);
  33864. SIMD.float32x4.store(dest, 0, minor0);
  33865. SIMD.float32x4.store(dest, 4, minor1);
  33866. SIMD.float32x4.store(dest, 8, minor2);
  33867. SIMD.float32x4.store(dest, 12, minor3);
  33868. return this;
  33869. };
  33870. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  33871. var out = result.m;
  33872. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  33873. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  33874. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  33875. // cc.kmVec3Subtract(f, pCenter, pEye);
  33876. var f = SIMD.float32x4.sub(center, eye);
  33877. // cc.kmVec3Normalize(f, f);
  33878. var tmp = SIMD.float32x4.mul(f, f);
  33879. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  33880. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  33881. // cc.kmVec3Assign(up, pUp);
  33882. // cc.kmVec3Normalize(up, up);
  33883. tmp = SIMD.float32x4.mul(up, up);
  33884. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  33885. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  33886. // cc.kmVec3Cross(s, f, up);
  33887. 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)));
  33888. // cc.kmVec3Normalize(s, s);
  33889. tmp = SIMD.float32x4.mul(s, s);
  33890. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  33891. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  33892. // cc.kmVec3Cross(u, s, f);
  33893. 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)));
  33894. // cc.kmVec3Normalize(s, s);
  33895. tmp = SIMD.float32x4.mul(s, s);
  33896. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  33897. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  33898. var zero = SIMD.float32x4.splat(0.0);
  33899. s = SIMD.float32x4.neg(s);
  33900. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  33901. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  33902. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  33903. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  33904. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  33905. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  33906. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  33907. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  33908. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  33909. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  33910. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  33911. var b3 = SIMD.float32x4.neg(eye);
  33912. b3 = SIMD.float32x4.withW(b3, 1.0);
  33913. 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)))));
  33914. 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)))));
  33915. 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)))));
  33916. 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)))));
  33917. };
  33918. return SIMDMatrix;
  33919. })();
  33920. BABYLON.SIMDMatrix = SIMDMatrix;
  33921. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  33922. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  33923. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  33924. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  33925. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  33926. var SIMDHelper = (function () {
  33927. function SIMDHelper() {
  33928. }
  33929. Object.defineProperty(SIMDHelper, "IsEnabled", {
  33930. get: function () {
  33931. return SIMDHelper._isEnabled;
  33932. },
  33933. enumerable: true,
  33934. configurable: true
  33935. });
  33936. SIMDHelper.DisableSIMD = function () {
  33937. // Replace functions
  33938. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  33939. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  33940. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  33941. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  33942. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  33943. SIMDHelper._isEnabled = false;
  33944. };
  33945. SIMDHelper.EnableSIMD = function () {
  33946. if (window.SIMD === undefined) {
  33947. return;
  33948. }
  33949. // Replace functions
  33950. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  33951. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  33952. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  33953. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  33954. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  33955. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  33956. get: function () { return this._data[0]; },
  33957. set: function (value) {
  33958. if (!this._data) {
  33959. this._data = new Float32Array(3);
  33960. }
  33961. this._data[0] = value;
  33962. }
  33963. });
  33964. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  33965. get: function () { return this._data[1]; },
  33966. set: function (value) {
  33967. this._data[1] = value;
  33968. }
  33969. });
  33970. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  33971. get: function () { return this._data[2]; },
  33972. set: function (value) {
  33973. this._data[2] = value;
  33974. }
  33975. });
  33976. SIMDHelper._isEnabled = true;
  33977. };
  33978. SIMDHelper._isEnabled = false;
  33979. return SIMDHelper;
  33980. })();
  33981. BABYLON.SIMDHelper = SIMDHelper;
  33982. })(BABYLON || (BABYLON = {}));
  33983. var BABYLON;
  33984. (function (BABYLON) {
  33985. var ShaderMaterial = (function (_super) {
  33986. __extends(ShaderMaterial, _super);
  33987. function ShaderMaterial(name, scene, shaderPath, options) {
  33988. _super.call(this, name, scene);
  33989. this._textures = {};
  33990. this._floats = {};
  33991. this._floatsArrays = {};
  33992. this._colors3 = {};
  33993. this._colors4 = {};
  33994. this._vectors2 = {};
  33995. this._vectors3 = {};
  33996. this._vectors4 = {};
  33997. this._matrices = {};
  33998. this._matrices3x3 = {};
  33999. this._matrices2x2 = {};
  34000. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  34001. this._shaderPath = shaderPath;
  34002. options.needAlphaBlending = options.needAlphaBlending || false;
  34003. options.needAlphaTesting = options.needAlphaTesting || false;
  34004. options.attributes = options.attributes || ["position", "normal", "uv"];
  34005. options.uniforms = options.uniforms || ["worldViewProjection"];
  34006. options.samplers = options.samplers || [];
  34007. options.defines = options.defines || [];
  34008. this._options = options;
  34009. }
  34010. ShaderMaterial.prototype.needAlphaBlending = function () {
  34011. return this._options.needAlphaBlending;
  34012. };
  34013. ShaderMaterial.prototype.needAlphaTesting = function () {
  34014. return this._options.needAlphaTesting;
  34015. };
  34016. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  34017. if (this._options.uniforms.indexOf(uniformName) === -1) {
  34018. this._options.uniforms.push(uniformName);
  34019. }
  34020. };
  34021. ShaderMaterial.prototype.setTexture = function (name, texture) {
  34022. if (this._options.samplers.indexOf(name) === -1) {
  34023. this._options.samplers.push(name);
  34024. }
  34025. this._textures[name] = texture;
  34026. return this;
  34027. };
  34028. ShaderMaterial.prototype.setFloat = function (name, value) {
  34029. this._checkUniform(name);
  34030. this._floats[name] = value;
  34031. return this;
  34032. };
  34033. ShaderMaterial.prototype.setFloats = function (name, value) {
  34034. this._checkUniform(name);
  34035. this._floatsArrays[name] = value;
  34036. return this;
  34037. };
  34038. ShaderMaterial.prototype.setColor3 = function (name, value) {
  34039. this._checkUniform(name);
  34040. this._colors3[name] = value;
  34041. return this;
  34042. };
  34043. ShaderMaterial.prototype.setColor4 = function (name, value) {
  34044. this._checkUniform(name);
  34045. this._colors4[name] = value;
  34046. return this;
  34047. };
  34048. ShaderMaterial.prototype.setVector2 = function (name, value) {
  34049. this._checkUniform(name);
  34050. this._vectors2[name] = value;
  34051. return this;
  34052. };
  34053. ShaderMaterial.prototype.setVector3 = function (name, value) {
  34054. this._checkUniform(name);
  34055. this._vectors3[name] = value;
  34056. return this;
  34057. };
  34058. ShaderMaterial.prototype.setVector4 = function (name, value) {
  34059. this._checkUniform(name);
  34060. this._vectors4[name] = value;
  34061. return this;
  34062. };
  34063. ShaderMaterial.prototype.setMatrix = function (name, value) {
  34064. this._checkUniform(name);
  34065. this._matrices[name] = value;
  34066. return this;
  34067. };
  34068. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  34069. this._checkUniform(name);
  34070. this._matrices3x3[name] = value;
  34071. return this;
  34072. };
  34073. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  34074. this._checkUniform(name);
  34075. this._matrices2x2[name] = value;
  34076. return this;
  34077. };
  34078. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  34079. var scene = this.getScene();
  34080. var engine = scene.getEngine();
  34081. if (!this.checkReadyOnEveryCall) {
  34082. if (this._renderId === scene.getRenderId()) {
  34083. return true;
  34084. }
  34085. }
  34086. // Instances
  34087. var defines = [];
  34088. var fallbacks = new BABYLON.EffectFallbacks();
  34089. if (useInstances) {
  34090. defines.push("#define INSTANCES");
  34091. }
  34092. for (var index = 0; index < this._options.defines.length; index++) {
  34093. defines.push(this._options.defines[index]);
  34094. }
  34095. // Bones
  34096. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  34097. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  34098. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  34099. fallbacks.addCPUSkinningFallback(0, mesh);
  34100. }
  34101. // Alpha test
  34102. if (engine.getAlphaTesting()) {
  34103. defines.push("#define ALPHATEST");
  34104. }
  34105. var previousEffect = this._effect;
  34106. var join = defines.join("\n");
  34107. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  34108. if (!this._effect.isReady()) {
  34109. return false;
  34110. }
  34111. if (previousEffect !== this._effect) {
  34112. scene.resetCachedMaterial();
  34113. }
  34114. this._renderId = scene.getRenderId();
  34115. return true;
  34116. };
  34117. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34118. var scene = this.getScene();
  34119. if (this._options.uniforms.indexOf("world") !== -1) {
  34120. this._effect.setMatrix("world", world);
  34121. }
  34122. if (this._options.uniforms.indexOf("worldView") !== -1) {
  34123. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  34124. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  34125. }
  34126. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  34127. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  34128. }
  34129. };
  34130. ShaderMaterial.prototype.bind = function (world, mesh) {
  34131. // Std values
  34132. this.bindOnlyWorldMatrix(world);
  34133. if (this.getScene().getCachedMaterial() !== this) {
  34134. if (this._options.uniforms.indexOf("view") !== -1) {
  34135. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  34136. }
  34137. if (this._options.uniforms.indexOf("projection") !== -1) {
  34138. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  34139. }
  34140. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  34141. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  34142. }
  34143. // Bones
  34144. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  34145. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  34146. }
  34147. // Texture
  34148. for (var name in this._textures) {
  34149. this._effect.setTexture(name, this._textures[name]);
  34150. }
  34151. // Float
  34152. for (name in this._floats) {
  34153. this._effect.setFloat(name, this._floats[name]);
  34154. }
  34155. // Float s
  34156. for (name in this._floatsArrays) {
  34157. this._effect.setArray(name, this._floatsArrays[name]);
  34158. }
  34159. // Color3
  34160. for (name in this._colors3) {
  34161. this._effect.setColor3(name, this._colors3[name]);
  34162. }
  34163. // Color4
  34164. for (name in this._colors4) {
  34165. var color = this._colors4[name];
  34166. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  34167. }
  34168. // Vector2
  34169. for (name in this._vectors2) {
  34170. this._effect.setVector2(name, this._vectors2[name]);
  34171. }
  34172. // Vector3
  34173. for (name in this._vectors3) {
  34174. this._effect.setVector3(name, this._vectors3[name]);
  34175. }
  34176. // Vector4
  34177. for (name in this._vectors4) {
  34178. this._effect.setVector4(name, this._vectors4[name]);
  34179. }
  34180. // Matrix
  34181. for (name in this._matrices) {
  34182. this._effect.setMatrix(name, this._matrices[name]);
  34183. }
  34184. // Matrix 3x3
  34185. for (name in this._matrices3x3) {
  34186. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  34187. }
  34188. // Matrix 2x2
  34189. for (name in this._matrices2x2) {
  34190. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  34191. }
  34192. }
  34193. _super.prototype.bind.call(this, world, mesh);
  34194. };
  34195. ShaderMaterial.prototype.clone = function (name) {
  34196. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  34197. return newShaderMaterial;
  34198. };
  34199. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  34200. for (var name in this._textures) {
  34201. this._textures[name].dispose();
  34202. }
  34203. this._textures = {};
  34204. _super.prototype.dispose.call(this, forceDisposeEffect);
  34205. };
  34206. ShaderMaterial.prototype.serialize = function () {
  34207. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  34208. serializationObject.customType = "BABYLON.ShaderMaterial";
  34209. serializationObject.options = this._options;
  34210. serializationObject.shaderPath = this._shaderPath;
  34211. // Texture
  34212. serializationObject.textures = {};
  34213. for (var name in this._textures) {
  34214. serializationObject.textures[name] = this._textures[name].serialize();
  34215. }
  34216. // Float
  34217. serializationObject.floats = {};
  34218. for (name in this._floats) {
  34219. serializationObject.floats[name] = this._floats[name];
  34220. }
  34221. // Float s
  34222. serializationObject.floatArrays = {};
  34223. for (name in this._floatsArrays) {
  34224. serializationObject.floatArrays[name] = this._floatsArrays[name];
  34225. }
  34226. // Color3
  34227. serializationObject.colors3 = {};
  34228. for (name in this._colors3) {
  34229. serializationObject.colors3[name] = this._colors3[name].asArray();
  34230. }
  34231. // Color4
  34232. serializationObject.colors4 = {};
  34233. for (name in this._colors4) {
  34234. serializationObject.colors4[name] = this._colors4[name].asArray();
  34235. }
  34236. // Vector2
  34237. serializationObject.vectors2 = {};
  34238. for (name in this._vectors2) {
  34239. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  34240. }
  34241. // Vector3
  34242. serializationObject.vectors3 = {};
  34243. for (name in this._vectors3) {
  34244. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  34245. }
  34246. // Vector4
  34247. serializationObject.vectors4 = {};
  34248. for (name in this._vectors4) {
  34249. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  34250. }
  34251. // Matrix
  34252. serializationObject.matrices = {};
  34253. for (name in this._matrices) {
  34254. serializationObject.matrices[name] = this._matrices[name].asArray();
  34255. }
  34256. // Matrix 3x3
  34257. serializationObject.matrices3x3 = {};
  34258. for (name in this._matrices3x3) {
  34259. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  34260. }
  34261. // Matrix 2x2
  34262. serializationObject.matrices2x2 = {};
  34263. for (name in this._matrices2x2) {
  34264. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  34265. }
  34266. return serializationObject;
  34267. };
  34268. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  34269. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  34270. // Texture
  34271. for (var name in source.textures) {
  34272. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  34273. }
  34274. // Float
  34275. for (name in source.floats) {
  34276. material.setFloat(name, source.floats[name]);
  34277. }
  34278. // Float s
  34279. for (name in source.floatsArrays) {
  34280. material.setFloats(name, source.floatsArrays[name]);
  34281. }
  34282. // Color3
  34283. for (name in source.colors3) {
  34284. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  34285. }
  34286. // Color4
  34287. for (name in source.colors4) {
  34288. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  34289. }
  34290. // Vector2
  34291. for (name in source.vectors2) {
  34292. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  34293. }
  34294. // Vector3
  34295. for (name in source.vectors3) {
  34296. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  34297. }
  34298. // Vector4
  34299. for (name in source.vectors4) {
  34300. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  34301. }
  34302. // Matrix
  34303. for (name in source.matrices) {
  34304. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  34305. }
  34306. // Matrix 3x3
  34307. for (name in source.matrices3x3) {
  34308. material.setMatrix3x3(name, source.matrices3x3[name]);
  34309. }
  34310. // Matrix 2x2
  34311. for (name in source.matrices2x2) {
  34312. material.setMatrix2x2(name, source.matrices2x2[name]);
  34313. }
  34314. return material;
  34315. };
  34316. return ShaderMaterial;
  34317. })(BABYLON.Material);
  34318. BABYLON.ShaderMaterial = ShaderMaterial;
  34319. })(BABYLON || (BABYLON = {}));
  34320. var BABYLON;
  34321. (function (BABYLON) {
  34322. var Internals;
  34323. (function (Internals) {
  34324. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  34325. // All values and structures referenced from:
  34326. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  34327. var DDS_MAGIC = 0x20534444;
  34328. 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;
  34329. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  34330. 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;
  34331. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  34332. function FourCCToInt32(value) {
  34333. return value.charCodeAt(0) +
  34334. (value.charCodeAt(1) << 8) +
  34335. (value.charCodeAt(2) << 16) +
  34336. (value.charCodeAt(3) << 24);
  34337. }
  34338. function Int32ToFourCC(value) {
  34339. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  34340. }
  34341. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  34342. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  34343. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  34344. var headerLengthInt = 31; // The header length in 32 bit ints
  34345. // Offsets into the header array
  34346. var off_magic = 0;
  34347. var off_size = 1;
  34348. var off_flags = 2;
  34349. var off_height = 3;
  34350. var off_width = 4;
  34351. var off_mipmapCount = 7;
  34352. var off_pfFlags = 20;
  34353. var off_pfFourCC = 21;
  34354. var off_RGBbpp = 22;
  34355. var off_RMask = 23;
  34356. var off_GMask = 24;
  34357. var off_BMask = 25;
  34358. var off_AMask = 26;
  34359. var off_caps1 = 27;
  34360. var off_caps2 = 28;
  34361. ;
  34362. var DDSTools = (function () {
  34363. function DDSTools() {
  34364. }
  34365. DDSTools.GetDDSInfo = function (arrayBuffer) {
  34366. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  34367. var mipmapCount = 1;
  34368. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  34369. mipmapCount = Math.max(1, header[off_mipmapCount]);
  34370. }
  34371. return {
  34372. width: header[off_width],
  34373. height: header[off_height],
  34374. mipmapCount: mipmapCount,
  34375. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  34376. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  34377. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  34378. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  34379. };
  34380. };
  34381. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34382. var byteArray = new Uint8Array(dataLength);
  34383. var srcData = new Uint8Array(arrayBuffer);
  34384. var index = 0;
  34385. for (var y = height - 1; y >= 0; y--) {
  34386. for (var x = 0; x < width; x++) {
  34387. var srcPos = dataOffset + (x + y * width) * 4;
  34388. byteArray[index + 2] = srcData[srcPos];
  34389. byteArray[index + 1] = srcData[srcPos + 1];
  34390. byteArray[index] = srcData[srcPos + 2];
  34391. byteArray[index + 3] = srcData[srcPos + 3];
  34392. index += 4;
  34393. }
  34394. }
  34395. return byteArray;
  34396. };
  34397. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34398. var byteArray = new Uint8Array(dataLength);
  34399. var srcData = new Uint8Array(arrayBuffer);
  34400. var index = 0;
  34401. for (var y = height - 1; y >= 0; y--) {
  34402. for (var x = 0; x < width; x++) {
  34403. var srcPos = dataOffset + (x + y * width) * 3;
  34404. byteArray[index + 2] = srcData[srcPos];
  34405. byteArray[index + 1] = srcData[srcPos + 1];
  34406. byteArray[index] = srcData[srcPos + 2];
  34407. index += 3;
  34408. }
  34409. }
  34410. return byteArray;
  34411. };
  34412. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  34413. var byteArray = new Uint8Array(dataLength);
  34414. var srcData = new Uint8Array(arrayBuffer);
  34415. var index = 0;
  34416. for (var y = height - 1; y >= 0; y--) {
  34417. for (var x = 0; x < width; x++) {
  34418. var srcPos = dataOffset + (x + y * width);
  34419. byteArray[index] = srcData[srcPos];
  34420. index++;
  34421. }
  34422. }
  34423. return byteArray;
  34424. };
  34425. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  34426. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  34427. if (header[off_magic] != DDS_MAGIC) {
  34428. BABYLON.Tools.Error("Invalid magic number in DDS header");
  34429. return;
  34430. }
  34431. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  34432. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  34433. return;
  34434. }
  34435. if (info.isFourCC) {
  34436. fourCC = header[off_pfFourCC];
  34437. switch (fourCC) {
  34438. case FOURCC_DXT1:
  34439. blockBytes = 8;
  34440. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  34441. break;
  34442. case FOURCC_DXT3:
  34443. blockBytes = 16;
  34444. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  34445. break;
  34446. case FOURCC_DXT5:
  34447. blockBytes = 16;
  34448. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  34449. break;
  34450. default:
  34451. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  34452. return;
  34453. }
  34454. }
  34455. mipmapCount = 1;
  34456. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  34457. mipmapCount = Math.max(1, header[off_mipmapCount]);
  34458. }
  34459. var bpp = header[off_RGBbpp];
  34460. for (var face = 0; face < faces; face++) {
  34461. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  34462. width = header[off_width];
  34463. height = header[off_height];
  34464. dataOffset = header[off_size] + 4;
  34465. for (i = 0; i < mipmapCount; ++i) {
  34466. if (info.isRGB) {
  34467. if (bpp === 24) {
  34468. dataLength = width * height * 3;
  34469. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34470. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  34471. }
  34472. else {
  34473. dataLength = width * height * 4;
  34474. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34475. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  34476. }
  34477. }
  34478. else if (info.isLuminance) {
  34479. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  34480. var unpaddedRowSize = width;
  34481. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  34482. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  34483. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  34484. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  34485. }
  34486. else {
  34487. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  34488. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  34489. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  34490. }
  34491. dataOffset += dataLength;
  34492. width *= 0.5;
  34493. height *= 0.5;
  34494. width = Math.max(1.0, width);
  34495. height = Math.max(1.0, height);
  34496. }
  34497. }
  34498. };
  34499. return DDSTools;
  34500. })();
  34501. Internals.DDSTools = DDSTools;
  34502. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34503. })(BABYLON || (BABYLON = {}));
  34504. var BABYLON;
  34505. (function (BABYLON) {
  34506. var CannonJSPlugin = (function () {
  34507. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  34508. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  34509. if (iterations === void 0) { iterations = 10; }
  34510. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  34511. this.name = "CannonJSPlugin";
  34512. this._physicsMaterials = [];
  34513. this._fixedTimeStep = 1 / 60;
  34514. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  34515. this._currentCollisionGroup = 2;
  34516. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  34517. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  34518. this._tmpPosition = BABYLON.Vector3.Zero();
  34519. this._tmpQuaternion = new BABYLON.Quaternion();
  34520. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  34521. this._tmpDeltaRotation = new BABYLON.Quaternion();
  34522. this._tmpUnityRotation = new BABYLON.Quaternion();
  34523. if (!this.isSupported()) {
  34524. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  34525. return;
  34526. }
  34527. this.world = new CANNON.World();
  34528. this.world.broadphase = new CANNON.NaiveBroadphase();
  34529. this.world.solver.iterations = iterations;
  34530. }
  34531. CannonJSPlugin.prototype.setGravity = function (gravity) {
  34532. this.world.gravity.copy(gravity);
  34533. };
  34534. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  34535. this._fixedTimeStep = timeStep;
  34536. };
  34537. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  34538. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  34539. };
  34540. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  34541. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  34542. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  34543. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  34544. };
  34545. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  34546. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  34547. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  34548. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  34549. };
  34550. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  34551. //parent-child relationship. Does this impostor has a parent impostor?
  34552. if (impostor.parent) {
  34553. if (impostor.physicsBody) {
  34554. this.removePhysicsBody(impostor);
  34555. //TODO is that needed?
  34556. impostor.forceUpdate();
  34557. }
  34558. return;
  34559. }
  34560. //should a new body be created for this impostor?
  34561. if (impostor.isBodyInitRequired()) {
  34562. var shape = this._createShape(impostor);
  34563. //unregister events, if body is being changed
  34564. var oldBody = impostor.physicsBody;
  34565. if (oldBody) {
  34566. this.removePhysicsBody(impostor);
  34567. }
  34568. //create the body and material
  34569. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  34570. var bodyCreationObject = {
  34571. mass: impostor.getParam("mass"),
  34572. material: material
  34573. };
  34574. // A simple extend, in case native options were used.
  34575. var nativeOptions = impostor.getParam("nativeOptions");
  34576. for (var key in nativeOptions) {
  34577. if (nativeOptions.hasOwnProperty(key)) {
  34578. bodyCreationObject[key] = nativeOptions[key];
  34579. }
  34580. }
  34581. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  34582. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  34583. this.world.addEventListener("preStep", impostor.beforeStep);
  34584. this.world.addEventListener("postStep", impostor.afterStep);
  34585. impostor.physicsBody.addShape(shape);
  34586. this.world.add(impostor.physicsBody);
  34587. //try to keep the body moving in the right direction by taking old properties.
  34588. //Should be tested!
  34589. if (oldBody) {
  34590. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  34591. impostor.physicsBody[param].copy(oldBody[param]);
  34592. });
  34593. }
  34594. this._processChildMeshes(impostor);
  34595. }
  34596. //now update the body's transformation
  34597. this._updatePhysicsBodyTransformation(impostor);
  34598. };
  34599. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  34600. var _this = this;
  34601. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  34602. if (meshChildren.length) {
  34603. var processMesh = function (localPosition, mesh) {
  34604. var childImpostor = mesh.getPhysicsImpostor();
  34605. if (childImpostor) {
  34606. var parent = childImpostor.parent;
  34607. if (parent !== mainImpostor) {
  34608. var localPosition = mesh.position;
  34609. if (childImpostor.physicsBody) {
  34610. _this.removePhysicsBody(childImpostor);
  34611. childImpostor.physicsBody = null;
  34612. }
  34613. childImpostor.parent = mainImpostor;
  34614. childImpostor.resetUpdateFlags();
  34615. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  34616. //Add the mass of the children.
  34617. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  34618. }
  34619. }
  34620. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  34621. };
  34622. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  34623. }
  34624. };
  34625. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  34626. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  34627. this.world.removeEventListener("preStep", impostor.beforeStep);
  34628. this.world.removeEventListener("postStep", impostor.afterStep);
  34629. this.world.remove(impostor.physicsBody);
  34630. };
  34631. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  34632. var mainBody = impostorJoint.mainImpostor.physicsBody;
  34633. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  34634. if (!mainBody || !connectedBody) {
  34635. return;
  34636. }
  34637. var constraint;
  34638. var jointData = impostorJoint.joint.jointData;
  34639. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  34640. var constraintData = {
  34641. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  34642. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  34643. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  34644. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  34645. maxForce: jointData.nativeParams.maxForce,
  34646. collideConnected: !!jointData.collision
  34647. };
  34648. //Not needed, Cannon has a collideConnected flag
  34649. /*if (!jointData.collision) {
  34650. //add 1st body to a collision group of its own, if it is not in 1
  34651. if (mainBody.collisionFilterGroup === 1) {
  34652. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  34653. this._currentCollisionGroup <<= 1;
  34654. }
  34655. if (connectedBody.collisionFilterGroup === 1) {
  34656. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  34657. this._currentCollisionGroup <<= 1;
  34658. }
  34659. //add their mask to the collisionFilterMask of each other:
  34660. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  34661. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  34662. }*/
  34663. switch (impostorJoint.joint.type) {
  34664. case BABYLON.PhysicsJoint.HingeJoint:
  34665. case BABYLON.PhysicsJoint.Hinge2Joint:
  34666. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  34667. break;
  34668. case BABYLON.PhysicsJoint.DistanceJoint:
  34669. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  34670. break;
  34671. case BABYLON.PhysicsJoint.SpringJoint:
  34672. var springData = jointData;
  34673. constraint = new CANNON.Spring(mainBody, connectedBody, {
  34674. restLength: springData.length,
  34675. stiffness: springData.stiffness,
  34676. damping: springData.damping,
  34677. localAnchorA: constraintData.pivotA,
  34678. localAnchorB: constraintData.pivotB
  34679. });
  34680. break;
  34681. case BABYLON.PhysicsJoint.PointToPointJoint:
  34682. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  34683. default:
  34684. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  34685. break;
  34686. }
  34687. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  34688. constraint.collideConnected = !!jointData.collision;
  34689. impostorJoint.joint.physicsJoint = constraint;
  34690. //don't add spring as constraint, as it is not one.
  34691. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  34692. this.world.addConstraint(constraint);
  34693. }
  34694. else {
  34695. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  34696. constraint.applyForce();
  34697. });
  34698. }
  34699. };
  34700. CannonJSPlugin.prototype.removeJoint = function (joint) {
  34701. //TODO
  34702. };
  34703. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  34704. var index;
  34705. var mat;
  34706. for (index = 0; index < this._physicsMaterials.length; index++) {
  34707. mat = this._physicsMaterials[index];
  34708. if (mat.friction === friction && mat.restitution === restitution) {
  34709. return mat;
  34710. }
  34711. }
  34712. var currentMat = new CANNON.Material("mat");
  34713. currentMat.friction = friction;
  34714. currentMat.restitution = restitution;
  34715. this._physicsMaterials.push(currentMat);
  34716. return currentMat;
  34717. };
  34718. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  34719. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  34720. };
  34721. CannonJSPlugin.prototype._createShape = function (impostor) {
  34722. var object = impostor.object;
  34723. var returnValue;
  34724. var extendSize = impostor.getObjectExtendSize();
  34725. switch (impostor.type) {
  34726. case BABYLON.PhysicsEngine.SphereImpostor:
  34727. var radiusX = extendSize.x;
  34728. var radiusY = extendSize.y;
  34729. var radiusZ = extendSize.z;
  34730. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  34731. break;
  34732. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  34733. case BABYLON.PhysicsImpostor.CylinderImpostor:
  34734. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  34735. break;
  34736. case BABYLON.PhysicsImpostor.BoxImpostor:
  34737. var box = extendSize.scale(0.5);
  34738. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  34739. break;
  34740. case BABYLON.PhysicsImpostor.PlaneImpostor:
  34741. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  34742. returnValue = new CANNON.Plane();
  34743. break;
  34744. case BABYLON.PhysicsImpostor.MeshImpostor:
  34745. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  34746. var rawFaces = object.getIndices ? object.getIndices() : [];
  34747. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  34748. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  34749. break;
  34750. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  34751. returnValue = this._createHeightmap(object);
  34752. break;
  34753. case BABYLON.PhysicsImpostor.ParticleImpostor:
  34754. returnValue = new CANNON.Particle();
  34755. break;
  34756. }
  34757. return returnValue;
  34758. };
  34759. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  34760. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34761. var matrix = [];
  34762. //For now pointDepth will not be used and will be automatically calculated.
  34763. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  34764. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  34765. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  34766. var elementSize = dim * 2 / arraySize;
  34767. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  34768. for (var i = 0; i < pos.length; i = i + 3) {
  34769. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  34770. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  34771. var y = pos[i + 1] + minY;
  34772. if (!matrix[x]) {
  34773. matrix[x] = [];
  34774. }
  34775. if (!matrix[x][z]) {
  34776. matrix[x][z] = y;
  34777. }
  34778. matrix[x][z] = Math.max(y, matrix[x][z]);
  34779. }
  34780. for (var x = 0; x <= arraySize; ++x) {
  34781. if (!matrix[x]) {
  34782. var loc = 1;
  34783. while (!matrix[(x + loc) % arraySize]) {
  34784. loc++;
  34785. }
  34786. matrix[x] = matrix[(x + loc) % arraySize].slice();
  34787. }
  34788. for (var z = 0; z <= arraySize; ++z) {
  34789. if (!matrix[x][z]) {
  34790. var loc = 1;
  34791. var newValue;
  34792. while (newValue === undefined) {
  34793. newValue = matrix[x][(z + loc++) % arraySize];
  34794. }
  34795. matrix[x][z] = newValue;
  34796. }
  34797. }
  34798. }
  34799. var shape = new CANNON.Heightfield(matrix, {
  34800. elementSize: elementSize
  34801. });
  34802. //For future reference, needed for body transformation
  34803. shape.minY = minY;
  34804. return shape;
  34805. };
  34806. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  34807. var object = impostor.object;
  34808. //make sure it is updated...
  34809. object.computeWorldMatrix && object.computeWorldMatrix(true);
  34810. // The delta between the mesh position and the mesh bounding box center
  34811. var center = impostor.getObjectCenter();
  34812. var extendSize = impostor.getObjectExtendSize();
  34813. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  34814. this._tmpPosition.copyFrom(center);
  34815. var quaternion = object.rotationQuaternion;
  34816. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  34817. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  34818. //-90 DEG in X, precalculated
  34819. quaternion = quaternion.multiply(this._minus90X);
  34820. //Invert! (Precalculated, 90 deg in X)
  34821. //No need to clone. this will never change.
  34822. impostor.setDeltaRotation(this._plus90X);
  34823. }
  34824. //If it is a heightfield, if should be centered.
  34825. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  34826. var mesh = object;
  34827. //calculate the correct body position:
  34828. var rotationQuaternion = mesh.rotationQuaternion;
  34829. mesh.rotationQuaternion = this._tmpUnityRotation;
  34830. mesh.computeWorldMatrix(true);
  34831. //get original center with no rotation
  34832. var c = center.clone();
  34833. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  34834. //rotation is back
  34835. mesh.rotationQuaternion = rotationQuaternion;
  34836. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  34837. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  34838. mesh.setPivotMatrix(p);
  34839. mesh.computeWorldMatrix(true);
  34840. //calculate the translation
  34841. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  34842. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  34843. //add it inverted to the delta
  34844. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  34845. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  34846. mesh.setPivotMatrix(oldPivot);
  34847. mesh.computeWorldMatrix(true);
  34848. }
  34849. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  34850. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  34851. this._tmpPosition.copyFrom(object.position);
  34852. }
  34853. impostor.setDeltaPosition(this._tmpDeltaPosition);
  34854. //Now update the impostor object
  34855. impostor.physicsBody.position.copy(this._tmpPosition);
  34856. impostor.physicsBody.quaternion.copy(quaternion);
  34857. };
  34858. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  34859. impostor.object.position.copyFrom(impostor.physicsBody.position);
  34860. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  34861. };
  34862. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  34863. impostor.physicsBody.position.copy(newPosition);
  34864. impostor.physicsBody.quaternion.copy(newRotation);
  34865. };
  34866. CannonJSPlugin.prototype.isSupported = function () {
  34867. return window.CANNON !== undefined;
  34868. };
  34869. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  34870. impostor.physicsBody.velocity.copy(velocity);
  34871. };
  34872. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  34873. impostor.physicsBody.angularVelocity.copy(velocity);
  34874. };
  34875. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  34876. var v = impostor.physicsBody.velocity;
  34877. if (!v)
  34878. return null;
  34879. return new BABYLON.Vector3(v.x, v.y, v.z);
  34880. };
  34881. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  34882. var v = impostor.physicsBody.angularVelocity;
  34883. if (!v)
  34884. return null;
  34885. return new BABYLON.Vector3(v.x, v.y, v.z);
  34886. };
  34887. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  34888. impostor.physicsBody.mass = mass;
  34889. impostor.physicsBody.updateMassProperties();
  34890. };
  34891. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  34892. impostor.physicsBody.sleep();
  34893. };
  34894. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  34895. impostor.physicsBody.wakeUp();
  34896. };
  34897. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  34898. joint.physicsJoint.distance = maxDistance;
  34899. };
  34900. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  34901. if (!motorIndex) {
  34902. joint.physicsJoint.enableMotor();
  34903. }
  34904. };
  34905. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  34906. if (!motorIndex) {
  34907. joint.physicsJoint.disableMotor();
  34908. }
  34909. };
  34910. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  34911. if (!motorIndex) {
  34912. joint.physicsJoint.enableMotor();
  34913. joint.physicsJoint.setMotorSpeed(speed);
  34914. if (maxForce) {
  34915. this.setLimit(joint, maxForce);
  34916. }
  34917. }
  34918. };
  34919. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  34920. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  34921. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  34922. };
  34923. CannonJSPlugin.prototype.dispose = function () {
  34924. //nothing to do, actually.
  34925. };
  34926. return CannonJSPlugin;
  34927. })();
  34928. BABYLON.CannonJSPlugin = CannonJSPlugin;
  34929. })(BABYLON || (BABYLON = {}));
  34930. var BABYLON;
  34931. (function (BABYLON) {
  34932. var OimoJSPlugin = (function () {
  34933. function OimoJSPlugin(iterations) {
  34934. this.name = "OimoJSPlugin";
  34935. this._tmpImpostorsArray = [];
  34936. this._tmpPositionVector = BABYLON.Vector3.Zero();
  34937. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  34938. this.world.clear();
  34939. //making sure no stats are calculated
  34940. this.world.isNoStat = true;
  34941. }
  34942. OimoJSPlugin.prototype.setGravity = function (gravity) {
  34943. this.world.gravity.copy(gravity);
  34944. };
  34945. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  34946. this.world.timeStep = timeStep;
  34947. };
  34948. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  34949. var _this = this;
  34950. impostors.forEach(function (impostor) {
  34951. impostor.beforeStep();
  34952. });
  34953. this.world.step();
  34954. impostors.forEach(function (impostor) {
  34955. impostor.afterStep();
  34956. //update the ordered impostors array
  34957. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  34958. });
  34959. //check for collisions
  34960. var contact = this.world.contacts;
  34961. while (contact !== null) {
  34962. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  34963. contact = contact.next;
  34964. continue;
  34965. }
  34966. //is this body colliding with any other? get the impostor
  34967. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  34968. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  34969. if (!mainImpostor || !collidingImpostor) {
  34970. contact = contact.next;
  34971. continue;
  34972. }
  34973. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  34974. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  34975. contact = contact.next;
  34976. }
  34977. };
  34978. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  34979. var mass = impostor.physicsBody.massInfo.mass;
  34980. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  34981. };
  34982. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  34983. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  34984. this.applyImpulse(impostor, force, contactPoint);
  34985. };
  34986. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  34987. var _this = this;
  34988. //parent-child relationship. Does this impostor has a parent impostor?
  34989. if (impostor.parent) {
  34990. if (impostor.physicsBody) {
  34991. this.removePhysicsBody(impostor);
  34992. //TODO is that needed?
  34993. impostor.forceUpdate();
  34994. }
  34995. return;
  34996. }
  34997. if (impostor.isBodyInitRequired()) {
  34998. var bodyConfig = {
  34999. name: impostor.uniqueId,
  35000. //Oimo must have mass, also for static objects.
  35001. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  35002. size: [],
  35003. type: [],
  35004. pos: [],
  35005. rot: [],
  35006. move: impostor.getParam("mass") !== 0,
  35007. //Supporting older versions of Oimo
  35008. world: this.world
  35009. };
  35010. var impostors = [impostor];
  35011. function addToArray(parent) {
  35012. if (!parent.getChildMeshes)
  35013. return;
  35014. parent.getChildMeshes().forEach(function (m) {
  35015. if (m.physicsImpostor) {
  35016. impostors.push(m.physicsImpostor);
  35017. m.physicsImpostor._init();
  35018. }
  35019. });
  35020. }
  35021. addToArray(impostor.object);
  35022. function checkWithEpsilon(value) {
  35023. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  35024. }
  35025. impostors.forEach(function (i) {
  35026. //get the correct bounding box
  35027. var oldQuaternion = i.object.rotationQuaternion;
  35028. var rot = new OIMO.Euler().setFromQuaternion({
  35029. x: impostor.object.rotationQuaternion.x,
  35030. y: impostor.object.rotationQuaternion.y,
  35031. z: impostor.object.rotationQuaternion.z,
  35032. s: impostor.object.rotationQuaternion.w });
  35033. var extendSize = i.getObjectExtendSize();
  35034. if (i === impostor) {
  35035. var center = impostor.getObjectCenter();
  35036. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  35037. //Can also use Array.prototype.push.apply
  35038. bodyConfig.pos.push(center.x);
  35039. bodyConfig.pos.push(center.y);
  35040. bodyConfig.pos.push(center.z);
  35041. //tmp solution
  35042. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  35043. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  35044. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  35045. }
  35046. else {
  35047. bodyConfig.pos.push(i.object.position.x);
  35048. bodyConfig.pos.push(i.object.position.y);
  35049. bodyConfig.pos.push(i.object.position.z);
  35050. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  35051. bodyConfig.rot.push(0);
  35052. bodyConfig.rot.push(0);
  35053. bodyConfig.rot.push(0);
  35054. }
  35055. // register mesh
  35056. switch (i.type) {
  35057. case BABYLON.PhysicsImpostor.ParticleImpostor:
  35058. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  35059. case BABYLON.PhysicsImpostor.SphereImpostor:
  35060. var radiusX = extendSize.x;
  35061. var radiusY = extendSize.y;
  35062. var radiusZ = extendSize.z;
  35063. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  35064. bodyConfig.type.push('sphere');
  35065. //due to the way oimo works with compounds, add 3 times
  35066. bodyConfig.size.push(size);
  35067. bodyConfig.size.push(size);
  35068. bodyConfig.size.push(size);
  35069. break;
  35070. case BABYLON.PhysicsImpostor.CylinderImpostor:
  35071. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  35072. var sizeY = checkWithEpsilon(extendSize.y);
  35073. bodyConfig.type.push('cylinder');
  35074. bodyConfig.size.push(sizeX);
  35075. bodyConfig.size.push(sizeY);
  35076. //due to the way oimo works with compounds, add one more value.
  35077. bodyConfig.size.push(sizeY);
  35078. break;
  35079. case BABYLON.PhysicsImpostor.PlaneImpostor:
  35080. case BABYLON.PhysicsImpostor.BoxImpostor:
  35081. default:
  35082. var sizeX = checkWithEpsilon(extendSize.x);
  35083. var sizeY = checkWithEpsilon(extendSize.y);
  35084. var sizeZ = checkWithEpsilon(extendSize.z);
  35085. bodyConfig.type.push('box');
  35086. bodyConfig.size.push(sizeX);
  35087. bodyConfig.size.push(sizeY);
  35088. bodyConfig.size.push(sizeZ);
  35089. break;
  35090. }
  35091. //actually not needed, but hey...
  35092. i.object.rotationQuaternion = oldQuaternion;
  35093. });
  35094. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  35095. }
  35096. else {
  35097. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  35098. }
  35099. impostor.setDeltaPosition(this._tmpPositionVector);
  35100. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  35101. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  35102. };
  35103. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  35104. //impostor.physicsBody.dispose();
  35105. //Same as : (older oimo versions)
  35106. this.world.removeRigidBody(impostor.physicsBody);
  35107. };
  35108. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  35109. var mainBody = impostorJoint.mainImpostor.physicsBody;
  35110. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  35111. if (!mainBody || !connectedBody) {
  35112. return;
  35113. }
  35114. var jointData = impostorJoint.joint.jointData;
  35115. var options = jointData.nativeParams || {};
  35116. var type;
  35117. var nativeJointData = {
  35118. body1: mainBody,
  35119. body2: connectedBody,
  35120. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  35121. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  35122. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  35123. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  35124. min: options.min,
  35125. max: options.max,
  35126. collision: options.collision || jointData.collision,
  35127. spring: options.spring,
  35128. //supporting older version of Oimo
  35129. world: this.world
  35130. };
  35131. switch (impostorJoint.joint.type) {
  35132. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  35133. type = "jointBall";
  35134. break;
  35135. case BABYLON.PhysicsJoint.SpringJoint:
  35136. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  35137. var springData = jointData;
  35138. nativeJointData.min = springData.length || nativeJointData.min;
  35139. //Max should also be set, just make sure it is at least min
  35140. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  35141. case BABYLON.PhysicsJoint.DistanceJoint:
  35142. type = "jointDistance";
  35143. nativeJointData.max = jointData.maxDistance;
  35144. break;
  35145. case BABYLON.PhysicsJoint.PrismaticJoint:
  35146. type = "jointPrisme";
  35147. break;
  35148. case BABYLON.PhysicsJoint.SliderJoint:
  35149. type = "jointSlide";
  35150. break;
  35151. case BABYLON.PhysicsJoint.WheelJoint:
  35152. type = "jointWheel";
  35153. break;
  35154. case BABYLON.PhysicsJoint.HingeJoint:
  35155. default:
  35156. type = "jointHinge";
  35157. break;
  35158. }
  35159. nativeJointData.type = type;
  35160. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  35161. };
  35162. OimoJSPlugin.prototype.removeJoint = function (joint) {
  35163. joint.joint.physicsJoint.dispose();
  35164. };
  35165. OimoJSPlugin.prototype.isSupported = function () {
  35166. return OIMO !== undefined;
  35167. };
  35168. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  35169. if (!impostor.physicsBody.sleeping) {
  35170. //TODO check that
  35171. if (impostor.physicsBody.shapes.next) {
  35172. var parentShape = this._getLastShape(impostor.physicsBody);
  35173. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  35174. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  35175. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  35176. }
  35177. else {
  35178. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  35179. }
  35180. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  35181. }
  35182. };
  35183. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  35184. var body = impostor.physicsBody;
  35185. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  35186. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  35187. body.syncShapes();
  35188. body.awake();
  35189. };
  35190. OimoJSPlugin.prototype._getLastShape = function (body) {
  35191. var lastShape = body.shapes;
  35192. while (lastShape.next) {
  35193. lastShape = lastShape.next;
  35194. }
  35195. return lastShape;
  35196. };
  35197. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  35198. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  35199. };
  35200. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  35201. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  35202. };
  35203. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  35204. var v = impostor.physicsBody.linearVelocity;
  35205. if (!v)
  35206. return null;
  35207. return new BABYLON.Vector3(v.x, v.y, v.z);
  35208. };
  35209. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  35210. var v = impostor.physicsBody.angularVelocity;
  35211. if (!v)
  35212. return null;
  35213. return new BABYLON.Vector3(v.x, v.y, v.z);
  35214. };
  35215. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  35216. var staticBody = mass === 0;
  35217. //this will actually set the body's density and not its mass.
  35218. //But this is how oimo treats the mass variable.
  35219. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  35220. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  35221. };
  35222. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  35223. impostor.physicsBody.sleep();
  35224. };
  35225. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  35226. impostor.physicsBody.awake();
  35227. };
  35228. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  35229. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  35230. if (minDistance !== void 0) {
  35231. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  35232. }
  35233. };
  35234. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  35235. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.limitMotor;
  35236. if (motor) {
  35237. motor.setMotor(speed, maxForce);
  35238. }
  35239. };
  35240. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  35241. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.limitMotor;
  35242. if (motor) {
  35243. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  35244. }
  35245. };
  35246. OimoJSPlugin.prototype.dispose = function () {
  35247. this.world.clear();
  35248. };
  35249. return OimoJSPlugin;
  35250. })();
  35251. BABYLON.OimoJSPlugin = OimoJSPlugin;
  35252. })(BABYLON || (BABYLON = {}));
  35253. var BABYLON;
  35254. (function (BABYLON) {
  35255. var DisplayPassPostProcess = (function (_super) {
  35256. __extends(DisplayPassPostProcess, _super);
  35257. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  35258. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  35259. }
  35260. return DisplayPassPostProcess;
  35261. })(BABYLON.PostProcess);
  35262. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  35263. })(BABYLON || (BABYLON = {}));
  35264. var BABYLON;
  35265. (function (BABYLON) {
  35266. var SimplificationSettings = (function () {
  35267. function SimplificationSettings(quality, distance, optimizeMesh) {
  35268. this.quality = quality;
  35269. this.distance = distance;
  35270. this.optimizeMesh = optimizeMesh;
  35271. }
  35272. return SimplificationSettings;
  35273. })();
  35274. BABYLON.SimplificationSettings = SimplificationSettings;
  35275. var SimplificationQueue = (function () {
  35276. function SimplificationQueue() {
  35277. this.running = false;
  35278. this._simplificationArray = [];
  35279. }
  35280. SimplificationQueue.prototype.addTask = function (task) {
  35281. this._simplificationArray.push(task);
  35282. };
  35283. SimplificationQueue.prototype.executeNext = function () {
  35284. var task = this._simplificationArray.pop();
  35285. if (task) {
  35286. this.running = true;
  35287. this.runSimplification(task);
  35288. }
  35289. else {
  35290. this.running = false;
  35291. }
  35292. };
  35293. SimplificationQueue.prototype.runSimplification = function (task) {
  35294. var _this = this;
  35295. if (task.parallelProcessing) {
  35296. //parallel simplifier
  35297. task.settings.forEach(function (setting) {
  35298. var simplifier = _this.getSimplifier(task);
  35299. simplifier.simplify(setting, function (newMesh) {
  35300. task.mesh.addLODLevel(setting.distance, newMesh);
  35301. newMesh.isVisible = true;
  35302. //check if it is the last
  35303. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  35304. //all done, run the success callback.
  35305. task.successCallback();
  35306. }
  35307. _this.executeNext();
  35308. });
  35309. });
  35310. }
  35311. else {
  35312. //single simplifier.
  35313. var simplifier = this.getSimplifier(task);
  35314. var runDecimation = function (setting, callback) {
  35315. simplifier.simplify(setting, function (newMesh) {
  35316. task.mesh.addLODLevel(setting.distance, newMesh);
  35317. newMesh.isVisible = true;
  35318. //run the next quality level
  35319. callback();
  35320. });
  35321. };
  35322. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  35323. runDecimation(task.settings[loop.index], function () {
  35324. loop.executeNext();
  35325. });
  35326. }, function () {
  35327. //execution ended, run the success callback.
  35328. if (task.successCallback) {
  35329. task.successCallback();
  35330. }
  35331. _this.executeNext();
  35332. });
  35333. }
  35334. };
  35335. SimplificationQueue.prototype.getSimplifier = function (task) {
  35336. switch (task.simplificationType) {
  35337. case SimplificationType.QUADRATIC:
  35338. default:
  35339. return new QuadraticErrorSimplification(task.mesh);
  35340. }
  35341. };
  35342. return SimplificationQueue;
  35343. })();
  35344. BABYLON.SimplificationQueue = SimplificationQueue;
  35345. /**
  35346. * The implemented types of simplification.
  35347. * At the moment only Quadratic Error Decimation is implemented.
  35348. */
  35349. (function (SimplificationType) {
  35350. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  35351. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  35352. var SimplificationType = BABYLON.SimplificationType;
  35353. var DecimationTriangle = (function () {
  35354. function DecimationTriangle(vertices) {
  35355. this.vertices = vertices;
  35356. this.error = new Array(4);
  35357. this.deleted = false;
  35358. this.isDirty = false;
  35359. this.deletePending = false;
  35360. this.borderFactor = 0;
  35361. }
  35362. return DecimationTriangle;
  35363. })();
  35364. BABYLON.DecimationTriangle = DecimationTriangle;
  35365. var DecimationVertex = (function () {
  35366. function DecimationVertex(position, id) {
  35367. this.position = position;
  35368. this.id = id;
  35369. this.isBorder = true;
  35370. this.q = new QuadraticMatrix();
  35371. this.triangleCount = 0;
  35372. this.triangleStart = 0;
  35373. this.originalOffsets = [];
  35374. }
  35375. DecimationVertex.prototype.updatePosition = function (newPosition) {
  35376. this.position.copyFrom(newPosition);
  35377. };
  35378. return DecimationVertex;
  35379. })();
  35380. BABYLON.DecimationVertex = DecimationVertex;
  35381. var QuadraticMatrix = (function () {
  35382. function QuadraticMatrix(data) {
  35383. this.data = new Array(10);
  35384. for (var i = 0; i < 10; ++i) {
  35385. if (data && data[i]) {
  35386. this.data[i] = data[i];
  35387. }
  35388. else {
  35389. this.data[i] = 0;
  35390. }
  35391. }
  35392. }
  35393. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  35394. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  35395. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  35396. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  35397. return det;
  35398. };
  35399. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  35400. for (var i = 0; i < 10; ++i) {
  35401. this.data[i] += matrix.data[i];
  35402. }
  35403. };
  35404. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  35405. for (var i = 0; i < 10; ++i) {
  35406. this.data[i] += data[i];
  35407. }
  35408. };
  35409. QuadraticMatrix.prototype.add = function (matrix) {
  35410. var m = new QuadraticMatrix();
  35411. for (var i = 0; i < 10; ++i) {
  35412. m.data[i] = this.data[i] + matrix.data[i];
  35413. }
  35414. return m;
  35415. };
  35416. QuadraticMatrix.FromData = function (a, b, c, d) {
  35417. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  35418. };
  35419. //returning an array to avoid garbage collection
  35420. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  35421. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  35422. };
  35423. return QuadraticMatrix;
  35424. })();
  35425. BABYLON.QuadraticMatrix = QuadraticMatrix;
  35426. var Reference = (function () {
  35427. function Reference(vertexId, triangleId) {
  35428. this.vertexId = vertexId;
  35429. this.triangleId = triangleId;
  35430. }
  35431. return Reference;
  35432. })();
  35433. BABYLON.Reference = Reference;
  35434. /**
  35435. * An implementation of the Quadratic Error simplification algorithm.
  35436. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  35437. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  35438. * @author RaananW
  35439. */
  35440. var QuadraticErrorSimplification = (function () {
  35441. function QuadraticErrorSimplification(_mesh) {
  35442. this._mesh = _mesh;
  35443. this.initialized = false;
  35444. this.syncIterations = 5000;
  35445. this.aggressiveness = 7;
  35446. this.decimationIterations = 100;
  35447. this.boundingBoxEpsilon = BABYLON.Epsilon;
  35448. }
  35449. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  35450. var _this = this;
  35451. this.initDecimatedMesh();
  35452. //iterating through the submeshes array, one after the other.
  35453. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  35454. _this.initWithMesh(loop.index, function () {
  35455. _this.runDecimation(settings, loop.index, function () {
  35456. loop.executeNext();
  35457. });
  35458. }, settings.optimizeMesh);
  35459. }, function () {
  35460. setTimeout(function () {
  35461. successCallback(_this._reconstructedMesh);
  35462. }, 0);
  35463. });
  35464. };
  35465. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  35466. var _this = this;
  35467. var gCount = 0;
  35468. triangle.vertices.forEach(function (vertex) {
  35469. var count = 0;
  35470. var vPos = vertex.position;
  35471. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  35472. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  35473. ++count;
  35474. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  35475. ++count;
  35476. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  35477. ++count;
  35478. if (count > 1) {
  35479. ++gCount;
  35480. }
  35481. ;
  35482. });
  35483. if (gCount > 1) {
  35484. console.log(triangle, gCount);
  35485. }
  35486. return gCount > 1;
  35487. };
  35488. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  35489. var _this = this;
  35490. var targetCount = ~~(this.triangles.length * settings.quality);
  35491. var deletedTriangles = 0;
  35492. var triangleCount = this.triangles.length;
  35493. var iterationFunction = function (iteration, callback) {
  35494. setTimeout(function () {
  35495. if (iteration % 5 === 0) {
  35496. _this.updateMesh(iteration === 0);
  35497. }
  35498. for (var i = 0; i < _this.triangles.length; ++i) {
  35499. _this.triangles[i].isDirty = false;
  35500. }
  35501. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  35502. var trianglesIterator = function (i) {
  35503. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  35504. var t = _this.triangles[tIdx];
  35505. if (!t)
  35506. return;
  35507. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  35508. return;
  35509. }
  35510. for (var j = 0; j < 3; ++j) {
  35511. if (t.error[j] < threshold) {
  35512. var deleted0 = [];
  35513. var deleted1 = [];
  35514. var v0 = t.vertices[j];
  35515. var v1 = t.vertices[(j + 1) % 3];
  35516. if (v0.isBorder || v1.isBorder)
  35517. continue;
  35518. var p = BABYLON.Vector3.Zero();
  35519. var n = BABYLON.Vector3.Zero();
  35520. var uv = BABYLON.Vector2.Zero();
  35521. var color = new BABYLON.Color4(0, 0, 0, 1);
  35522. _this.calculateError(v0, v1, p, n, uv, color);
  35523. var delTr = [];
  35524. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  35525. continue;
  35526. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  35527. continue;
  35528. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  35529. continue;
  35530. var uniqueArray = [];
  35531. delTr.forEach(function (deletedT) {
  35532. if (uniqueArray.indexOf(deletedT) === -1) {
  35533. deletedT.deletePending = true;
  35534. uniqueArray.push(deletedT);
  35535. }
  35536. });
  35537. if (uniqueArray.length % 2 !== 0) {
  35538. continue;
  35539. }
  35540. v0.q = v1.q.add(v0.q);
  35541. v0.updatePosition(p);
  35542. var tStart = _this.references.length;
  35543. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  35544. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  35545. var tCount = _this.references.length - tStart;
  35546. if (tCount <= v0.triangleCount) {
  35547. if (tCount) {
  35548. for (var c = 0; c < tCount; c++) {
  35549. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  35550. }
  35551. }
  35552. }
  35553. else {
  35554. v0.triangleStart = tStart;
  35555. }
  35556. v0.triangleCount = tCount;
  35557. break;
  35558. }
  35559. }
  35560. };
  35561. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  35562. }, 0);
  35563. };
  35564. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  35565. if (triangleCount - deletedTriangles <= targetCount)
  35566. loop.breakLoop();
  35567. else {
  35568. iterationFunction(loop.index, function () {
  35569. loop.executeNext();
  35570. });
  35571. }
  35572. }, function () {
  35573. setTimeout(function () {
  35574. //reconstruct this part of the mesh
  35575. _this.reconstructMesh(submeshIndex);
  35576. successCallback();
  35577. }, 0);
  35578. });
  35579. };
  35580. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  35581. var _this = this;
  35582. this.vertices = [];
  35583. this.triangles = [];
  35584. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35585. var indices = this._mesh.getIndices();
  35586. var submesh = this._mesh.subMeshes[submeshIndex];
  35587. var findInVertices = function (positionToSearch) {
  35588. if (optimizeMesh) {
  35589. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  35590. if (_this.vertices[ii].position.equals(positionToSearch)) {
  35591. return _this.vertices[ii];
  35592. }
  35593. }
  35594. }
  35595. return null;
  35596. };
  35597. var vertexReferences = [];
  35598. var vertexInit = function (i) {
  35599. var offset = i + submesh.verticesStart;
  35600. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  35601. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  35602. vertex.originalOffsets.push(offset);
  35603. if (vertex.id === _this.vertices.length) {
  35604. _this.vertices.push(vertex);
  35605. }
  35606. vertexReferences.push(vertex.id);
  35607. };
  35608. //var totalVertices = mesh.getTotalVertices();
  35609. var totalVertices = submesh.verticesCount;
  35610. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  35611. var indicesInit = function (i) {
  35612. var offset = (submesh.indexStart / 3) + i;
  35613. var pos = (offset * 3);
  35614. var i0 = indices[pos + 0];
  35615. var i1 = indices[pos + 1];
  35616. var i2 = indices[pos + 2];
  35617. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  35618. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  35619. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  35620. var triangle = new DecimationTriangle([v0, v1, v2]);
  35621. triangle.originalOffset = pos;
  35622. _this.triangles.push(triangle);
  35623. };
  35624. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  35625. _this.init(callback);
  35626. });
  35627. });
  35628. };
  35629. QuadraticErrorSimplification.prototype.init = function (callback) {
  35630. var _this = this;
  35631. var triangleInit1 = function (i) {
  35632. var t = _this.triangles[i];
  35633. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  35634. for (var j = 0; j < 3; j++) {
  35635. 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))));
  35636. }
  35637. };
  35638. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  35639. var triangleInit2 = function (i) {
  35640. var t = _this.triangles[i];
  35641. for (var j = 0; j < 3; ++j) {
  35642. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  35643. }
  35644. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  35645. };
  35646. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  35647. _this.initialized = true;
  35648. callback();
  35649. });
  35650. });
  35651. };
  35652. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  35653. var newTriangles = [];
  35654. var i;
  35655. for (i = 0; i < this.vertices.length; ++i) {
  35656. this.vertices[i].triangleCount = 0;
  35657. }
  35658. var t;
  35659. var j;
  35660. for (i = 0; i < this.triangles.length; ++i) {
  35661. if (!this.triangles[i].deleted) {
  35662. t = this.triangles[i];
  35663. for (j = 0; j < 3; ++j) {
  35664. t.vertices[j].triangleCount = 1;
  35665. }
  35666. newTriangles.push(t);
  35667. }
  35668. }
  35669. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  35670. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  35671. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  35672. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  35673. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35674. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  35675. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  35676. var vertexCount = 0;
  35677. for (i = 0; i < this.vertices.length; ++i) {
  35678. var vertex = this.vertices[i];
  35679. vertex.id = vertexCount;
  35680. if (vertex.triangleCount) {
  35681. vertex.originalOffsets.forEach(function (originalOffset) {
  35682. newPositionData.push(vertex.position.x);
  35683. newPositionData.push(vertex.position.y);
  35684. newPositionData.push(vertex.position.z);
  35685. newNormalData.push(normalData[originalOffset * 3]);
  35686. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  35687. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  35688. if (uvs && uvs.length) {
  35689. newUVsData.push(uvs[(originalOffset * 2)]);
  35690. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  35691. }
  35692. else if (colorsData && colorsData.length) {
  35693. newColorsData.push(colorsData[(originalOffset * 4)]);
  35694. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  35695. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  35696. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  35697. }
  35698. ++vertexCount;
  35699. });
  35700. }
  35701. }
  35702. var startingIndex = this._reconstructedMesh.getTotalIndices();
  35703. var startingVertex = this._reconstructedMesh.getTotalVertices();
  35704. var submeshesArray = this._reconstructedMesh.subMeshes;
  35705. this._reconstructedMesh.subMeshes = [];
  35706. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  35707. var originalIndices = this._mesh.getIndices();
  35708. for (i = 0; i < newTriangles.length; ++i) {
  35709. t = newTriangles[i]; //now get the new referencing point for each vertex
  35710. [0, 1, 2].forEach(function (idx) {
  35711. var id = originalIndices[t.originalOffset + idx];
  35712. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  35713. if (offset < 0)
  35714. offset = 0;
  35715. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  35716. });
  35717. }
  35718. //overwriting the old vertex buffers and indices.
  35719. this._reconstructedMesh.setIndices(newIndicesArray);
  35720. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  35721. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  35722. if (newUVsData.length > 0)
  35723. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  35724. if (newColorsData.length > 0)
  35725. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  35726. //create submesh
  35727. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  35728. if (submeshIndex > 0) {
  35729. this._reconstructedMesh.subMeshes = [];
  35730. submeshesArray.forEach(function (submesh) {
  35731. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  35732. });
  35733. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  35734. }
  35735. };
  35736. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  35737. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  35738. this._reconstructedMesh.material = this._mesh.material;
  35739. this._reconstructedMesh.parent = this._mesh.parent;
  35740. this._reconstructedMesh.isVisible = false;
  35741. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  35742. };
  35743. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  35744. for (var i = 0; i < vertex1.triangleCount; ++i) {
  35745. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  35746. if (t.deleted)
  35747. continue;
  35748. var s = this.references[vertex1.triangleStart + i].vertexId;
  35749. var v1 = t.vertices[(s + 1) % 3];
  35750. var v2 = t.vertices[(s + 2) % 3];
  35751. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  35752. deletedArray[i] = true;
  35753. delTr.push(t);
  35754. continue;
  35755. }
  35756. var d1 = v1.position.subtract(point);
  35757. d1 = d1.normalize();
  35758. var d2 = v2.position.subtract(point);
  35759. d2 = d2.normalize();
  35760. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  35761. return true;
  35762. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  35763. deletedArray[i] = false;
  35764. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  35765. return true;
  35766. }
  35767. return false;
  35768. };
  35769. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  35770. var newDeleted = deletedTriangles;
  35771. for (var i = 0; i < vertex.triangleCount; ++i) {
  35772. var ref = this.references[vertex.triangleStart + i];
  35773. var t = this.triangles[ref.triangleId];
  35774. if (t.deleted)
  35775. continue;
  35776. if (deletedArray[i] && t.deletePending) {
  35777. t.deleted = true;
  35778. newDeleted++;
  35779. continue;
  35780. }
  35781. t.vertices[ref.vertexId] = origVertex;
  35782. t.isDirty = true;
  35783. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  35784. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  35785. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  35786. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  35787. this.references.push(ref);
  35788. }
  35789. return newDeleted;
  35790. };
  35791. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  35792. for (var i = 0; i < this.vertices.length; ++i) {
  35793. var vCount = [];
  35794. var vId = [];
  35795. var v = this.vertices[i];
  35796. var j;
  35797. for (j = 0; j < v.triangleCount; ++j) {
  35798. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  35799. for (var ii = 0; ii < 3; ii++) {
  35800. var ofs = 0;
  35801. var vv = triangle.vertices[ii];
  35802. while (ofs < vCount.length) {
  35803. if (vId[ofs] === vv.id)
  35804. break;
  35805. ++ofs;
  35806. }
  35807. if (ofs === vCount.length) {
  35808. vCount.push(1);
  35809. vId.push(vv.id);
  35810. }
  35811. else {
  35812. vCount[ofs]++;
  35813. }
  35814. }
  35815. }
  35816. for (j = 0; j < vCount.length; ++j) {
  35817. if (vCount[j] === 1) {
  35818. this.vertices[vId[j]].isBorder = true;
  35819. }
  35820. else {
  35821. this.vertices[vId[j]].isBorder = false;
  35822. }
  35823. }
  35824. }
  35825. };
  35826. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  35827. if (identifyBorders === void 0) { identifyBorders = false; }
  35828. var i;
  35829. if (!identifyBorders) {
  35830. var newTrianglesVector = [];
  35831. for (i = 0; i < this.triangles.length; ++i) {
  35832. if (!this.triangles[i].deleted) {
  35833. newTrianglesVector.push(this.triangles[i]);
  35834. }
  35835. }
  35836. this.triangles = newTrianglesVector;
  35837. }
  35838. for (i = 0; i < this.vertices.length; ++i) {
  35839. this.vertices[i].triangleCount = 0;
  35840. this.vertices[i].triangleStart = 0;
  35841. }
  35842. var t;
  35843. var j;
  35844. var v;
  35845. for (i = 0; i < this.triangles.length; ++i) {
  35846. t = this.triangles[i];
  35847. for (j = 0; j < 3; ++j) {
  35848. v = t.vertices[j];
  35849. v.triangleCount++;
  35850. }
  35851. }
  35852. var tStart = 0;
  35853. for (i = 0; i < this.vertices.length; ++i) {
  35854. this.vertices[i].triangleStart = tStart;
  35855. tStart += this.vertices[i].triangleCount;
  35856. this.vertices[i].triangleCount = 0;
  35857. }
  35858. var newReferences = new Array(this.triangles.length * 3);
  35859. for (i = 0; i < this.triangles.length; ++i) {
  35860. t = this.triangles[i];
  35861. for (j = 0; j < 3; ++j) {
  35862. v = t.vertices[j];
  35863. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  35864. v.triangleCount++;
  35865. }
  35866. }
  35867. this.references = newReferences;
  35868. if (identifyBorders) {
  35869. this.identifyBorder();
  35870. }
  35871. };
  35872. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  35873. var x = point.x;
  35874. var y = point.y;
  35875. var z = point.z;
  35876. 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
  35877. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  35878. };
  35879. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  35880. var q = vertex1.q.add(vertex2.q);
  35881. var border = vertex1.isBorder && vertex2.isBorder;
  35882. var error = 0;
  35883. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  35884. if (qDet !== 0 && !border) {
  35885. if (!pointResult) {
  35886. pointResult = BABYLON.Vector3.Zero();
  35887. }
  35888. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  35889. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  35890. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  35891. error = this.vertexError(q, pointResult);
  35892. }
  35893. else {
  35894. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  35895. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  35896. var error1 = this.vertexError(q, vertex1.position);
  35897. var error2 = this.vertexError(q, vertex2.position);
  35898. var error3 = this.vertexError(q, p3);
  35899. error = Math.min(error1, error2, error3);
  35900. if (error === error1) {
  35901. if (pointResult) {
  35902. pointResult.copyFrom(vertex1.position);
  35903. }
  35904. }
  35905. else if (error === error2) {
  35906. if (pointResult) {
  35907. pointResult.copyFrom(vertex2.position);
  35908. }
  35909. }
  35910. else {
  35911. if (pointResult) {
  35912. pointResult.copyFrom(p3);
  35913. }
  35914. }
  35915. }
  35916. return error;
  35917. };
  35918. return QuadraticErrorSimplification;
  35919. })();
  35920. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  35921. })(BABYLON || (BABYLON = {}));
  35922. var BABYLON;
  35923. (function (BABYLON) {
  35924. var serializedGeometries = [];
  35925. var serializeGeometry = function (geometry, serializationGeometries) {
  35926. if (serializedGeometries[geometry.id]) {
  35927. return;
  35928. }
  35929. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  35930. serializationGeometries.boxes.push(geometry.serialize());
  35931. }
  35932. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  35933. serializationGeometries.spheres.push(geometry.serialize());
  35934. }
  35935. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  35936. serializationGeometries.cylinders.push(geometry.serialize());
  35937. }
  35938. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  35939. serializationGeometries.toruses.push(geometry.serialize());
  35940. }
  35941. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  35942. serializationGeometries.grounds.push(geometry.serialize());
  35943. }
  35944. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  35945. serializationGeometries.planes.push(geometry.serialize());
  35946. }
  35947. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  35948. serializationGeometries.torusKnots.push(geometry.serialize());
  35949. }
  35950. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  35951. throw new Error("Unknown primitive type");
  35952. }
  35953. else {
  35954. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  35955. }
  35956. serializedGeometries[geometry.id] = true;
  35957. };
  35958. var serializeMesh = function (mesh, serializationScene) {
  35959. var serializationObject = {};
  35960. serializationObject.name = mesh.name;
  35961. serializationObject.id = mesh.id;
  35962. if (BABYLON.Tags.HasTags(mesh)) {
  35963. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  35964. }
  35965. serializationObject.position = mesh.position.asArray();
  35966. if (mesh.rotationQuaternion) {
  35967. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  35968. }
  35969. else if (mesh.rotation) {
  35970. serializationObject.rotation = mesh.rotation.asArray();
  35971. }
  35972. serializationObject.scaling = mesh.scaling.asArray();
  35973. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  35974. serializationObject.isEnabled = mesh.isEnabled();
  35975. serializationObject.isVisible = mesh.isVisible;
  35976. serializationObject.infiniteDistance = mesh.infiniteDistance;
  35977. serializationObject.pickable = mesh.isPickable;
  35978. serializationObject.receiveShadows = mesh.receiveShadows;
  35979. serializationObject.billboardMode = mesh.billboardMode;
  35980. serializationObject.visibility = mesh.visibility;
  35981. serializationObject.checkCollisions = mesh.checkCollisions;
  35982. // Parent
  35983. if (mesh.parent) {
  35984. serializationObject.parentId = mesh.parent.id;
  35985. }
  35986. // Geometry
  35987. var geometry = mesh._geometry;
  35988. if (geometry) {
  35989. var geometryId = geometry.id;
  35990. serializationObject.geometryId = geometryId;
  35991. if (!mesh.getScene().getGeometryByID(geometryId)) {
  35992. // 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
  35993. serializeGeometry(geometry, serializationScene.geometries);
  35994. }
  35995. // SubMeshes
  35996. serializationObject.subMeshes = [];
  35997. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35998. var subMesh = mesh.subMeshes[subIndex];
  35999. serializationObject.subMeshes.push({
  36000. materialIndex: subMesh.materialIndex,
  36001. verticesStart: subMesh.verticesStart,
  36002. verticesCount: subMesh.verticesCount,
  36003. indexStart: subMesh.indexStart,
  36004. indexCount: subMesh.indexCount
  36005. });
  36006. }
  36007. }
  36008. // Material
  36009. if (mesh.material) {
  36010. serializationObject.materialId = mesh.material.id;
  36011. }
  36012. else {
  36013. mesh.material = null;
  36014. }
  36015. // Skeleton
  36016. if (mesh.skeleton) {
  36017. serializationObject.skeletonId = mesh.skeleton.id;
  36018. }
  36019. // Physics
  36020. //TODO implement correct serialization for physics impostors.
  36021. if (mesh.getPhysicsImpostor()) {
  36022. serializationObject.physicsMass = mesh.getPhysicsMass();
  36023. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  36024. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  36025. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  36026. }
  36027. // Instances
  36028. serializationObject.instances = [];
  36029. for (var index = 0; index < mesh.instances.length; index++) {
  36030. var instance = mesh.instances[index];
  36031. var serializationInstance = {
  36032. name: instance.name,
  36033. position: instance.position.asArray(),
  36034. scaling: instance.scaling.asArray()
  36035. };
  36036. if (instance.rotationQuaternion) {
  36037. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  36038. }
  36039. else if (instance.rotation) {
  36040. serializationInstance.rotation = instance.rotation.asArray();
  36041. }
  36042. serializationObject.instances.push(serializationInstance);
  36043. // Animations
  36044. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  36045. serializationInstance.ranges = instance.serializeAnimationRanges();
  36046. }
  36047. // Animations
  36048. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  36049. serializationObject.ranges = mesh.serializeAnimationRanges();
  36050. // Layer mask
  36051. serializationObject.layerMask = mesh.layerMask;
  36052. return serializationObject;
  36053. };
  36054. var finalizeSingleMesh = function (mesh, serializationObject) {
  36055. //only works if the mesh is already loaded
  36056. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  36057. //serialize material
  36058. if (mesh.material) {
  36059. if (mesh.material instanceof BABYLON.StandardMaterial) {
  36060. serializationObject.materials = serializationObject.materials || [];
  36061. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  36062. serializationObject.materials.push(mesh.material.serialize());
  36063. }
  36064. }
  36065. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  36066. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  36067. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  36068. serializationObject.multiMaterials.push(mesh.material.serialize());
  36069. }
  36070. }
  36071. }
  36072. //serialize geometry
  36073. var geometry = mesh._geometry;
  36074. if (geometry) {
  36075. if (!serializationObject.geometries) {
  36076. serializationObject.geometries = {};
  36077. serializationObject.geometries.boxes = [];
  36078. serializationObject.geometries.spheres = [];
  36079. serializationObject.geometries.cylinders = [];
  36080. serializationObject.geometries.toruses = [];
  36081. serializationObject.geometries.grounds = [];
  36082. serializationObject.geometries.planes = [];
  36083. serializationObject.geometries.torusKnots = [];
  36084. serializationObject.geometries.vertexData = [];
  36085. }
  36086. serializeGeometry(geometry, serializationObject.geometries);
  36087. }
  36088. // Skeletons
  36089. if (mesh.skeleton) {
  36090. serializationObject.skeletons = serializationObject.skeletons || [];
  36091. serializationObject.skeletons.push(mesh.skeleton.serialize());
  36092. }
  36093. //serialize the actual mesh
  36094. serializationObject.meshes = serializationObject.meshes || [];
  36095. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  36096. }
  36097. };
  36098. var SceneSerializer = (function () {
  36099. function SceneSerializer() {
  36100. }
  36101. SceneSerializer.ClearCache = function () {
  36102. serializedGeometries = [];
  36103. };
  36104. SceneSerializer.Serialize = function (scene) {
  36105. var serializationObject = {};
  36106. // Scene
  36107. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  36108. serializationObject.autoClear = scene.autoClear;
  36109. serializationObject.clearColor = scene.clearColor.asArray();
  36110. serializationObject.ambientColor = scene.ambientColor.asArray();
  36111. serializationObject.gravity = scene.gravity.asArray();
  36112. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  36113. serializationObject.workerCollisions = scene.workerCollisions;
  36114. // Fog
  36115. if (scene.fogMode && scene.fogMode !== 0) {
  36116. serializationObject.fogMode = scene.fogMode;
  36117. serializationObject.fogColor = scene.fogColor.asArray();
  36118. serializationObject.fogStart = scene.fogStart;
  36119. serializationObject.fogEnd = scene.fogEnd;
  36120. serializationObject.fogDensity = scene.fogDensity;
  36121. }
  36122. //Physics
  36123. if (scene.isPhysicsEnabled()) {
  36124. serializationObject.physicsEnabled = true;
  36125. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  36126. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  36127. }
  36128. // Lights
  36129. serializationObject.lights = [];
  36130. var index;
  36131. var light;
  36132. for (index = 0; index < scene.lights.length; index++) {
  36133. light = scene.lights[index];
  36134. serializationObject.lights.push(light.serialize());
  36135. }
  36136. // Cameras
  36137. serializationObject.cameras = [];
  36138. for (index = 0; index < scene.cameras.length; index++) {
  36139. var camera = scene.cameras[index];
  36140. serializationObject.cameras.push(camera.serialize());
  36141. }
  36142. if (scene.activeCamera) {
  36143. serializationObject.activeCameraID = scene.activeCamera.id;
  36144. }
  36145. // Animations
  36146. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  36147. // Materials
  36148. serializationObject.materials = [];
  36149. serializationObject.multiMaterials = [];
  36150. var material;
  36151. for (index = 0; index < scene.materials.length; index++) {
  36152. material = scene.materials[index];
  36153. serializationObject.materials.push(material.serialize());
  36154. }
  36155. // MultiMaterials
  36156. serializationObject.multiMaterials = [];
  36157. for (index = 0; index < scene.multiMaterials.length; index++) {
  36158. var multiMaterial = scene.multiMaterials[index];
  36159. serializationObject.multiMaterials.push(multiMaterial.serialize());
  36160. }
  36161. // Skeletons
  36162. serializationObject.skeletons = [];
  36163. for (index = 0; index < scene.skeletons.length; index++) {
  36164. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  36165. }
  36166. // Geometries
  36167. serializationObject.geometries = {};
  36168. serializationObject.geometries.boxes = [];
  36169. serializationObject.geometries.spheres = [];
  36170. serializationObject.geometries.cylinders = [];
  36171. serializationObject.geometries.toruses = [];
  36172. serializationObject.geometries.grounds = [];
  36173. serializationObject.geometries.planes = [];
  36174. serializationObject.geometries.torusKnots = [];
  36175. serializationObject.geometries.vertexData = [];
  36176. serializedGeometries = [];
  36177. var geometries = scene.getGeometries();
  36178. for (index = 0; index < geometries.length; index++) {
  36179. var geometry = geometries[index];
  36180. if (geometry.isReady()) {
  36181. serializeGeometry(geometry, serializationObject.geometries);
  36182. }
  36183. }
  36184. // Meshes
  36185. serializationObject.meshes = [];
  36186. for (index = 0; index < scene.meshes.length; index++) {
  36187. var abstractMesh = scene.meshes[index];
  36188. if (abstractMesh instanceof BABYLON.Mesh) {
  36189. var mesh = abstractMesh;
  36190. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  36191. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  36192. }
  36193. }
  36194. }
  36195. // Particles Systems
  36196. serializationObject.particleSystems = [];
  36197. for (index = 0; index < scene.particleSystems.length; index++) {
  36198. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  36199. }
  36200. // Lens flares
  36201. serializationObject.lensFlareSystems = [];
  36202. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  36203. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  36204. }
  36205. // Shadows
  36206. serializationObject.shadowGenerators = [];
  36207. for (index = 0; index < scene.lights.length; index++) {
  36208. light = scene.lights[index];
  36209. if (light.getShadowGenerator()) {
  36210. serializationObject.shadowGenerators.push(light.getShadowGenerator().serialize());
  36211. }
  36212. }
  36213. return serializationObject;
  36214. };
  36215. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  36216. if (withParents === void 0) { withParents = false; }
  36217. if (withChildren === void 0) { withChildren = false; }
  36218. var serializationObject = {};
  36219. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  36220. if (withParents || withChildren) {
  36221. //deliberate for loop! not for each, appended should be processed as well.
  36222. for (var i = 0; i < toSerialize.length; ++i) {
  36223. if (withChildren) {
  36224. toSerialize[i].getDescendants().forEach(function (node) {
  36225. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  36226. toSerialize.push(node);
  36227. }
  36228. });
  36229. }
  36230. //make sure the array doesn't contain the object already
  36231. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  36232. toSerialize.push(toSerialize[i].parent);
  36233. }
  36234. }
  36235. }
  36236. toSerialize.forEach(function (mesh) {
  36237. finalizeSingleMesh(mesh, serializationObject);
  36238. });
  36239. return serializationObject;
  36240. };
  36241. return SceneSerializer;
  36242. })();
  36243. BABYLON.SceneSerializer = SceneSerializer;
  36244. })(BABYLON || (BABYLON = {}));
  36245. var BABYLON;
  36246. (function (BABYLON) {
  36247. // Unique ID when we import meshes from Babylon to CSG
  36248. var currentCSGMeshId = 0;
  36249. // # class Vertex
  36250. // Represents a vertex of a polygon. Use your own vertex class instead of this
  36251. // one to provide additional features like texture coordinates and vertex
  36252. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  36253. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  36254. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  36255. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  36256. // is not used anywhere else.
  36257. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  36258. var Vertex = (function () {
  36259. function Vertex(pos, normal, uv) {
  36260. this.pos = pos;
  36261. this.normal = normal;
  36262. this.uv = uv;
  36263. }
  36264. Vertex.prototype.clone = function () {
  36265. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  36266. };
  36267. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  36268. // orientation of a polygon is flipped.
  36269. Vertex.prototype.flip = function () {
  36270. this.normal = this.normal.scale(-1);
  36271. };
  36272. // Create a new vertex between this vertex and `other` by linearly
  36273. // interpolating all properties using a parameter of `t`. Subclasses should
  36274. // override this to interpolate additional properties.
  36275. Vertex.prototype.interpolate = function (other, t) {
  36276. 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));
  36277. };
  36278. return Vertex;
  36279. })();
  36280. // # class Plane
  36281. // Represents a plane in 3D space.
  36282. var Plane = (function () {
  36283. function Plane(normal, w) {
  36284. this.normal = normal;
  36285. this.w = w;
  36286. }
  36287. Plane.FromPoints = function (a, b, c) {
  36288. var v0 = c.subtract(a);
  36289. var v1 = b.subtract(a);
  36290. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  36291. return null;
  36292. }
  36293. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  36294. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  36295. };
  36296. Plane.prototype.clone = function () {
  36297. return new Plane(this.normal.clone(), this.w);
  36298. };
  36299. Plane.prototype.flip = function () {
  36300. this.normal.scaleInPlace(-1);
  36301. this.w = -this.w;
  36302. };
  36303. // Split `polygon` by this plane if needed, then put the polygon or polygon
  36304. // fragments in the appropriate lists. Coplanar polygons go into either
  36305. // `coplanarFront` or `coplanarBack` depending on their orientation with
  36306. // respect to this plane. Polygons in front or in back of this plane go into
  36307. // either `front` or `back`.
  36308. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  36309. var COPLANAR = 0;
  36310. var FRONT = 1;
  36311. var BACK = 2;
  36312. var SPANNING = 3;
  36313. // Classify each point as well as the entire polygon into one of the above
  36314. // four classes.
  36315. var polygonType = 0;
  36316. var types = [];
  36317. var i;
  36318. var t;
  36319. for (i = 0; i < polygon.vertices.length; i++) {
  36320. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  36321. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  36322. polygonType |= type;
  36323. types.push(type);
  36324. }
  36325. // Put the polygon in the correct list, splitting it when necessary.
  36326. switch (polygonType) {
  36327. case COPLANAR:
  36328. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  36329. break;
  36330. case FRONT:
  36331. front.push(polygon);
  36332. break;
  36333. case BACK:
  36334. back.push(polygon);
  36335. break;
  36336. case SPANNING:
  36337. var f = [], b = [];
  36338. for (i = 0; i < polygon.vertices.length; i++) {
  36339. var j = (i + 1) % polygon.vertices.length;
  36340. var ti = types[i], tj = types[j];
  36341. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  36342. if (ti !== BACK)
  36343. f.push(vi);
  36344. if (ti !== FRONT)
  36345. b.push(ti !== BACK ? vi.clone() : vi);
  36346. if ((ti | tj) === SPANNING) {
  36347. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  36348. var v = vi.interpolate(vj, t);
  36349. f.push(v);
  36350. b.push(v.clone());
  36351. }
  36352. }
  36353. var poly;
  36354. if (f.length >= 3) {
  36355. poly = new Polygon(f, polygon.shared);
  36356. if (poly.plane)
  36357. front.push(poly);
  36358. }
  36359. if (b.length >= 3) {
  36360. poly = new Polygon(b, polygon.shared);
  36361. if (poly.plane)
  36362. back.push(poly);
  36363. }
  36364. break;
  36365. }
  36366. };
  36367. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  36368. // point is on the plane.
  36369. Plane.EPSILON = 1e-5;
  36370. return Plane;
  36371. })();
  36372. // # class Polygon
  36373. // Represents a convex polygon. The vertices used to initialize a polygon must
  36374. // be coplanar and form a convex loop.
  36375. //
  36376. // Each convex polygon has a `shared` property, which is shared between all
  36377. // polygons that are clones of each other or were split from the same polygon.
  36378. // This can be used to define per-polygon properties (such as surface color).
  36379. var Polygon = (function () {
  36380. function Polygon(vertices, shared) {
  36381. this.vertices = vertices;
  36382. this.shared = shared;
  36383. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  36384. }
  36385. Polygon.prototype.clone = function () {
  36386. var vertices = this.vertices.map(function (v) { return v.clone(); });
  36387. return new Polygon(vertices, this.shared);
  36388. };
  36389. Polygon.prototype.flip = function () {
  36390. this.vertices.reverse().map(function (v) { v.flip(); });
  36391. this.plane.flip();
  36392. };
  36393. return Polygon;
  36394. })();
  36395. // # class Node
  36396. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  36397. // by picking a polygon to split along. That polygon (and all other coplanar
  36398. // polygons) are added directly to that node and the other polygons are added to
  36399. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  36400. // no distinction between internal and leaf nodes.
  36401. var Node = (function () {
  36402. function Node(polygons) {
  36403. this.plane = null;
  36404. this.front = null;
  36405. this.back = null;
  36406. this.polygons = [];
  36407. if (polygons) {
  36408. this.build(polygons);
  36409. }
  36410. }
  36411. Node.prototype.clone = function () {
  36412. var node = new Node();
  36413. node.plane = this.plane && this.plane.clone();
  36414. node.front = this.front && this.front.clone();
  36415. node.back = this.back && this.back.clone();
  36416. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  36417. return node;
  36418. };
  36419. // Convert solid space to empty space and empty space to solid space.
  36420. Node.prototype.invert = function () {
  36421. for (var i = 0; i < this.polygons.length; i++) {
  36422. this.polygons[i].flip();
  36423. }
  36424. if (this.plane) {
  36425. this.plane.flip();
  36426. }
  36427. if (this.front) {
  36428. this.front.invert();
  36429. }
  36430. if (this.back) {
  36431. this.back.invert();
  36432. }
  36433. var temp = this.front;
  36434. this.front = this.back;
  36435. this.back = temp;
  36436. };
  36437. // Recursively remove all polygons in `polygons` that are inside this BSP
  36438. // tree.
  36439. Node.prototype.clipPolygons = function (polygons) {
  36440. if (!this.plane)
  36441. return polygons.slice();
  36442. var front = [], back = [];
  36443. for (var i = 0; i < polygons.length; i++) {
  36444. this.plane.splitPolygon(polygons[i], front, back, front, back);
  36445. }
  36446. if (this.front) {
  36447. front = this.front.clipPolygons(front);
  36448. }
  36449. if (this.back) {
  36450. back = this.back.clipPolygons(back);
  36451. }
  36452. else {
  36453. back = [];
  36454. }
  36455. return front.concat(back);
  36456. };
  36457. // Remove all polygons in this BSP tree that are inside the other BSP tree
  36458. // `bsp`.
  36459. Node.prototype.clipTo = function (bsp) {
  36460. this.polygons = bsp.clipPolygons(this.polygons);
  36461. if (this.front)
  36462. this.front.clipTo(bsp);
  36463. if (this.back)
  36464. this.back.clipTo(bsp);
  36465. };
  36466. // Return a list of all polygons in this BSP tree.
  36467. Node.prototype.allPolygons = function () {
  36468. var polygons = this.polygons.slice();
  36469. if (this.front)
  36470. polygons = polygons.concat(this.front.allPolygons());
  36471. if (this.back)
  36472. polygons = polygons.concat(this.back.allPolygons());
  36473. return polygons;
  36474. };
  36475. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  36476. // new polygons are filtered down to the bottom of the tree and become new
  36477. // nodes there. Each set of polygons is partitioned using the first polygon
  36478. // (no heuristic is used to pick a good split).
  36479. Node.prototype.build = function (polygons) {
  36480. if (!polygons.length)
  36481. return;
  36482. if (!this.plane)
  36483. this.plane = polygons[0].plane.clone();
  36484. var front = [], back = [];
  36485. for (var i = 0; i < polygons.length; i++) {
  36486. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  36487. }
  36488. if (front.length) {
  36489. if (!this.front)
  36490. this.front = new Node();
  36491. this.front.build(front);
  36492. }
  36493. if (back.length) {
  36494. if (!this.back)
  36495. this.back = new Node();
  36496. this.back.build(back);
  36497. }
  36498. };
  36499. return Node;
  36500. })();
  36501. var CSG = (function () {
  36502. function CSG() {
  36503. this.polygons = new Array();
  36504. }
  36505. // Convert BABYLON.Mesh to BABYLON.CSG
  36506. CSG.FromMesh = function (mesh) {
  36507. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  36508. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  36509. if (mesh instanceof BABYLON.Mesh) {
  36510. mesh.computeWorldMatrix(true);
  36511. matrix = mesh.getWorldMatrix();
  36512. meshPosition = mesh.position.clone();
  36513. meshRotation = mesh.rotation.clone();
  36514. if (mesh.rotationQuaternion) {
  36515. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  36516. }
  36517. meshScaling = mesh.scaling.clone();
  36518. }
  36519. else {
  36520. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  36521. }
  36522. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36523. var subMeshes = mesh.subMeshes;
  36524. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  36525. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  36526. vertices = [];
  36527. for (var j = 0; j < 3; j++) {
  36528. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  36529. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  36530. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  36531. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  36532. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  36533. vertex = new Vertex(position, normal, uv);
  36534. vertices.push(vertex);
  36535. }
  36536. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  36537. // To handle the case of degenerated triangle
  36538. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  36539. if (polygon.plane)
  36540. polygons.push(polygon);
  36541. }
  36542. }
  36543. var csg = CSG.FromPolygons(polygons);
  36544. csg.matrix = matrix;
  36545. csg.position = meshPosition;
  36546. csg.rotation = meshRotation;
  36547. csg.scaling = meshScaling;
  36548. csg.rotationQuaternion = meshRotationQuaternion;
  36549. currentCSGMeshId++;
  36550. return csg;
  36551. };
  36552. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  36553. CSG.FromPolygons = function (polygons) {
  36554. var csg = new CSG();
  36555. csg.polygons = polygons;
  36556. return csg;
  36557. };
  36558. CSG.prototype.clone = function () {
  36559. var csg = new CSG();
  36560. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  36561. csg.copyTransformAttributes(this);
  36562. return csg;
  36563. };
  36564. CSG.prototype.toPolygons = function () {
  36565. return this.polygons;
  36566. };
  36567. CSG.prototype.union = function (csg) {
  36568. var a = new Node(this.clone().polygons);
  36569. var b = new Node(csg.clone().polygons);
  36570. a.clipTo(b);
  36571. b.clipTo(a);
  36572. b.invert();
  36573. b.clipTo(a);
  36574. b.invert();
  36575. a.build(b.allPolygons());
  36576. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  36577. };
  36578. CSG.prototype.unionInPlace = function (csg) {
  36579. var a = new Node(this.polygons);
  36580. var b = new Node(csg.polygons);
  36581. a.clipTo(b);
  36582. b.clipTo(a);
  36583. b.invert();
  36584. b.clipTo(a);
  36585. b.invert();
  36586. a.build(b.allPolygons());
  36587. this.polygons = a.allPolygons();
  36588. };
  36589. CSG.prototype.subtract = function (csg) {
  36590. var a = new Node(this.clone().polygons);
  36591. var b = new Node(csg.clone().polygons);
  36592. a.invert();
  36593. a.clipTo(b);
  36594. b.clipTo(a);
  36595. b.invert();
  36596. b.clipTo(a);
  36597. b.invert();
  36598. a.build(b.allPolygons());
  36599. a.invert();
  36600. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  36601. };
  36602. CSG.prototype.subtractInPlace = function (csg) {
  36603. var a = new Node(this.polygons);
  36604. var b = new Node(csg.polygons);
  36605. a.invert();
  36606. a.clipTo(b);
  36607. b.clipTo(a);
  36608. b.invert();
  36609. b.clipTo(a);
  36610. b.invert();
  36611. a.build(b.allPolygons());
  36612. a.invert();
  36613. this.polygons = a.allPolygons();
  36614. };
  36615. CSG.prototype.intersect = function (csg) {
  36616. var a = new Node(this.clone().polygons);
  36617. var b = new Node(csg.clone().polygons);
  36618. a.invert();
  36619. b.clipTo(a);
  36620. b.invert();
  36621. a.clipTo(b);
  36622. b.clipTo(a);
  36623. a.build(b.allPolygons());
  36624. a.invert();
  36625. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  36626. };
  36627. CSG.prototype.intersectInPlace = function (csg) {
  36628. var a = new Node(this.polygons);
  36629. var b = new Node(csg.polygons);
  36630. a.invert();
  36631. b.clipTo(a);
  36632. b.invert();
  36633. a.clipTo(b);
  36634. b.clipTo(a);
  36635. a.build(b.allPolygons());
  36636. a.invert();
  36637. this.polygons = a.allPolygons();
  36638. };
  36639. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  36640. // not modified.
  36641. CSG.prototype.inverse = function () {
  36642. var csg = this.clone();
  36643. csg.inverseInPlace();
  36644. return csg;
  36645. };
  36646. CSG.prototype.inverseInPlace = function () {
  36647. this.polygons.map(function (p) { p.flip(); });
  36648. };
  36649. // This is used to keep meshes transformations so they can be restored
  36650. // when we build back a Babylon Mesh
  36651. // NB : All CSG operations are performed in world coordinates
  36652. CSG.prototype.copyTransformAttributes = function (csg) {
  36653. this.matrix = csg.matrix;
  36654. this.position = csg.position;
  36655. this.rotation = csg.rotation;
  36656. this.scaling = csg.scaling;
  36657. this.rotationQuaternion = csg.rotationQuaternion;
  36658. return this;
  36659. };
  36660. // Build Raw mesh from CSG
  36661. // Coordinates here are in world space
  36662. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  36663. var matrix = this.matrix.clone();
  36664. matrix.invert();
  36665. 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;
  36666. if (keepSubMeshes) {
  36667. // Sort Polygons, since subMeshes are indices range
  36668. polygons.sort(function (a, b) {
  36669. if (a.shared.meshId === b.shared.meshId) {
  36670. return a.shared.subMeshId - b.shared.subMeshId;
  36671. }
  36672. else {
  36673. return a.shared.meshId - b.shared.meshId;
  36674. }
  36675. });
  36676. }
  36677. for (var i = 0, il = polygons.length; i < il; i++) {
  36678. polygon = polygons[i];
  36679. // Building SubMeshes
  36680. if (!subMesh_dict[polygon.shared.meshId]) {
  36681. subMesh_dict[polygon.shared.meshId] = {};
  36682. }
  36683. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  36684. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  36685. indexStart: +Infinity,
  36686. indexEnd: -Infinity,
  36687. materialIndex: polygon.shared.materialIndex
  36688. };
  36689. }
  36690. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  36691. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  36692. polygonIndices[0] = 0;
  36693. polygonIndices[1] = j - 1;
  36694. polygonIndices[2] = j;
  36695. for (var k = 0; k < 3; k++) {
  36696. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  36697. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  36698. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  36699. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  36700. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  36701. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  36702. // Check if 2 points can be merged
  36703. if (!(typeof vertex_idx !== 'undefined' &&
  36704. normals[vertex_idx * 3] === localNormal.x &&
  36705. normals[vertex_idx * 3 + 1] === localNormal.y &&
  36706. normals[vertex_idx * 3 + 2] === localNormal.z &&
  36707. uvs[vertex_idx * 2] === uv.x &&
  36708. uvs[vertex_idx * 2 + 1] === uv.y)) {
  36709. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  36710. uvs.push(uv.x, uv.y);
  36711. normals.push(normal.x, normal.y, normal.z);
  36712. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  36713. }
  36714. indices.push(vertex_idx);
  36715. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  36716. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  36717. currentIndex++;
  36718. }
  36719. }
  36720. }
  36721. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  36722. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  36723. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  36724. mesh.setIndices(indices);
  36725. if (keepSubMeshes) {
  36726. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  36727. var materialIndexOffset = 0, materialMaxIndex;
  36728. mesh.subMeshes = new Array();
  36729. for (var m in subMesh_dict) {
  36730. materialMaxIndex = -1;
  36731. for (var sm in subMesh_dict[m]) {
  36732. subMesh_obj = subMesh_dict[m][sm];
  36733. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  36734. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  36735. }
  36736. materialIndexOffset += ++materialMaxIndex;
  36737. }
  36738. }
  36739. return mesh;
  36740. };
  36741. // Build Mesh from CSG taking material and transforms into account
  36742. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  36743. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  36744. mesh.material = material;
  36745. mesh.position.copyFrom(this.position);
  36746. mesh.rotation.copyFrom(this.rotation);
  36747. if (this.rotationQuaternion) {
  36748. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  36749. }
  36750. mesh.scaling.copyFrom(this.scaling);
  36751. mesh.computeWorldMatrix(true);
  36752. return mesh;
  36753. };
  36754. return CSG;
  36755. })();
  36756. BABYLON.CSG = CSG;
  36757. })(BABYLON || (BABYLON = {}));
  36758. var BABYLON;
  36759. (function (BABYLON) {
  36760. var VRDistortionCorrectionPostProcess = (function (_super) {
  36761. __extends(VRDistortionCorrectionPostProcess, _super);
  36762. //ANY
  36763. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  36764. var _this = this;
  36765. _super.call(this, name, "vrDistortionCorrection", [
  36766. 'LensCenter',
  36767. 'Scale',
  36768. 'ScaleIn',
  36769. 'HmdWarpParam'
  36770. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  36771. this._isRightEye = isRightEye;
  36772. this._distortionFactors = vrMetrics.distortionK;
  36773. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  36774. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  36775. this.onSizeChanged = function () {
  36776. _this.aspectRatio = _this.width * .5 / _this.height;
  36777. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  36778. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  36779. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  36780. };
  36781. this.onApply = function (effect) {
  36782. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  36783. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  36784. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  36785. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  36786. };
  36787. }
  36788. return VRDistortionCorrectionPostProcess;
  36789. })(BABYLON.PostProcess);
  36790. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  36791. })(BABYLON || (BABYLON = {}));
  36792. // Mainly based on these 2 articles :
  36793. // 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
  36794. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  36795. var BABYLON;
  36796. (function (BABYLON) {
  36797. (function (JoystickAxis) {
  36798. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  36799. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  36800. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  36801. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  36802. var JoystickAxis = BABYLON.JoystickAxis;
  36803. var VirtualJoystick = (function () {
  36804. function VirtualJoystick(leftJoystick) {
  36805. var _this = this;
  36806. if (leftJoystick) {
  36807. this._leftJoystick = true;
  36808. }
  36809. else {
  36810. this._leftJoystick = false;
  36811. }
  36812. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  36813. VirtualJoystick._globalJoystickIndex++;
  36814. // By default left & right arrow keys are moving the X
  36815. // and up & down keys are moving the Y
  36816. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  36817. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  36818. this.reverseLeftRight = false;
  36819. this.reverseUpDown = false;
  36820. // collections of pointers
  36821. this._touches = new BABYLON.SmartCollection();
  36822. this.deltaPosition = BABYLON.Vector3.Zero();
  36823. this._joystickSensibility = 25;
  36824. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  36825. this._rotationSpeed = 25;
  36826. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  36827. this._rotateOnAxisRelativeToMesh = false;
  36828. this._onResize = function (evt) {
  36829. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  36830. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  36831. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  36832. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  36833. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  36834. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  36835. };
  36836. // injecting a canvas element on top of the canvas 3D game
  36837. if (!VirtualJoystick.vjCanvas) {
  36838. window.addEventListener("resize", this._onResize, false);
  36839. VirtualJoystick.vjCanvas = document.createElement("canvas");
  36840. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  36841. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  36842. VirtualJoystick.vjCanvas.width = window.innerWidth;
  36843. VirtualJoystick.vjCanvas.height = window.innerHeight;
  36844. VirtualJoystick.vjCanvas.style.width = "100%";
  36845. VirtualJoystick.vjCanvas.style.height = "100%";
  36846. VirtualJoystick.vjCanvas.style.position = "absolute";
  36847. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  36848. VirtualJoystick.vjCanvas.style.top = "0px";
  36849. VirtualJoystick.vjCanvas.style.left = "0px";
  36850. VirtualJoystick.vjCanvas.style.zIndex = "5";
  36851. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  36852. // Support for jQuery PEP polyfill
  36853. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  36854. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  36855. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  36856. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  36857. document.body.appendChild(VirtualJoystick.vjCanvas);
  36858. }
  36859. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  36860. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  36861. this.pressed = false;
  36862. // default joystick color
  36863. this._joystickColor = "cyan";
  36864. this._joystickPointerID = -1;
  36865. // current joystick position
  36866. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  36867. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  36868. // origin joystick position
  36869. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  36870. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  36871. this._onPointerDownHandlerRef = function (evt) {
  36872. _this._onPointerDown(evt);
  36873. };
  36874. this._onPointerMoveHandlerRef = function (evt) {
  36875. _this._onPointerMove(evt);
  36876. };
  36877. this._onPointerOutHandlerRef = function (evt) {
  36878. _this._onPointerUp(evt);
  36879. };
  36880. this._onPointerUpHandlerRef = function (evt) {
  36881. _this._onPointerUp(evt);
  36882. };
  36883. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  36884. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  36885. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  36886. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  36887. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  36888. evt.preventDefault(); // Disables system menu
  36889. }, false);
  36890. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  36891. }
  36892. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  36893. this._joystickSensibility = newJoystickSensibility;
  36894. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  36895. };
  36896. VirtualJoystick.prototype._onPointerDown = function (e) {
  36897. var positionOnScreenCondition;
  36898. e.preventDefault();
  36899. if (this._leftJoystick === true) {
  36900. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  36901. }
  36902. else {
  36903. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  36904. }
  36905. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  36906. // First contact will be dedicated to the virtual joystick
  36907. this._joystickPointerID = e.pointerId;
  36908. this._joystickPointerStartPos.x = e.clientX;
  36909. this._joystickPointerStartPos.y = e.clientY;
  36910. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  36911. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  36912. this._deltaJoystickVector.x = 0;
  36913. this._deltaJoystickVector.y = 0;
  36914. this.pressed = true;
  36915. this._touches.add(e.pointerId.toString(), e);
  36916. }
  36917. else {
  36918. // You can only trigger the action buttons with a joystick declared
  36919. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  36920. this._action();
  36921. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  36922. }
  36923. }
  36924. };
  36925. VirtualJoystick.prototype._onPointerMove = function (e) {
  36926. // If the current pointer is the one associated to the joystick (first touch contact)
  36927. if (this._joystickPointerID == e.pointerId) {
  36928. this._joystickPointerPos.x = e.clientX;
  36929. this._joystickPointerPos.y = e.clientY;
  36930. this._deltaJoystickVector = this._joystickPointerPos.clone();
  36931. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  36932. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  36933. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  36934. switch (this._axisTargetedByLeftAndRight) {
  36935. case JoystickAxis.X:
  36936. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  36937. break;
  36938. case JoystickAxis.Y:
  36939. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  36940. break;
  36941. case JoystickAxis.Z:
  36942. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  36943. break;
  36944. }
  36945. var directionUpDown = this.reverseUpDown ? 1 : -1;
  36946. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  36947. switch (this._axisTargetedByUpAndDown) {
  36948. case JoystickAxis.X:
  36949. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  36950. break;
  36951. case JoystickAxis.Y:
  36952. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  36953. break;
  36954. case JoystickAxis.Z:
  36955. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  36956. break;
  36957. }
  36958. }
  36959. else {
  36960. if (this._touches.item(e.pointerId.toString())) {
  36961. this._touches.item(e.pointerId.toString()).x = e.clientX;
  36962. this._touches.item(e.pointerId.toString()).y = e.clientY;
  36963. }
  36964. }
  36965. };
  36966. VirtualJoystick.prototype._onPointerUp = function (e) {
  36967. if (this._joystickPointerID == e.pointerId) {
  36968. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  36969. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  36970. this._joystickPointerID = -1;
  36971. this.pressed = false;
  36972. }
  36973. else {
  36974. var touch = this._touches.item(e.pointerId.toString());
  36975. if (touch) {
  36976. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  36977. }
  36978. }
  36979. this._deltaJoystickVector.x = 0;
  36980. this._deltaJoystickVector.y = 0;
  36981. this._touches.remove(e.pointerId.toString());
  36982. };
  36983. /**
  36984. * Change the color of the virtual joystick
  36985. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  36986. */
  36987. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  36988. this._joystickColor = newColor;
  36989. };
  36990. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  36991. this._action = action;
  36992. };
  36993. // Define which axis you'd like to control for left & right
  36994. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  36995. switch (axis) {
  36996. case JoystickAxis.X:
  36997. case JoystickAxis.Y:
  36998. case JoystickAxis.Z:
  36999. this._axisTargetedByLeftAndRight = axis;
  37000. break;
  37001. default:
  37002. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  37003. break;
  37004. }
  37005. };
  37006. // Define which axis you'd like to control for up & down
  37007. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  37008. switch (axis) {
  37009. case JoystickAxis.X:
  37010. case JoystickAxis.Y:
  37011. case JoystickAxis.Z:
  37012. this._axisTargetedByUpAndDown = axis;
  37013. break;
  37014. default:
  37015. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  37016. break;
  37017. }
  37018. };
  37019. VirtualJoystick.prototype._clearCanvas = function () {
  37020. if (this._leftJoystick) {
  37021. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  37022. }
  37023. else {
  37024. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  37025. }
  37026. };
  37027. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  37028. var _this = this;
  37029. if (this.pressed) {
  37030. this._touches.forEach(function (touch) {
  37031. if (touch.pointerId === _this._joystickPointerID) {
  37032. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  37033. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  37034. VirtualJoystick.vjCanvasContext.beginPath();
  37035. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  37036. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  37037. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  37038. VirtualJoystick.vjCanvasContext.stroke();
  37039. VirtualJoystick.vjCanvasContext.closePath();
  37040. VirtualJoystick.vjCanvasContext.beginPath();
  37041. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  37042. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  37043. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  37044. VirtualJoystick.vjCanvasContext.stroke();
  37045. VirtualJoystick.vjCanvasContext.closePath();
  37046. VirtualJoystick.vjCanvasContext.beginPath();
  37047. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  37048. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  37049. VirtualJoystick.vjCanvasContext.stroke();
  37050. VirtualJoystick.vjCanvasContext.closePath();
  37051. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  37052. }
  37053. else {
  37054. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  37055. VirtualJoystick.vjCanvasContext.beginPath();
  37056. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  37057. VirtualJoystick.vjCanvasContext.beginPath();
  37058. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  37059. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  37060. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  37061. VirtualJoystick.vjCanvasContext.stroke();
  37062. VirtualJoystick.vjCanvasContext.closePath();
  37063. touch.prevX = touch.x;
  37064. touch.prevY = touch.y;
  37065. }
  37066. ;
  37067. });
  37068. }
  37069. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  37070. };
  37071. VirtualJoystick.prototype.releaseCanvas = function () {
  37072. if (VirtualJoystick.vjCanvas) {
  37073. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  37074. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  37075. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  37076. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  37077. window.removeEventListener("resize", this._onResize);
  37078. document.body.removeChild(VirtualJoystick.vjCanvas);
  37079. VirtualJoystick.vjCanvas = null;
  37080. }
  37081. };
  37082. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  37083. VirtualJoystick._globalJoystickIndex = 0;
  37084. return VirtualJoystick;
  37085. })();
  37086. BABYLON.VirtualJoystick = VirtualJoystick;
  37087. })(BABYLON || (BABYLON = {}));
  37088. var BABYLON;
  37089. (function (BABYLON) {
  37090. // We're mainly based on the logic defined into the FreeCamera code
  37091. var VirtualJoysticksCamera = (function (_super) {
  37092. __extends(VirtualJoysticksCamera, _super);
  37093. function VirtualJoysticksCamera(name, position, scene) {
  37094. _super.call(this, name, position, scene);
  37095. this.inputs.addVirtualJoystick();
  37096. }
  37097. return VirtualJoysticksCamera;
  37098. })(BABYLON.FreeCamera);
  37099. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  37100. })(BABYLON || (BABYLON = {}));
  37101. var BABYLON;
  37102. (function (BABYLON) {
  37103. var AnaglyphPostProcess = (function (_super) {
  37104. __extends(AnaglyphPostProcess, _super);
  37105. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  37106. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  37107. }
  37108. return AnaglyphPostProcess;
  37109. })(BABYLON.PostProcess);
  37110. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  37111. })(BABYLON || (BABYLON = {}));
  37112. var BABYLON;
  37113. (function (BABYLON) {
  37114. var OutlineRenderer = (function () {
  37115. function OutlineRenderer(scene) {
  37116. this._scene = scene;
  37117. }
  37118. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  37119. var _this = this;
  37120. if (useOverlay === void 0) { useOverlay = false; }
  37121. var scene = this._scene;
  37122. var engine = this._scene.getEngine();
  37123. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  37124. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  37125. return;
  37126. }
  37127. var mesh = subMesh.getRenderingMesh();
  37128. var material = subMesh.getMaterial();
  37129. engine.enableEffect(this._effect);
  37130. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  37131. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  37132. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  37133. // Bones
  37134. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37135. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  37136. }
  37137. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  37138. // Alpha test
  37139. if (material && material.needAlphaTesting()) {
  37140. var alphaTexture = material.getAlphaTestTexture();
  37141. this._effect.setTexture("diffuseSampler", alphaTexture);
  37142. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  37143. }
  37144. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  37145. };
  37146. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  37147. var defines = [];
  37148. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  37149. var mesh = subMesh.getMesh();
  37150. var material = subMesh.getMaterial();
  37151. // Alpha test
  37152. if (material && material.needAlphaTesting()) {
  37153. defines.push("#define ALPHATEST");
  37154. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37155. attribs.push(BABYLON.VertexBuffer.UVKind);
  37156. defines.push("#define UV1");
  37157. }
  37158. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37159. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37160. defines.push("#define UV2");
  37161. }
  37162. }
  37163. // Bones
  37164. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37165. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37166. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37167. if (mesh.numBoneInfluencers > 4) {
  37168. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  37169. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  37170. }
  37171. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  37172. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  37173. }
  37174. else {
  37175. defines.push("#define NUM_BONE_INFLUENCERS 0");
  37176. }
  37177. // Instances
  37178. if (useInstances) {
  37179. defines.push("#define INSTANCES");
  37180. attribs.push("world0");
  37181. attribs.push("world1");
  37182. attribs.push("world2");
  37183. attribs.push("world3");
  37184. }
  37185. // Get correct effect
  37186. var join = defines.join("\n");
  37187. if (this._cachedDefines !== join) {
  37188. this._cachedDefines = join;
  37189. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  37190. }
  37191. return this._effect.isReady();
  37192. };
  37193. return OutlineRenderer;
  37194. })();
  37195. BABYLON.OutlineRenderer = OutlineRenderer;
  37196. })(BABYLON || (BABYLON = {}));
  37197. var BABYLON;
  37198. (function (BABYLON) {
  37199. var MeshAssetTask = (function () {
  37200. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  37201. this.name = name;
  37202. this.meshesNames = meshesNames;
  37203. this.rootUrl = rootUrl;
  37204. this.sceneFilename = sceneFilename;
  37205. this.isCompleted = false;
  37206. }
  37207. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37208. var _this = this;
  37209. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  37210. _this.loadedMeshes = meshes;
  37211. _this.loadedParticleSystems = particleSystems;
  37212. _this.loadedSkeletons = skeletons;
  37213. _this.isCompleted = true;
  37214. if (_this.onSuccess) {
  37215. _this.onSuccess(_this);
  37216. }
  37217. onSuccess();
  37218. }, null, function () {
  37219. if (_this.onError) {
  37220. _this.onError(_this);
  37221. }
  37222. onError();
  37223. });
  37224. };
  37225. return MeshAssetTask;
  37226. })();
  37227. BABYLON.MeshAssetTask = MeshAssetTask;
  37228. var TextFileAssetTask = (function () {
  37229. function TextFileAssetTask(name, url) {
  37230. this.name = name;
  37231. this.url = url;
  37232. this.isCompleted = false;
  37233. }
  37234. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37235. var _this = this;
  37236. BABYLON.Tools.LoadFile(this.url, function (data) {
  37237. _this.text = data;
  37238. _this.isCompleted = true;
  37239. if (_this.onSuccess) {
  37240. _this.onSuccess(_this);
  37241. }
  37242. onSuccess();
  37243. }, null, scene.database, false, function () {
  37244. if (_this.onError) {
  37245. _this.onError(_this);
  37246. }
  37247. onError();
  37248. });
  37249. };
  37250. return TextFileAssetTask;
  37251. })();
  37252. BABYLON.TextFileAssetTask = TextFileAssetTask;
  37253. var BinaryFileAssetTask = (function () {
  37254. function BinaryFileAssetTask(name, url) {
  37255. this.name = name;
  37256. this.url = url;
  37257. this.isCompleted = false;
  37258. }
  37259. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37260. var _this = this;
  37261. BABYLON.Tools.LoadFile(this.url, function (data) {
  37262. _this.data = data;
  37263. _this.isCompleted = true;
  37264. if (_this.onSuccess) {
  37265. _this.onSuccess(_this);
  37266. }
  37267. onSuccess();
  37268. }, null, scene.database, true, function () {
  37269. if (_this.onError) {
  37270. _this.onError(_this);
  37271. }
  37272. onError();
  37273. });
  37274. };
  37275. return BinaryFileAssetTask;
  37276. })();
  37277. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  37278. var ImageAssetTask = (function () {
  37279. function ImageAssetTask(name, url) {
  37280. this.name = name;
  37281. this.url = url;
  37282. this.isCompleted = false;
  37283. }
  37284. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37285. var _this = this;
  37286. var img = new Image();
  37287. img.onload = function () {
  37288. _this.image = img;
  37289. _this.isCompleted = true;
  37290. if (_this.onSuccess) {
  37291. _this.onSuccess(_this);
  37292. }
  37293. onSuccess();
  37294. };
  37295. img.onerror = function () {
  37296. if (_this.onError) {
  37297. _this.onError(_this);
  37298. }
  37299. onError();
  37300. };
  37301. img.src = this.url;
  37302. };
  37303. return ImageAssetTask;
  37304. })();
  37305. BABYLON.ImageAssetTask = ImageAssetTask;
  37306. var TextureAssetTask = (function () {
  37307. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  37308. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37309. this.name = name;
  37310. this.url = url;
  37311. this.noMipmap = noMipmap;
  37312. this.invertY = invertY;
  37313. this.samplingMode = samplingMode;
  37314. this.isCompleted = false;
  37315. }
  37316. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  37317. var _this = this;
  37318. var onload = function () {
  37319. _this.isCompleted = true;
  37320. if (_this.onSuccess) {
  37321. _this.onSuccess(_this);
  37322. }
  37323. onSuccess();
  37324. };
  37325. var onerror = function () {
  37326. if (_this.onError) {
  37327. _this.onError(_this);
  37328. }
  37329. onError();
  37330. };
  37331. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  37332. };
  37333. return TextureAssetTask;
  37334. })();
  37335. BABYLON.TextureAssetTask = TextureAssetTask;
  37336. var AssetsManager = (function () {
  37337. function AssetsManager(scene) {
  37338. this._tasks = new Array();
  37339. this._waitingTasksCount = 0;
  37340. this.useDefaultLoadingScreen = true;
  37341. this._scene = scene;
  37342. }
  37343. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  37344. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  37345. this._tasks.push(task);
  37346. return task;
  37347. };
  37348. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  37349. var task = new TextFileAssetTask(taskName, url);
  37350. this._tasks.push(task);
  37351. return task;
  37352. };
  37353. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  37354. var task = new BinaryFileAssetTask(taskName, url);
  37355. this._tasks.push(task);
  37356. return task;
  37357. };
  37358. AssetsManager.prototype.addImageTask = function (taskName, url) {
  37359. var task = new ImageAssetTask(taskName, url);
  37360. this._tasks.push(task);
  37361. return task;
  37362. };
  37363. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  37364. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37365. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  37366. this._tasks.push(task);
  37367. return task;
  37368. };
  37369. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  37370. this._waitingTasksCount--;
  37371. if (this._waitingTasksCount === 0) {
  37372. if (this.onFinish) {
  37373. this.onFinish(this._tasks);
  37374. }
  37375. this._scene.getEngine().hideLoadingUI();
  37376. }
  37377. };
  37378. AssetsManager.prototype._runTask = function (task) {
  37379. var _this = this;
  37380. task.run(this._scene, function () {
  37381. if (_this.onTaskSuccess) {
  37382. _this.onTaskSuccess(task);
  37383. }
  37384. _this._decreaseWaitingTasksCount();
  37385. }, function () {
  37386. if (_this.onTaskError) {
  37387. _this.onTaskError(task);
  37388. }
  37389. _this._decreaseWaitingTasksCount();
  37390. });
  37391. };
  37392. AssetsManager.prototype.reset = function () {
  37393. this._tasks = new Array();
  37394. return this;
  37395. };
  37396. AssetsManager.prototype.load = function () {
  37397. this._waitingTasksCount = this._tasks.length;
  37398. if (this._waitingTasksCount === 0) {
  37399. if (this.onFinish) {
  37400. this.onFinish(this._tasks);
  37401. }
  37402. return this;
  37403. }
  37404. if (this.useDefaultLoadingScreen) {
  37405. this._scene.getEngine().displayLoadingUI();
  37406. }
  37407. for (var index = 0; index < this._tasks.length; index++) {
  37408. var task = this._tasks[index];
  37409. this._runTask(task);
  37410. }
  37411. return this;
  37412. };
  37413. return AssetsManager;
  37414. })();
  37415. BABYLON.AssetsManager = AssetsManager;
  37416. })(BABYLON || (BABYLON = {}));
  37417. var BABYLON;
  37418. (function (BABYLON) {
  37419. var VRCameraMetrics = (function () {
  37420. function VRCameraMetrics() {
  37421. this.compensateDistortion = true;
  37422. }
  37423. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  37424. get: function () {
  37425. return this.hResolution / (2 * this.vResolution);
  37426. },
  37427. enumerable: true,
  37428. configurable: true
  37429. });
  37430. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  37431. get: function () {
  37432. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  37433. },
  37434. enumerable: true,
  37435. configurable: true
  37436. });
  37437. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  37438. get: function () {
  37439. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  37440. var h = (4 * meters) / this.hScreenSize;
  37441. return BABYLON.Matrix.Translation(h, 0, 0);
  37442. },
  37443. enumerable: true,
  37444. configurable: true
  37445. });
  37446. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  37447. get: function () {
  37448. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  37449. var h = (4 * meters) / this.hScreenSize;
  37450. return BABYLON.Matrix.Translation(-h, 0, 0);
  37451. },
  37452. enumerable: true,
  37453. configurable: true
  37454. });
  37455. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  37456. get: function () {
  37457. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  37458. },
  37459. enumerable: true,
  37460. configurable: true
  37461. });
  37462. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  37463. get: function () {
  37464. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  37465. },
  37466. enumerable: true,
  37467. configurable: true
  37468. });
  37469. VRCameraMetrics.GetDefault = function () {
  37470. var result = new VRCameraMetrics();
  37471. result.hResolution = 1280;
  37472. result.vResolution = 800;
  37473. result.hScreenSize = 0.149759993;
  37474. result.vScreenSize = 0.0935999975;
  37475. result.vScreenCenter = 0.0467999987,
  37476. result.eyeToScreenDistance = 0.0410000011;
  37477. result.lensSeparationDistance = 0.0635000020;
  37478. result.interpupillaryDistance = 0.0640000030;
  37479. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  37480. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  37481. result.postProcessScaleFactor = 1.714605507808412;
  37482. result.lensCenterOffset = 0.151976421;
  37483. return result;
  37484. };
  37485. return VRCameraMetrics;
  37486. })();
  37487. BABYLON.VRCameraMetrics = VRCameraMetrics;
  37488. })(BABYLON || (BABYLON = {}));
  37489. var BABYLON;
  37490. (function (BABYLON) {
  37491. var VRDeviceOrientationFreeCamera = (function (_super) {
  37492. __extends(VRDeviceOrientationFreeCamera, _super);
  37493. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion) {
  37494. if (compensateDistortion === void 0) { compensateDistortion = true; }
  37495. _super.call(this, name, position, scene);
  37496. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  37497. metrics.compensateDistortion = compensateDistortion;
  37498. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  37499. this.inputs.addVRDeviceOrientation();
  37500. }
  37501. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  37502. return "VRDeviceOrientationFreeCamera";
  37503. };
  37504. return VRDeviceOrientationFreeCamera;
  37505. })(BABYLON.FreeCamera);
  37506. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  37507. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  37508. __extends(VRDeviceOrientationArcRotateCamera, _super);
  37509. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion) {
  37510. if (compensateDistortion === void 0) { compensateDistortion = true; }
  37511. _super.call(this, name, alpha, beta, radius, target, scene);
  37512. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  37513. metrics.compensateDistortion = compensateDistortion;
  37514. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  37515. this.inputs.addVRDeviceOrientation();
  37516. }
  37517. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  37518. return "VRDeviceOrientationArcRotateCamera";
  37519. };
  37520. return VRDeviceOrientationArcRotateCamera;
  37521. })(BABYLON.ArcRotateCamera);
  37522. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  37523. })(BABYLON || (BABYLON = {}));
  37524. var BABYLON;
  37525. (function (BABYLON) {
  37526. var WebVRFreeCamera = (function (_super) {
  37527. __extends(WebVRFreeCamera, _super);
  37528. function WebVRFreeCamera(name, position, scene, compensateDistortion) {
  37529. if (compensateDistortion === void 0) { compensateDistortion = true; }
  37530. _super.call(this, name, position, scene);
  37531. this._hmdDevice = null;
  37532. this._sensorDevice = null;
  37533. this._cacheState = null;
  37534. this._cacheQuaternion = new BABYLON.Quaternion();
  37535. this._cacheRotation = BABYLON.Vector3.Zero();
  37536. this._vrEnabled = false;
  37537. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  37538. metrics.compensateDistortion = compensateDistortion;
  37539. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  37540. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  37541. }
  37542. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  37543. var size = devices.length;
  37544. var i = 0;
  37545. // Reset devices.
  37546. this._sensorDevice = null;
  37547. this._hmdDevice = null;
  37548. // Search for a HmdDevice.
  37549. while (i < size && this._hmdDevice === null) {
  37550. if (devices[i] instanceof HMDVRDevice) {
  37551. this._hmdDevice = devices[i];
  37552. }
  37553. i++;
  37554. }
  37555. i = 0;
  37556. while (i < size && this._sensorDevice === null) {
  37557. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  37558. this._sensorDevice = devices[i];
  37559. }
  37560. i++;
  37561. }
  37562. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  37563. };
  37564. WebVRFreeCamera.prototype._checkInputs = function () {
  37565. if (this._vrEnabled) {
  37566. this._cacheState = this._sensorDevice.getState();
  37567. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  37568. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  37569. this.rotation.x = -this._cacheRotation.x;
  37570. this.rotation.y = -this._cacheRotation.y;
  37571. this.rotation.z = this._cacheRotation.z;
  37572. }
  37573. _super.prototype._checkInputs.call(this);
  37574. };
  37575. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  37576. _super.prototype.attachControl.call(this, element, noPreventDefault);
  37577. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  37578. if (navigator.getVRDevices) {
  37579. navigator.getVRDevices().then(this._getWebVRDevices);
  37580. }
  37581. else if (navigator.mozGetVRDevices) {
  37582. navigator.mozGetVRDevices(this._getWebVRDevices);
  37583. }
  37584. };
  37585. WebVRFreeCamera.prototype.detachControl = function (element) {
  37586. _super.prototype.detachControl.call(this, element);
  37587. this._vrEnabled = false;
  37588. };
  37589. WebVRFreeCamera.prototype.getTypeName = function () {
  37590. return "WebVRFreeCamera";
  37591. };
  37592. return WebVRFreeCamera;
  37593. })(BABYLON.FreeCamera);
  37594. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  37595. })(BABYLON || (BABYLON = {}));
  37596. var BABYLON;
  37597. (function (BABYLON) {
  37598. // Standard optimizations
  37599. var SceneOptimization = (function () {
  37600. function SceneOptimization(priority) {
  37601. if (priority === void 0) { priority = 0; }
  37602. this.priority = priority;
  37603. this.apply = function (scene) {
  37604. return true; // Return true if everything that can be done was applied
  37605. };
  37606. }
  37607. return SceneOptimization;
  37608. })();
  37609. BABYLON.SceneOptimization = SceneOptimization;
  37610. var TextureOptimization = (function (_super) {
  37611. __extends(TextureOptimization, _super);
  37612. function TextureOptimization(priority, maximumSize) {
  37613. var _this = this;
  37614. if (priority === void 0) { priority = 0; }
  37615. if (maximumSize === void 0) { maximumSize = 1024; }
  37616. _super.call(this, priority);
  37617. this.priority = priority;
  37618. this.maximumSize = maximumSize;
  37619. this.apply = function (scene) {
  37620. var allDone = true;
  37621. for (var index = 0; index < scene.textures.length; index++) {
  37622. var texture = scene.textures[index];
  37623. if (!texture.canRescale) {
  37624. continue;
  37625. }
  37626. var currentSize = texture.getSize();
  37627. var maxDimension = Math.max(currentSize.width, currentSize.height);
  37628. if (maxDimension > _this.maximumSize) {
  37629. texture.scale(0.5);
  37630. allDone = false;
  37631. }
  37632. }
  37633. return allDone;
  37634. };
  37635. }
  37636. return TextureOptimization;
  37637. })(SceneOptimization);
  37638. BABYLON.TextureOptimization = TextureOptimization;
  37639. var HardwareScalingOptimization = (function (_super) {
  37640. __extends(HardwareScalingOptimization, _super);
  37641. function HardwareScalingOptimization(priority, maximumScale) {
  37642. var _this = this;
  37643. if (priority === void 0) { priority = 0; }
  37644. if (maximumScale === void 0) { maximumScale = 2; }
  37645. _super.call(this, priority);
  37646. this.priority = priority;
  37647. this.maximumScale = maximumScale;
  37648. this._currentScale = 1;
  37649. this.apply = function (scene) {
  37650. _this._currentScale++;
  37651. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  37652. return _this._currentScale >= _this.maximumScale;
  37653. };
  37654. }
  37655. return HardwareScalingOptimization;
  37656. })(SceneOptimization);
  37657. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  37658. var ShadowsOptimization = (function (_super) {
  37659. __extends(ShadowsOptimization, _super);
  37660. function ShadowsOptimization() {
  37661. _super.apply(this, arguments);
  37662. this.apply = function (scene) {
  37663. scene.shadowsEnabled = false;
  37664. return true;
  37665. };
  37666. }
  37667. return ShadowsOptimization;
  37668. })(SceneOptimization);
  37669. BABYLON.ShadowsOptimization = ShadowsOptimization;
  37670. var PostProcessesOptimization = (function (_super) {
  37671. __extends(PostProcessesOptimization, _super);
  37672. function PostProcessesOptimization() {
  37673. _super.apply(this, arguments);
  37674. this.apply = function (scene) {
  37675. scene.postProcessesEnabled = false;
  37676. return true;
  37677. };
  37678. }
  37679. return PostProcessesOptimization;
  37680. })(SceneOptimization);
  37681. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  37682. var LensFlaresOptimization = (function (_super) {
  37683. __extends(LensFlaresOptimization, _super);
  37684. function LensFlaresOptimization() {
  37685. _super.apply(this, arguments);
  37686. this.apply = function (scene) {
  37687. scene.lensFlaresEnabled = false;
  37688. return true;
  37689. };
  37690. }
  37691. return LensFlaresOptimization;
  37692. })(SceneOptimization);
  37693. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  37694. var ParticlesOptimization = (function (_super) {
  37695. __extends(ParticlesOptimization, _super);
  37696. function ParticlesOptimization() {
  37697. _super.apply(this, arguments);
  37698. this.apply = function (scene) {
  37699. scene.particlesEnabled = false;
  37700. return true;
  37701. };
  37702. }
  37703. return ParticlesOptimization;
  37704. })(SceneOptimization);
  37705. BABYLON.ParticlesOptimization = ParticlesOptimization;
  37706. var RenderTargetsOptimization = (function (_super) {
  37707. __extends(RenderTargetsOptimization, _super);
  37708. function RenderTargetsOptimization() {
  37709. _super.apply(this, arguments);
  37710. this.apply = function (scene) {
  37711. scene.renderTargetsEnabled = false;
  37712. return true;
  37713. };
  37714. }
  37715. return RenderTargetsOptimization;
  37716. })(SceneOptimization);
  37717. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  37718. var MergeMeshesOptimization = (function (_super) {
  37719. __extends(MergeMeshesOptimization, _super);
  37720. function MergeMeshesOptimization() {
  37721. var _this = this;
  37722. _super.apply(this, arguments);
  37723. this._canBeMerged = function (abstractMesh) {
  37724. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  37725. return false;
  37726. }
  37727. var mesh = abstractMesh;
  37728. if (!mesh.isVisible || !mesh.isEnabled()) {
  37729. return false;
  37730. }
  37731. if (mesh.instances.length > 0) {
  37732. return false;
  37733. }
  37734. if (mesh.skeleton || mesh.hasLODLevels) {
  37735. return false;
  37736. }
  37737. if (mesh.parent) {
  37738. return false;
  37739. }
  37740. return true;
  37741. };
  37742. this.apply = function (scene, updateSelectionTree) {
  37743. var globalPool = scene.meshes.slice(0);
  37744. var globalLength = globalPool.length;
  37745. for (var index = 0; index < globalLength; index++) {
  37746. var currentPool = new Array();
  37747. var current = globalPool[index];
  37748. // Checks
  37749. if (!_this._canBeMerged(current)) {
  37750. continue;
  37751. }
  37752. currentPool.push(current);
  37753. // Find compatible meshes
  37754. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  37755. var otherMesh = globalPool[subIndex];
  37756. if (!_this._canBeMerged(otherMesh)) {
  37757. continue;
  37758. }
  37759. if (otherMesh.material !== current.material) {
  37760. continue;
  37761. }
  37762. if (otherMesh.checkCollisions !== current.checkCollisions) {
  37763. continue;
  37764. }
  37765. currentPool.push(otherMesh);
  37766. globalLength--;
  37767. globalPool.splice(subIndex, 1);
  37768. subIndex--;
  37769. }
  37770. if (currentPool.length < 2) {
  37771. continue;
  37772. }
  37773. // Merge meshes
  37774. BABYLON.Mesh.MergeMeshes(currentPool);
  37775. }
  37776. if (updateSelectionTree != undefined) {
  37777. if (updateSelectionTree) {
  37778. scene.createOrUpdateSelectionOctree();
  37779. }
  37780. }
  37781. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  37782. scene.createOrUpdateSelectionOctree();
  37783. }
  37784. return true;
  37785. };
  37786. }
  37787. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  37788. get: function () {
  37789. return MergeMeshesOptimization._UpdateSelectionTree;
  37790. },
  37791. set: function (value) {
  37792. MergeMeshesOptimization._UpdateSelectionTree = value;
  37793. },
  37794. enumerable: true,
  37795. configurable: true
  37796. });
  37797. MergeMeshesOptimization._UpdateSelectionTree = false;
  37798. return MergeMeshesOptimization;
  37799. })(SceneOptimization);
  37800. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  37801. // Options
  37802. var SceneOptimizerOptions = (function () {
  37803. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  37804. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  37805. if (trackerDuration === void 0) { trackerDuration = 2000; }
  37806. this.targetFrameRate = targetFrameRate;
  37807. this.trackerDuration = trackerDuration;
  37808. this.optimizations = new Array();
  37809. }
  37810. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  37811. var result = new SceneOptimizerOptions(targetFrameRate);
  37812. var priority = 0;
  37813. result.optimizations.push(new MergeMeshesOptimization(priority));
  37814. result.optimizations.push(new ShadowsOptimization(priority));
  37815. result.optimizations.push(new LensFlaresOptimization(priority));
  37816. // Next priority
  37817. priority++;
  37818. result.optimizations.push(new PostProcessesOptimization(priority));
  37819. result.optimizations.push(new ParticlesOptimization(priority));
  37820. // Next priority
  37821. priority++;
  37822. result.optimizations.push(new TextureOptimization(priority, 1024));
  37823. return result;
  37824. };
  37825. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  37826. var result = new SceneOptimizerOptions(targetFrameRate);
  37827. var priority = 0;
  37828. result.optimizations.push(new MergeMeshesOptimization(priority));
  37829. result.optimizations.push(new ShadowsOptimization(priority));
  37830. result.optimizations.push(new LensFlaresOptimization(priority));
  37831. // Next priority
  37832. priority++;
  37833. result.optimizations.push(new PostProcessesOptimization(priority));
  37834. result.optimizations.push(new ParticlesOptimization(priority));
  37835. // Next priority
  37836. priority++;
  37837. result.optimizations.push(new TextureOptimization(priority, 512));
  37838. // Next priority
  37839. priority++;
  37840. result.optimizations.push(new RenderTargetsOptimization(priority));
  37841. // Next priority
  37842. priority++;
  37843. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  37844. return result;
  37845. };
  37846. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  37847. var result = new SceneOptimizerOptions(targetFrameRate);
  37848. var priority = 0;
  37849. result.optimizations.push(new MergeMeshesOptimization(priority));
  37850. result.optimizations.push(new ShadowsOptimization(priority));
  37851. result.optimizations.push(new LensFlaresOptimization(priority));
  37852. // Next priority
  37853. priority++;
  37854. result.optimizations.push(new PostProcessesOptimization(priority));
  37855. result.optimizations.push(new ParticlesOptimization(priority));
  37856. // Next priority
  37857. priority++;
  37858. result.optimizations.push(new TextureOptimization(priority, 256));
  37859. // Next priority
  37860. priority++;
  37861. result.optimizations.push(new RenderTargetsOptimization(priority));
  37862. // Next priority
  37863. priority++;
  37864. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  37865. return result;
  37866. };
  37867. return SceneOptimizerOptions;
  37868. })();
  37869. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  37870. // Scene optimizer tool
  37871. var SceneOptimizer = (function () {
  37872. function SceneOptimizer() {
  37873. }
  37874. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  37875. // TODO: add an epsilon
  37876. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  37877. if (onSuccess) {
  37878. onSuccess();
  37879. }
  37880. return;
  37881. }
  37882. // Apply current level of optimizations
  37883. var allDone = true;
  37884. var noOptimizationApplied = true;
  37885. for (var index = 0; index < options.optimizations.length; index++) {
  37886. var optimization = options.optimizations[index];
  37887. if (optimization.priority === currentPriorityLevel) {
  37888. noOptimizationApplied = false;
  37889. allDone = allDone && optimization.apply(scene);
  37890. }
  37891. }
  37892. // If no optimization was applied, this is a failure :(
  37893. if (noOptimizationApplied) {
  37894. if (onFailure) {
  37895. onFailure();
  37896. }
  37897. return;
  37898. }
  37899. // If all optimizations were done, move to next level
  37900. if (allDone) {
  37901. currentPriorityLevel++;
  37902. }
  37903. // Let's the system running for a specific amount of time before checking FPS
  37904. scene.executeWhenReady(function () {
  37905. setTimeout(function () {
  37906. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  37907. }, options.trackerDuration);
  37908. });
  37909. };
  37910. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  37911. if (!options) {
  37912. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  37913. }
  37914. // Let's the system running for a specific amount of time before checking FPS
  37915. scene.executeWhenReady(function () {
  37916. setTimeout(function () {
  37917. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  37918. }, options.trackerDuration);
  37919. });
  37920. };
  37921. return SceneOptimizer;
  37922. })();
  37923. BABYLON.SceneOptimizer = SceneOptimizer;
  37924. })(BABYLON || (BABYLON = {}));
  37925. var BABYLON;
  37926. (function (BABYLON) {
  37927. var Internals;
  37928. (function (Internals) {
  37929. var MeshLODLevel = (function () {
  37930. function MeshLODLevel(distance, mesh) {
  37931. this.distance = distance;
  37932. this.mesh = mesh;
  37933. }
  37934. return MeshLODLevel;
  37935. })();
  37936. Internals.MeshLODLevel = MeshLODLevel;
  37937. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  37938. })(BABYLON || (BABYLON = {}));
  37939. var BABYLON;
  37940. (function (BABYLON) {
  37941. var RawTexture = (function (_super) {
  37942. __extends(RawTexture, _super);
  37943. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  37944. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37945. if (invertY === void 0) { invertY = false; }
  37946. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37947. _super.call(this, null, scene, !generateMipMaps, invertY);
  37948. this.format = format;
  37949. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  37950. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37951. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37952. }
  37953. RawTexture.prototype.update = function (data) {
  37954. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  37955. };
  37956. // Statics
  37957. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  37958. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37959. if (invertY === void 0) { invertY = false; }
  37960. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37961. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  37962. };
  37963. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  37964. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37965. if (invertY === void 0) { invertY = false; }
  37966. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37967. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  37968. };
  37969. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  37970. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37971. if (invertY === void 0) { invertY = false; }
  37972. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37973. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  37974. };
  37975. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  37976. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37977. if (invertY === void 0) { invertY = false; }
  37978. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37979. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  37980. };
  37981. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  37982. if (generateMipMaps === void 0) { generateMipMaps = true; }
  37983. if (invertY === void 0) { invertY = false; }
  37984. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37985. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  37986. };
  37987. return RawTexture;
  37988. })(BABYLON.Texture);
  37989. BABYLON.RawTexture = RawTexture;
  37990. })(BABYLON || (BABYLON = {}));
  37991. var BABYLON;
  37992. (function (BABYLON) {
  37993. var IndexedVector2 = (function (_super) {
  37994. __extends(IndexedVector2, _super);
  37995. function IndexedVector2(original, index) {
  37996. _super.call(this, original.x, original.y);
  37997. this.index = index;
  37998. }
  37999. return IndexedVector2;
  38000. })(BABYLON.Vector2);
  38001. var PolygonPoints = (function () {
  38002. function PolygonPoints() {
  38003. this.elements = new Array();
  38004. }
  38005. PolygonPoints.prototype.add = function (originalPoints) {
  38006. var _this = this;
  38007. var result = new Array();
  38008. originalPoints.forEach(function (point) {
  38009. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  38010. var newPoint = new IndexedVector2(point, _this.elements.length);
  38011. result.push(newPoint);
  38012. _this.elements.push(newPoint);
  38013. }
  38014. });
  38015. return result;
  38016. };
  38017. PolygonPoints.prototype.computeBounds = function () {
  38018. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  38019. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  38020. this.elements.forEach(function (point) {
  38021. // x
  38022. if (point.x < lmin.x) {
  38023. lmin.x = point.x;
  38024. }
  38025. else if (point.x > lmax.x) {
  38026. lmax.x = point.x;
  38027. }
  38028. // y
  38029. if (point.y < lmin.y) {
  38030. lmin.y = point.y;
  38031. }
  38032. else if (point.y > lmax.y) {
  38033. lmax.y = point.y;
  38034. }
  38035. });
  38036. return {
  38037. min: lmin,
  38038. max: lmax,
  38039. width: lmax.x - lmin.x,
  38040. height: lmax.y - lmin.y
  38041. };
  38042. };
  38043. return PolygonPoints;
  38044. })();
  38045. var Polygon = (function () {
  38046. function Polygon() {
  38047. }
  38048. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  38049. return [
  38050. new BABYLON.Vector2(xmin, ymin),
  38051. new BABYLON.Vector2(xmax, ymin),
  38052. new BABYLON.Vector2(xmax, ymax),
  38053. new BABYLON.Vector2(xmin, ymax)
  38054. ];
  38055. };
  38056. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  38057. if (cx === void 0) { cx = 0; }
  38058. if (cy === void 0) { cy = 0; }
  38059. if (numberOfSides === void 0) { numberOfSides = 32; }
  38060. var result = new Array();
  38061. var angle = 0;
  38062. var increment = (Math.PI * 2) / numberOfSides;
  38063. for (var i = 0; i < numberOfSides; i++) {
  38064. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  38065. angle -= increment;
  38066. }
  38067. return result;
  38068. };
  38069. Polygon.Parse = function (input) {
  38070. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  38071. var i, result = [];
  38072. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  38073. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  38074. }
  38075. return result;
  38076. };
  38077. Polygon.StartingAt = function (x, y) {
  38078. return BABYLON.Path2.StartingAt(x, y);
  38079. };
  38080. return Polygon;
  38081. })();
  38082. BABYLON.Polygon = Polygon;
  38083. var PolygonMeshBuilder = (function () {
  38084. function PolygonMeshBuilder(name, contours, scene) {
  38085. this._points = new PolygonPoints();
  38086. this._outlinepoints = new PolygonPoints();
  38087. this._holes = [];
  38088. if (!("poly2tri" in window)) {
  38089. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  38090. }
  38091. this._name = name;
  38092. this._scene = scene;
  38093. var points;
  38094. if (contours instanceof BABYLON.Path2) {
  38095. points = contours.getPoints();
  38096. }
  38097. else {
  38098. points = contours;
  38099. }
  38100. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  38101. this._outlinepoints.add(points);
  38102. }
  38103. PolygonMeshBuilder.prototype.addHole = function (hole) {
  38104. this._swctx.addHole(this._points.add(hole));
  38105. var holepoints = new PolygonPoints();
  38106. holepoints.add(hole);
  38107. this._holes.push(holepoints);
  38108. return this;
  38109. };
  38110. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  38111. var _this = this;
  38112. if (updatable === void 0) { updatable = false; }
  38113. var result = new BABYLON.Mesh(this._name, this._scene);
  38114. var normals = [];
  38115. var positions = [];
  38116. var uvs = [];
  38117. var bounds = this._points.computeBounds();
  38118. this._points.elements.forEach(function (p) {
  38119. normals.push(0, 1.0, 0);
  38120. positions.push(p.x, 0, p.y);
  38121. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  38122. });
  38123. var indices = [];
  38124. this._swctx.triangulate();
  38125. this._swctx.getTriangles().forEach(function (triangle) {
  38126. triangle.getPoints().forEach(function (point) {
  38127. indices.push(point.index);
  38128. });
  38129. });
  38130. if (depth > 0) {
  38131. var positionscount = (positions.length / 3); //get the current pointcount
  38132. this._points.elements.forEach(function (p) {
  38133. normals.push(0, -1.0, 0);
  38134. positions.push(p.x, -depth, p.y);
  38135. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  38136. });
  38137. var p1; //we need to change order of point so the triangles are made in the rigth way.
  38138. var p2;
  38139. var poscounter = 0;
  38140. this._swctx.getTriangles().forEach(function (triangle) {
  38141. triangle.getPoints().forEach(function (point) {
  38142. switch (poscounter) {
  38143. case 0:
  38144. p1 = point;
  38145. break;
  38146. case 1:
  38147. p2 = point;
  38148. break;
  38149. case 2:
  38150. indices.push(point.index + positionscount);
  38151. indices.push(p2.index + positionscount);
  38152. indices.push(p1.index + positionscount);
  38153. poscounter = -1;
  38154. break;
  38155. }
  38156. poscounter++;
  38157. //indices.push((<IndexedVector2>point).index + positionscount);
  38158. });
  38159. });
  38160. //Add the sides
  38161. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  38162. this._holes.forEach(function (hole) {
  38163. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  38164. });
  38165. }
  38166. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  38167. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  38168. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  38169. result.setIndices(indices);
  38170. return result;
  38171. };
  38172. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  38173. var StartIndex = positions.length / 3;
  38174. var ulength = 0;
  38175. for (var i = 0; i < points.elements.length; i++) {
  38176. var p = points.elements[i];
  38177. var p1;
  38178. if ((i + 1) > points.elements.length - 1) {
  38179. p1 = points.elements[0];
  38180. }
  38181. else {
  38182. p1 = points.elements[i + 1];
  38183. }
  38184. positions.push(p.x, 0, p.y);
  38185. positions.push(p.x, -depth, p.y);
  38186. positions.push(p1.x, 0, p1.y);
  38187. positions.push(p1.x, -depth, p1.y);
  38188. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  38189. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  38190. var v3 = v2.subtract(v1);
  38191. var v4 = new BABYLON.Vector3(0, 1, 0);
  38192. var vn = BABYLON.Vector3.Cross(v3, v4);
  38193. vn = vn.normalize();
  38194. uvs.push(ulength / bounds.width, 0);
  38195. uvs.push(ulength / bounds.width, 1);
  38196. ulength += v3.length();
  38197. uvs.push((ulength / bounds.width), 0);
  38198. uvs.push((ulength / bounds.width), 1);
  38199. if (!flip) {
  38200. normals.push(-vn.x, -vn.y, -vn.z);
  38201. normals.push(-vn.x, -vn.y, -vn.z);
  38202. normals.push(-vn.x, -vn.y, -vn.z);
  38203. normals.push(-vn.x, -vn.y, -vn.z);
  38204. indices.push(StartIndex);
  38205. indices.push(StartIndex + 1);
  38206. indices.push(StartIndex + 2);
  38207. indices.push(StartIndex + 1);
  38208. indices.push(StartIndex + 3);
  38209. indices.push(StartIndex + 2);
  38210. }
  38211. else {
  38212. normals.push(vn.x, vn.y, vn.z);
  38213. normals.push(vn.x, vn.y, vn.z);
  38214. normals.push(vn.x, vn.y, vn.z);
  38215. normals.push(vn.x, vn.y, vn.z);
  38216. indices.push(StartIndex);
  38217. indices.push(StartIndex + 2);
  38218. indices.push(StartIndex + 1);
  38219. indices.push(StartIndex + 1);
  38220. indices.push(StartIndex + 2);
  38221. indices.push(StartIndex + 3);
  38222. }
  38223. StartIndex += 4;
  38224. }
  38225. ;
  38226. };
  38227. return PolygonMeshBuilder;
  38228. })();
  38229. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  38230. })(BABYLON || (BABYLON = {}));
  38231. var BABYLON;
  38232. (function (BABYLON) {
  38233. var Octree = (function () {
  38234. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  38235. if (maxDepth === void 0) { maxDepth = 2; }
  38236. this.maxDepth = maxDepth;
  38237. this.dynamicContent = new Array();
  38238. this._maxBlockCapacity = maxBlockCapacity || 64;
  38239. this._selectionContent = new BABYLON.SmartArray(1024);
  38240. this._creationFunc = creationFunc;
  38241. }
  38242. // Methods
  38243. Octree.prototype.update = function (worldMin, worldMax, entries) {
  38244. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  38245. };
  38246. Octree.prototype.addMesh = function (entry) {
  38247. for (var index = 0; index < this.blocks.length; index++) {
  38248. var block = this.blocks[index];
  38249. block.addEntry(entry);
  38250. }
  38251. };
  38252. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  38253. this._selectionContent.reset();
  38254. for (var index = 0; index < this.blocks.length; index++) {
  38255. var block = this.blocks[index];
  38256. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  38257. }
  38258. if (allowDuplicate) {
  38259. this._selectionContent.concat(this.dynamicContent);
  38260. }
  38261. else {
  38262. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  38263. }
  38264. return this._selectionContent;
  38265. };
  38266. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  38267. this._selectionContent.reset();
  38268. for (var index = 0; index < this.blocks.length; index++) {
  38269. var block = this.blocks[index];
  38270. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  38271. }
  38272. if (allowDuplicate) {
  38273. this._selectionContent.concat(this.dynamicContent);
  38274. }
  38275. else {
  38276. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  38277. }
  38278. return this._selectionContent;
  38279. };
  38280. Octree.prototype.intersectsRay = function (ray) {
  38281. this._selectionContent.reset();
  38282. for (var index = 0; index < this.blocks.length; index++) {
  38283. var block = this.blocks[index];
  38284. block.intersectsRay(ray, this._selectionContent);
  38285. }
  38286. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  38287. return this._selectionContent;
  38288. };
  38289. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  38290. target.blocks = new Array();
  38291. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  38292. // Segmenting space
  38293. for (var x = 0; x < 2; x++) {
  38294. for (var y = 0; y < 2; y++) {
  38295. for (var z = 0; z < 2; z++) {
  38296. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  38297. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  38298. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  38299. block.addEntries(entries);
  38300. target.blocks.push(block);
  38301. }
  38302. }
  38303. }
  38304. };
  38305. Octree.CreationFuncForMeshes = function (entry, block) {
  38306. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  38307. block.entries.push(entry);
  38308. }
  38309. };
  38310. Octree.CreationFuncForSubMeshes = function (entry, block) {
  38311. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  38312. block.entries.push(entry);
  38313. }
  38314. };
  38315. return Octree;
  38316. })();
  38317. BABYLON.Octree = Octree;
  38318. })(BABYLON || (BABYLON = {}));
  38319. var BABYLON;
  38320. (function (BABYLON) {
  38321. var OctreeBlock = (function () {
  38322. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  38323. this.entries = new Array();
  38324. this._boundingVectors = new Array();
  38325. this._capacity = capacity;
  38326. this._depth = depth;
  38327. this._maxDepth = maxDepth;
  38328. this._creationFunc = creationFunc;
  38329. this._minPoint = minPoint;
  38330. this._maxPoint = maxPoint;
  38331. this._boundingVectors.push(minPoint.clone());
  38332. this._boundingVectors.push(maxPoint.clone());
  38333. this._boundingVectors.push(minPoint.clone());
  38334. this._boundingVectors[2].x = maxPoint.x;
  38335. this._boundingVectors.push(minPoint.clone());
  38336. this._boundingVectors[3].y = maxPoint.y;
  38337. this._boundingVectors.push(minPoint.clone());
  38338. this._boundingVectors[4].z = maxPoint.z;
  38339. this._boundingVectors.push(maxPoint.clone());
  38340. this._boundingVectors[5].z = minPoint.z;
  38341. this._boundingVectors.push(maxPoint.clone());
  38342. this._boundingVectors[6].x = minPoint.x;
  38343. this._boundingVectors.push(maxPoint.clone());
  38344. this._boundingVectors[7].y = minPoint.y;
  38345. }
  38346. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  38347. // Property
  38348. get: function () {
  38349. return this._capacity;
  38350. },
  38351. enumerable: true,
  38352. configurable: true
  38353. });
  38354. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  38355. get: function () {
  38356. return this._minPoint;
  38357. },
  38358. enumerable: true,
  38359. configurable: true
  38360. });
  38361. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  38362. get: function () {
  38363. return this._maxPoint;
  38364. },
  38365. enumerable: true,
  38366. configurable: true
  38367. });
  38368. // Methods
  38369. OctreeBlock.prototype.addEntry = function (entry) {
  38370. if (this.blocks) {
  38371. for (var index = 0; index < this.blocks.length; index++) {
  38372. var block = this.blocks[index];
  38373. block.addEntry(entry);
  38374. }
  38375. return;
  38376. }
  38377. this._creationFunc(entry, this);
  38378. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  38379. this.createInnerBlocks();
  38380. }
  38381. };
  38382. OctreeBlock.prototype.addEntries = function (entries) {
  38383. for (var index = 0; index < entries.length; index++) {
  38384. var mesh = entries[index];
  38385. this.addEntry(mesh);
  38386. }
  38387. };
  38388. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  38389. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  38390. if (this.blocks) {
  38391. for (var index = 0; index < this.blocks.length; index++) {
  38392. var block = this.blocks[index];
  38393. block.select(frustumPlanes, selection, allowDuplicate);
  38394. }
  38395. return;
  38396. }
  38397. if (allowDuplicate) {
  38398. selection.concat(this.entries);
  38399. }
  38400. else {
  38401. selection.concatWithNoDuplicate(this.entries);
  38402. }
  38403. }
  38404. };
  38405. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  38406. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  38407. if (this.blocks) {
  38408. for (var index = 0; index < this.blocks.length; index++) {
  38409. var block = this.blocks[index];
  38410. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  38411. }
  38412. return;
  38413. }
  38414. if (allowDuplicate) {
  38415. selection.concat(this.entries);
  38416. }
  38417. else {
  38418. selection.concatWithNoDuplicate(this.entries);
  38419. }
  38420. }
  38421. };
  38422. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  38423. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  38424. if (this.blocks) {
  38425. for (var index = 0; index < this.blocks.length; index++) {
  38426. var block = this.blocks[index];
  38427. block.intersectsRay(ray, selection);
  38428. }
  38429. return;
  38430. }
  38431. selection.concatWithNoDuplicate(this.entries);
  38432. }
  38433. };
  38434. OctreeBlock.prototype.createInnerBlocks = function () {
  38435. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  38436. };
  38437. return OctreeBlock;
  38438. })();
  38439. BABYLON.OctreeBlock = OctreeBlock;
  38440. })(BABYLON || (BABYLON = {}));
  38441. var BABYLON;
  38442. (function (BABYLON) {
  38443. var BlurPostProcess = (function (_super) {
  38444. __extends(BlurPostProcess, _super);
  38445. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  38446. var _this = this;
  38447. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  38448. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  38449. this.direction = direction;
  38450. this.blurWidth = blurWidth;
  38451. this.onApply = function (effect) {
  38452. effect.setFloat2("screenSize", _this.width, _this.height);
  38453. effect.setVector2("direction", _this.direction);
  38454. effect.setFloat("blurWidth", _this.blurWidth);
  38455. };
  38456. }
  38457. return BlurPostProcess;
  38458. })(BABYLON.PostProcess);
  38459. BABYLON.BlurPostProcess = BlurPostProcess;
  38460. })(BABYLON || (BABYLON = {}));
  38461. var BABYLON;
  38462. (function (BABYLON) {
  38463. var RefractionPostProcess = (function (_super) {
  38464. __extends(RefractionPostProcess, _super);
  38465. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  38466. var _this = this;
  38467. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  38468. this.color = color;
  38469. this.depth = depth;
  38470. this.colorLevel = colorLevel;
  38471. this.onActivate = function (cam) {
  38472. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  38473. };
  38474. this.onApply = function (effect) {
  38475. effect.setColor3("baseColor", _this.color);
  38476. effect.setFloat("depth", _this.depth);
  38477. effect.setFloat("colorLevel", _this.colorLevel);
  38478. effect.setTexture("refractionSampler", _this._refRexture);
  38479. };
  38480. }
  38481. // Methods
  38482. RefractionPostProcess.prototype.dispose = function (camera) {
  38483. if (this._refRexture) {
  38484. this._refRexture.dispose();
  38485. }
  38486. _super.prototype.dispose.call(this, camera);
  38487. };
  38488. return RefractionPostProcess;
  38489. })(BABYLON.PostProcess);
  38490. BABYLON.RefractionPostProcess = RefractionPostProcess;
  38491. })(BABYLON || (BABYLON = {}));
  38492. var BABYLON;
  38493. (function (BABYLON) {
  38494. var BlackAndWhitePostProcess = (function (_super) {
  38495. __extends(BlackAndWhitePostProcess, _super);
  38496. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  38497. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  38498. }
  38499. return BlackAndWhitePostProcess;
  38500. })(BABYLON.PostProcess);
  38501. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  38502. })(BABYLON || (BABYLON = {}));
  38503. var BABYLON;
  38504. (function (BABYLON) {
  38505. var ConvolutionPostProcess = (function (_super) {
  38506. __extends(ConvolutionPostProcess, _super);
  38507. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  38508. var _this = this;
  38509. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  38510. this.kernel = kernel;
  38511. this.onApply = function (effect) {
  38512. effect.setFloat2("screenSize", _this.width, _this.height);
  38513. effect.setArray("kernel", _this.kernel);
  38514. };
  38515. }
  38516. // Statics
  38517. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  38518. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  38519. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  38520. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  38521. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  38522. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  38523. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  38524. return ConvolutionPostProcess;
  38525. })(BABYLON.PostProcess);
  38526. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  38527. })(BABYLON || (BABYLON = {}));
  38528. var BABYLON;
  38529. (function (BABYLON) {
  38530. var FilterPostProcess = (function (_super) {
  38531. __extends(FilterPostProcess, _super);
  38532. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  38533. var _this = this;
  38534. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  38535. this.kernelMatrix = kernelMatrix;
  38536. this.onApply = function (effect) {
  38537. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  38538. };
  38539. }
  38540. return FilterPostProcess;
  38541. })(BABYLON.PostProcess);
  38542. BABYLON.FilterPostProcess = FilterPostProcess;
  38543. })(BABYLON || (BABYLON = {}));
  38544. var BABYLON;
  38545. (function (BABYLON) {
  38546. var FxaaPostProcess = (function (_super) {
  38547. __extends(FxaaPostProcess, _super);
  38548. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  38549. var _this = this;
  38550. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  38551. this.onSizeChanged = function () {
  38552. _this.texelWidth = 1.0 / _this.width;
  38553. _this.texelHeight = 1.0 / _this.height;
  38554. };
  38555. this.onApply = function (effect) {
  38556. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  38557. };
  38558. }
  38559. return FxaaPostProcess;
  38560. })(BABYLON.PostProcess);
  38561. BABYLON.FxaaPostProcess = FxaaPostProcess;
  38562. })(BABYLON || (BABYLON = {}));
  38563. var BABYLON;
  38564. (function (BABYLON) {
  38565. var StereoscopicInterlacePostProcess = (function (_super) {
  38566. __extends(StereoscopicInterlacePostProcess, _super);
  38567. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  38568. var _this = this;
  38569. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  38570. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  38571. this.onSizeChanged = function () {
  38572. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  38573. };
  38574. this.onApply = function (effect) {
  38575. effect.setTextureFromPostProcess("camASampler", postProcessA);
  38576. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  38577. };
  38578. }
  38579. return StereoscopicInterlacePostProcess;
  38580. })(BABYLON.PostProcess);
  38581. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  38582. })(BABYLON || (BABYLON = {}));
  38583. var BABYLON;
  38584. (function (BABYLON) {
  38585. var LensFlare = (function () {
  38586. function LensFlare(size, position, color, imgUrl, system) {
  38587. this.size = size;
  38588. this.position = position;
  38589. this.dispose = function () {
  38590. if (this.texture) {
  38591. this.texture.dispose();
  38592. }
  38593. // Remove from scene
  38594. var index = this._system.lensFlares.indexOf(this);
  38595. this._system.lensFlares.splice(index, 1);
  38596. };
  38597. this.color = color || new BABYLON.Color3(1, 1, 1);
  38598. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  38599. this._system = system;
  38600. system.lensFlares.push(this);
  38601. }
  38602. return LensFlare;
  38603. })();
  38604. BABYLON.LensFlare = LensFlare;
  38605. })(BABYLON || (BABYLON = {}));
  38606. var BABYLON;
  38607. (function (BABYLON) {
  38608. var LensFlareSystem = (function () {
  38609. function LensFlareSystem(name, emitter, scene) {
  38610. this.name = name;
  38611. this.lensFlares = new Array();
  38612. this.borderLimit = 300;
  38613. this.layerMask = 0x0FFFFFFF;
  38614. this._vertexDeclaration = [2];
  38615. this._vertexStrideSize = 2 * 4;
  38616. this._isEnabled = true;
  38617. this._scene = scene;
  38618. this._emitter = emitter;
  38619. this.id = name;
  38620. scene.lensFlareSystems.push(this);
  38621. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  38622. // VBO
  38623. var vertices = [];
  38624. vertices.push(1, 1);
  38625. vertices.push(-1, 1);
  38626. vertices.push(-1, -1);
  38627. vertices.push(1, -1);
  38628. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  38629. // Indices
  38630. var indices = [];
  38631. indices.push(0);
  38632. indices.push(1);
  38633. indices.push(2);
  38634. indices.push(0);
  38635. indices.push(2);
  38636. indices.push(3);
  38637. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  38638. // Effects
  38639. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  38640. }
  38641. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  38642. get: function () {
  38643. return this._isEnabled;
  38644. },
  38645. set: function (value) {
  38646. this._isEnabled = value;
  38647. },
  38648. enumerable: true,
  38649. configurable: true
  38650. });
  38651. LensFlareSystem.prototype.getScene = function () {
  38652. return this._scene;
  38653. };
  38654. LensFlareSystem.prototype.getEmitter = function () {
  38655. return this._emitter;
  38656. };
  38657. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  38658. this._emitter = newEmitter;
  38659. };
  38660. LensFlareSystem.prototype.getEmitterPosition = function () {
  38661. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  38662. };
  38663. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  38664. var position = this.getEmitterPosition();
  38665. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  38666. this._positionX = position.x;
  38667. this._positionY = position.y;
  38668. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  38669. if (position.z > 0) {
  38670. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  38671. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  38672. return true;
  38673. }
  38674. }
  38675. return false;
  38676. };
  38677. LensFlareSystem.prototype._isVisible = function () {
  38678. if (!this._isEnabled) {
  38679. return false;
  38680. }
  38681. var emitterPosition = this.getEmitterPosition();
  38682. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  38683. var distance = direction.length();
  38684. direction.normalize();
  38685. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  38686. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  38687. return !pickInfo.hit || pickInfo.distance > distance;
  38688. };
  38689. LensFlareSystem.prototype.render = function () {
  38690. if (!this._effect.isReady())
  38691. return false;
  38692. var engine = this._scene.getEngine();
  38693. var viewport = this._scene.activeCamera.viewport;
  38694. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  38695. // Position
  38696. if (!this.computeEffectivePosition(globalViewport)) {
  38697. return false;
  38698. }
  38699. // Visibility
  38700. if (!this._isVisible()) {
  38701. return false;
  38702. }
  38703. // Intensity
  38704. var awayX;
  38705. var awayY;
  38706. if (this._positionX < this.borderLimit + globalViewport.x) {
  38707. awayX = this.borderLimit + globalViewport.x - this._positionX;
  38708. }
  38709. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  38710. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  38711. }
  38712. else {
  38713. awayX = 0;
  38714. }
  38715. if (this._positionY < this.borderLimit + globalViewport.y) {
  38716. awayY = this.borderLimit + globalViewport.y - this._positionY;
  38717. }
  38718. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  38719. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  38720. }
  38721. else {
  38722. awayY = 0;
  38723. }
  38724. var away = (awayX > awayY) ? awayX : awayY;
  38725. if (away > this.borderLimit) {
  38726. away = this.borderLimit;
  38727. }
  38728. var intensity = 1.0 - (away / this.borderLimit);
  38729. if (intensity < 0) {
  38730. return false;
  38731. }
  38732. if (intensity > 1.0) {
  38733. intensity = 1.0;
  38734. }
  38735. // Position
  38736. var centerX = globalViewport.x + globalViewport.width / 2;
  38737. var centerY = globalViewport.y + globalViewport.height / 2;
  38738. var distX = centerX - this._positionX;
  38739. var distY = centerY - this._positionY;
  38740. // Effects
  38741. engine.enableEffect(this._effect);
  38742. engine.setState(false);
  38743. engine.setDepthBuffer(false);
  38744. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  38745. // VBOs
  38746. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  38747. // Flares
  38748. for (var index = 0; index < this.lensFlares.length; index++) {
  38749. var flare = this.lensFlares[index];
  38750. var x = centerX - (distX * flare.position);
  38751. var y = centerY - (distY * flare.position);
  38752. var cw = flare.size;
  38753. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  38754. var cx = 2 * (x / globalViewport.width) - 1.0;
  38755. var cy = 1.0 - 2 * (y / globalViewport.height);
  38756. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  38757. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  38758. // Texture
  38759. this._effect.setTexture("textureSampler", flare.texture);
  38760. // Color
  38761. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  38762. // Draw order
  38763. engine.draw(true, 0, 6);
  38764. }
  38765. engine.setDepthBuffer(true);
  38766. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  38767. return true;
  38768. };
  38769. LensFlareSystem.prototype.dispose = function () {
  38770. if (this._vertexBuffer) {
  38771. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  38772. this._vertexBuffer = null;
  38773. }
  38774. if (this._indexBuffer) {
  38775. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  38776. this._indexBuffer = null;
  38777. }
  38778. while (this.lensFlares.length) {
  38779. this.lensFlares[0].dispose();
  38780. }
  38781. // Remove from scene
  38782. var index = this._scene.lensFlareSystems.indexOf(this);
  38783. this._scene.lensFlareSystems.splice(index, 1);
  38784. };
  38785. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  38786. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  38787. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  38788. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  38789. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  38790. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  38791. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  38792. var parsedFlare = parsedLensFlareSystem.flares[index];
  38793. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  38794. }
  38795. return lensFlareSystem;
  38796. };
  38797. LensFlareSystem.prototype.serialize = function () {
  38798. var serializationObject = {};
  38799. serializationObject.id = this.id;
  38800. serializationObject.name = this.name;
  38801. serializationObject.emitterId = this.getEmitter().id;
  38802. serializationObject.borderLimit = this.borderLimit;
  38803. serializationObject.flares = [];
  38804. for (var index = 0; index < this.lensFlares.length; index++) {
  38805. var flare = this.lensFlares[index];
  38806. serializationObject.flares.push({
  38807. size: flare.size,
  38808. position: flare.position,
  38809. color: flare.color.asArray(),
  38810. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  38811. });
  38812. }
  38813. return serializationObject;
  38814. };
  38815. return LensFlareSystem;
  38816. })();
  38817. BABYLON.LensFlareSystem = LensFlareSystem;
  38818. })(BABYLON || (BABYLON = {}));
  38819. var BABYLON;
  38820. (function (BABYLON) {
  38821. // We're mainly based on the logic defined into the FreeCamera code
  38822. var DeviceOrientationCamera = (function (_super) {
  38823. __extends(DeviceOrientationCamera, _super);
  38824. //-- end properties for backward compatibility for inputs
  38825. function DeviceOrientationCamera(name, position, scene) {
  38826. _super.call(this, name, position, scene);
  38827. this.inputs.addDeviceOrientation();
  38828. }
  38829. Object.defineProperty(DeviceOrientationCamera.prototype, "angularSensibility", {
  38830. //-- Begin properties for backward compatibility for inputs
  38831. get: function () {
  38832. var gamepad = this.inputs.attached["deviceOrientation"];
  38833. if (gamepad)
  38834. return gamepad.angularSensibility;
  38835. },
  38836. set: function (value) {
  38837. var gamepad = this.inputs.attached["deviceOrientation"];
  38838. if (gamepad)
  38839. gamepad.angularSensibility = value;
  38840. },
  38841. enumerable: true,
  38842. configurable: true
  38843. });
  38844. Object.defineProperty(DeviceOrientationCamera.prototype, "moveSensibility", {
  38845. get: function () {
  38846. var gamepad = this.inputs.attached["deviceOrientation"];
  38847. if (gamepad)
  38848. return gamepad.moveSensibility;
  38849. },
  38850. set: function (value) {
  38851. var gamepad = this.inputs.attached["deviceOrientation"];
  38852. if (gamepad)
  38853. gamepad.moveSensibility = value;
  38854. },
  38855. enumerable: true,
  38856. configurable: true
  38857. });
  38858. DeviceOrientationCamera.prototype.getTypeName = function () {
  38859. return "DeviceOrientationCamera";
  38860. };
  38861. return DeviceOrientationCamera;
  38862. })(BABYLON.FreeCamera);
  38863. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  38864. })(BABYLON || (BABYLON = {}));
  38865. var BABYLON;
  38866. (function (BABYLON) {
  38867. // We're mainly based on the logic defined into the FreeCamera code
  38868. var UniversalCamera = (function (_super) {
  38869. __extends(UniversalCamera, _super);
  38870. //-- end properties for backward compatibility for inputs
  38871. function UniversalCamera(name, position, scene) {
  38872. _super.call(this, name, position, scene);
  38873. this.inputs.addGamepad();
  38874. }
  38875. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  38876. //-- Begin properties for backward compatibility for inputs
  38877. get: function () {
  38878. var gamepad = this.inputs.attached["gamepad"];
  38879. if (gamepad)
  38880. return gamepad.gamepadAngularSensibility;
  38881. },
  38882. set: function (value) {
  38883. var gamepad = this.inputs.attached["gamepad"];
  38884. if (gamepad)
  38885. gamepad.gamepadAngularSensibility = value;
  38886. },
  38887. enumerable: true,
  38888. configurable: true
  38889. });
  38890. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  38891. get: function () {
  38892. var gamepad = this.inputs.attached["gamepad"];
  38893. if (gamepad)
  38894. return gamepad.gamepadMoveSensibility;
  38895. },
  38896. set: function (value) {
  38897. var gamepad = this.inputs.attached["gamepad"];
  38898. if (gamepad)
  38899. gamepad.gamepadMoveSensibility = value;
  38900. },
  38901. enumerable: true,
  38902. configurable: true
  38903. });
  38904. UniversalCamera.prototype.getTypeName = function () {
  38905. return "UniversalCamera";
  38906. };
  38907. return UniversalCamera;
  38908. })(BABYLON.TouchCamera);
  38909. BABYLON.UniversalCamera = UniversalCamera;
  38910. })(BABYLON || (BABYLON = {}));
  38911. var BABYLON;
  38912. (function (BABYLON) {
  38913. var Gamepads = (function () {
  38914. function Gamepads(ongamedpadconnected) {
  38915. var _this = this;
  38916. this.babylonGamepads = [];
  38917. this.oneGamepadConnected = false;
  38918. this.isMonitoring = false;
  38919. this.gamepadEventSupported = 'GamepadEvent' in window;
  38920. this.gamepadSupportAvailable = (navigator.getGamepads ||
  38921. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  38922. this._callbackGamepadConnected = ongamedpadconnected;
  38923. if (this.gamepadSupportAvailable) {
  38924. // Checking if the gamepad connected event is supported (like in Firefox)
  38925. if (this.gamepadEventSupported) {
  38926. this._onGamepadConnectedEvent = function (evt) {
  38927. _this._onGamepadConnected(evt);
  38928. };
  38929. this._onGamepadDisonnectedEvent = function (evt) {
  38930. _this._onGamepadDisconnected(evt);
  38931. };
  38932. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  38933. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  38934. }
  38935. else {
  38936. this._startMonitoringGamepads();
  38937. }
  38938. }
  38939. }
  38940. Gamepads.prototype.dispose = function () {
  38941. if (Gamepads.gamepadDOMInfo) {
  38942. document.body.removeChild(Gamepads.gamepadDOMInfo);
  38943. }
  38944. if (this._onGamepadConnectedEvent) {
  38945. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  38946. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  38947. this._onGamepadConnectedEvent = null;
  38948. this._onGamepadDisonnectedEvent = null;
  38949. }
  38950. };
  38951. Gamepads.prototype._onGamepadConnected = function (evt) {
  38952. var newGamepad = this._addNewGamepad(evt.gamepad);
  38953. if (this._callbackGamepadConnected)
  38954. this._callbackGamepadConnected(newGamepad);
  38955. this._startMonitoringGamepads();
  38956. };
  38957. Gamepads.prototype._addNewGamepad = function (gamepad) {
  38958. if (!this.oneGamepadConnected) {
  38959. this.oneGamepadConnected = true;
  38960. if (Gamepads.gamepadDOMInfo) {
  38961. document.body.removeChild(Gamepads.gamepadDOMInfo);
  38962. Gamepads.gamepadDOMInfo = null;
  38963. }
  38964. }
  38965. var newGamepad;
  38966. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  38967. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  38968. }
  38969. else {
  38970. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  38971. }
  38972. this.babylonGamepads.push(newGamepad);
  38973. return newGamepad;
  38974. };
  38975. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  38976. // Remove the gamepad from the list of gamepads to monitor.
  38977. for (var i in this.babylonGamepads) {
  38978. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  38979. this.babylonGamepads.splice(+i, 1);
  38980. break;
  38981. }
  38982. }
  38983. // If no gamepads are left, stop the polling loop.
  38984. if (this.babylonGamepads.length == 0) {
  38985. this._stopMonitoringGamepads();
  38986. }
  38987. };
  38988. Gamepads.prototype._startMonitoringGamepads = function () {
  38989. if (!this.isMonitoring) {
  38990. this.isMonitoring = true;
  38991. this._checkGamepadsStatus();
  38992. }
  38993. };
  38994. Gamepads.prototype._stopMonitoringGamepads = function () {
  38995. this.isMonitoring = false;
  38996. };
  38997. Gamepads.prototype._checkGamepadsStatus = function () {
  38998. var _this = this;
  38999. // updating gamepad objects
  39000. this._updateGamepadObjects();
  39001. for (var i in this.babylonGamepads) {
  39002. this.babylonGamepads[i].update();
  39003. }
  39004. if (this.isMonitoring) {
  39005. if (window.requestAnimationFrame) {
  39006. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  39007. }
  39008. else if (window.mozRequestAnimationFrame) {
  39009. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  39010. }
  39011. else if (window.webkitRequestAnimationFrame) {
  39012. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  39013. }
  39014. }
  39015. };
  39016. // This function is called only on Chrome, which does not yet support
  39017. // connection/disconnection events, but requires you to monitor
  39018. // an array for changes.
  39019. Gamepads.prototype._updateGamepadObjects = function () {
  39020. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  39021. for (var i = 0; i < gamepads.length; i++) {
  39022. if (gamepads[i]) {
  39023. if (!(gamepads[i].index in this.babylonGamepads)) {
  39024. var newGamepad = this._addNewGamepad(gamepads[i]);
  39025. if (this._callbackGamepadConnected) {
  39026. this._callbackGamepadConnected(newGamepad);
  39027. }
  39028. }
  39029. else {
  39030. this.babylonGamepads[i].browserGamepad = gamepads[i];
  39031. }
  39032. }
  39033. }
  39034. };
  39035. return Gamepads;
  39036. })();
  39037. BABYLON.Gamepads = Gamepads;
  39038. var StickValues = (function () {
  39039. function StickValues(x, y) {
  39040. this.x = x;
  39041. this.y = y;
  39042. }
  39043. return StickValues;
  39044. })();
  39045. BABYLON.StickValues = StickValues;
  39046. var Gamepad = (function () {
  39047. function Gamepad(id, index, browserGamepad) {
  39048. this.id = id;
  39049. this.index = index;
  39050. this.browserGamepad = browserGamepad;
  39051. if (this.browserGamepad.axes.length >= 2) {
  39052. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  39053. }
  39054. if (this.browserGamepad.axes.length >= 4) {
  39055. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  39056. }
  39057. }
  39058. Gamepad.prototype.onleftstickchanged = function (callback) {
  39059. this._onleftstickchanged = callback;
  39060. };
  39061. Gamepad.prototype.onrightstickchanged = function (callback) {
  39062. this._onrightstickchanged = callback;
  39063. };
  39064. Object.defineProperty(Gamepad.prototype, "leftStick", {
  39065. get: function () {
  39066. return this._leftStick;
  39067. },
  39068. set: function (newValues) {
  39069. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  39070. this._onleftstickchanged(newValues);
  39071. }
  39072. this._leftStick = newValues;
  39073. },
  39074. enumerable: true,
  39075. configurable: true
  39076. });
  39077. Object.defineProperty(Gamepad.prototype, "rightStick", {
  39078. get: function () {
  39079. return this._rightStick;
  39080. },
  39081. set: function (newValues) {
  39082. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  39083. this._onrightstickchanged(newValues);
  39084. }
  39085. this._rightStick = newValues;
  39086. },
  39087. enumerable: true,
  39088. configurable: true
  39089. });
  39090. Gamepad.prototype.update = function () {
  39091. if (this._leftStick) {
  39092. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  39093. }
  39094. if (this._rightStick) {
  39095. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  39096. }
  39097. };
  39098. return Gamepad;
  39099. })();
  39100. BABYLON.Gamepad = Gamepad;
  39101. var GenericPad = (function (_super) {
  39102. __extends(GenericPad, _super);
  39103. function GenericPad(id, index, gamepad) {
  39104. _super.call(this, id, index, gamepad);
  39105. this.id = id;
  39106. this.index = index;
  39107. this.gamepad = gamepad;
  39108. this._buttons = new Array(gamepad.buttons.length);
  39109. }
  39110. GenericPad.prototype.onbuttondown = function (callback) {
  39111. this._onbuttondown = callback;
  39112. };
  39113. GenericPad.prototype.onbuttonup = function (callback) {
  39114. this._onbuttonup = callback;
  39115. };
  39116. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  39117. if (newValue !== currentValue) {
  39118. if (this._onbuttondown && newValue === 1) {
  39119. this._onbuttondown(buttonIndex);
  39120. }
  39121. if (this._onbuttonup && newValue === 0) {
  39122. this._onbuttonup(buttonIndex);
  39123. }
  39124. }
  39125. return newValue;
  39126. };
  39127. GenericPad.prototype.update = function () {
  39128. _super.prototype.update.call(this);
  39129. for (var index = 0; index < this._buttons.length; index++) {
  39130. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  39131. }
  39132. };
  39133. return GenericPad;
  39134. })(Gamepad);
  39135. BABYLON.GenericPad = GenericPad;
  39136. (function (Xbox360Button) {
  39137. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  39138. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  39139. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  39140. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  39141. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  39142. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  39143. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  39144. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  39145. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  39146. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  39147. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  39148. var Xbox360Button = BABYLON.Xbox360Button;
  39149. (function (Xbox360Dpad) {
  39150. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  39151. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  39152. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  39153. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  39154. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  39155. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  39156. var Xbox360Pad = (function (_super) {
  39157. __extends(Xbox360Pad, _super);
  39158. function Xbox360Pad() {
  39159. _super.apply(this, arguments);
  39160. this._leftTrigger = 0;
  39161. this._rightTrigger = 0;
  39162. this._buttonA = 0;
  39163. this._buttonB = 0;
  39164. this._buttonX = 0;
  39165. this._buttonY = 0;
  39166. this._buttonBack = 0;
  39167. this._buttonStart = 0;
  39168. this._buttonLB = 0;
  39169. this._buttonRB = 0;
  39170. this._buttonLeftStick = 0;
  39171. this._buttonRightStick = 0;
  39172. this._dPadUp = 0;
  39173. this._dPadDown = 0;
  39174. this._dPadLeft = 0;
  39175. this._dPadRight = 0;
  39176. }
  39177. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  39178. this._onlefttriggerchanged = callback;
  39179. };
  39180. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  39181. this._onrighttriggerchanged = callback;
  39182. };
  39183. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  39184. get: function () {
  39185. return this._leftTrigger;
  39186. },
  39187. set: function (newValue) {
  39188. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  39189. this._onlefttriggerchanged(newValue);
  39190. }
  39191. this._leftTrigger = newValue;
  39192. },
  39193. enumerable: true,
  39194. configurable: true
  39195. });
  39196. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  39197. get: function () {
  39198. return this._rightTrigger;
  39199. },
  39200. set: function (newValue) {
  39201. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  39202. this._onrighttriggerchanged(newValue);
  39203. }
  39204. this._rightTrigger = newValue;
  39205. },
  39206. enumerable: true,
  39207. configurable: true
  39208. });
  39209. Xbox360Pad.prototype.onbuttondown = function (callback) {
  39210. this._onbuttondown = callback;
  39211. };
  39212. Xbox360Pad.prototype.onbuttonup = function (callback) {
  39213. this._onbuttonup = callback;
  39214. };
  39215. Xbox360Pad.prototype.ondpaddown = function (callback) {
  39216. this._ondpaddown = callback;
  39217. };
  39218. Xbox360Pad.prototype.ondpadup = function (callback) {
  39219. this._ondpadup = callback;
  39220. };
  39221. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  39222. if (newValue !== currentValue) {
  39223. if (this._onbuttondown && newValue === 1) {
  39224. this._onbuttondown(buttonType);
  39225. }
  39226. if (this._onbuttonup && newValue === 0) {
  39227. this._onbuttonup(buttonType);
  39228. }
  39229. }
  39230. return newValue;
  39231. };
  39232. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  39233. if (newValue !== currentValue) {
  39234. if (this._ondpaddown && newValue === 1) {
  39235. this._ondpaddown(buttonType);
  39236. }
  39237. if (this._ondpadup && newValue === 0) {
  39238. this._ondpadup(buttonType);
  39239. }
  39240. }
  39241. return newValue;
  39242. };
  39243. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  39244. get: function () {
  39245. return this._buttonA;
  39246. },
  39247. set: function (value) {
  39248. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  39249. },
  39250. enumerable: true,
  39251. configurable: true
  39252. });
  39253. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  39254. get: function () {
  39255. return this._buttonB;
  39256. },
  39257. set: function (value) {
  39258. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  39259. },
  39260. enumerable: true,
  39261. configurable: true
  39262. });
  39263. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  39264. get: function () {
  39265. return this._buttonX;
  39266. },
  39267. set: function (value) {
  39268. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  39269. },
  39270. enumerable: true,
  39271. configurable: true
  39272. });
  39273. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  39274. get: function () {
  39275. return this._buttonY;
  39276. },
  39277. set: function (value) {
  39278. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  39279. },
  39280. enumerable: true,
  39281. configurable: true
  39282. });
  39283. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  39284. get: function () {
  39285. return this._buttonStart;
  39286. },
  39287. set: function (value) {
  39288. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  39289. },
  39290. enumerable: true,
  39291. configurable: true
  39292. });
  39293. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  39294. get: function () {
  39295. return this._buttonBack;
  39296. },
  39297. set: function (value) {
  39298. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  39299. },
  39300. enumerable: true,
  39301. configurable: true
  39302. });
  39303. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  39304. get: function () {
  39305. return this._buttonLB;
  39306. },
  39307. set: function (value) {
  39308. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  39309. },
  39310. enumerable: true,
  39311. configurable: true
  39312. });
  39313. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  39314. get: function () {
  39315. return this._buttonRB;
  39316. },
  39317. set: function (value) {
  39318. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  39319. },
  39320. enumerable: true,
  39321. configurable: true
  39322. });
  39323. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  39324. get: function () {
  39325. return this._buttonLeftStick;
  39326. },
  39327. set: function (value) {
  39328. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  39329. },
  39330. enumerable: true,
  39331. configurable: true
  39332. });
  39333. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  39334. get: function () {
  39335. return this._buttonRightStick;
  39336. },
  39337. set: function (value) {
  39338. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  39339. },
  39340. enumerable: true,
  39341. configurable: true
  39342. });
  39343. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  39344. get: function () {
  39345. return this._dPadUp;
  39346. },
  39347. set: function (value) {
  39348. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  39349. },
  39350. enumerable: true,
  39351. configurable: true
  39352. });
  39353. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  39354. get: function () {
  39355. return this._dPadDown;
  39356. },
  39357. set: function (value) {
  39358. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  39359. },
  39360. enumerable: true,
  39361. configurable: true
  39362. });
  39363. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  39364. get: function () {
  39365. return this._dPadLeft;
  39366. },
  39367. set: function (value) {
  39368. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  39369. },
  39370. enumerable: true,
  39371. configurable: true
  39372. });
  39373. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  39374. get: function () {
  39375. return this._dPadRight;
  39376. },
  39377. set: function (value) {
  39378. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  39379. },
  39380. enumerable: true,
  39381. configurable: true
  39382. });
  39383. Xbox360Pad.prototype.update = function () {
  39384. _super.prototype.update.call(this);
  39385. this.buttonA = this.browserGamepad.buttons[0].value;
  39386. this.buttonB = this.browserGamepad.buttons[1].value;
  39387. this.buttonX = this.browserGamepad.buttons[2].value;
  39388. this.buttonY = this.browserGamepad.buttons[3].value;
  39389. this.buttonLB = this.browserGamepad.buttons[4].value;
  39390. this.buttonRB = this.browserGamepad.buttons[5].value;
  39391. this.leftTrigger = this.browserGamepad.buttons[6].value;
  39392. this.rightTrigger = this.browserGamepad.buttons[7].value;
  39393. this.buttonBack = this.browserGamepad.buttons[8].value;
  39394. this.buttonStart = this.browserGamepad.buttons[9].value;
  39395. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  39396. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  39397. this.dPadUp = this.browserGamepad.buttons[12].value;
  39398. this.dPadDown = this.browserGamepad.buttons[13].value;
  39399. this.dPadLeft = this.browserGamepad.buttons[14].value;
  39400. this.dPadRight = this.browserGamepad.buttons[15].value;
  39401. };
  39402. return Xbox360Pad;
  39403. })(Gamepad);
  39404. BABYLON.Xbox360Pad = Xbox360Pad;
  39405. })(BABYLON || (BABYLON = {}));
  39406. var BABYLON;
  39407. (function (BABYLON) {
  39408. // We're mainly based on the logic defined into the FreeCamera code
  39409. var GamepadCamera = (function (_super) {
  39410. __extends(GamepadCamera, _super);
  39411. //-- end properties for backward compatibility for inputs
  39412. function GamepadCamera(name, position, scene) {
  39413. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  39414. _super.call(this, name, position, scene);
  39415. }
  39416. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  39417. //-- Begin properties for backward compatibility for inputs
  39418. get: function () {
  39419. var gamepad = this.inputs.attached["gamepad"];
  39420. if (gamepad)
  39421. return gamepad.gamepadAngularSensibility;
  39422. },
  39423. set: function (value) {
  39424. var gamepad = this.inputs.attached["gamepad"];
  39425. if (gamepad)
  39426. gamepad.gamepadAngularSensibility = value;
  39427. },
  39428. enumerable: true,
  39429. configurable: true
  39430. });
  39431. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  39432. get: function () {
  39433. var gamepad = this.inputs.attached["gamepad"];
  39434. if (gamepad)
  39435. return gamepad.gamepadMoveSensibility;
  39436. },
  39437. set: function (value) {
  39438. var gamepad = this.inputs.attached["gamepad"];
  39439. if (gamepad)
  39440. gamepad.gamepadMoveSensibility = value;
  39441. },
  39442. enumerable: true,
  39443. configurable: true
  39444. });
  39445. GamepadCamera.prototype.getTypeName = function () {
  39446. return "GamepadCamera";
  39447. };
  39448. return GamepadCamera;
  39449. })(BABYLON.UniversalCamera);
  39450. BABYLON.GamepadCamera = GamepadCamera;
  39451. })(BABYLON || (BABYLON = {}));
  39452. var BABYLON;
  39453. (function (BABYLON) {
  39454. var Analyser = (function () {
  39455. function Analyser(scene) {
  39456. this.SMOOTHING = 0.75;
  39457. this.FFT_SIZE = 512;
  39458. this.BARGRAPHAMPLITUDE = 256;
  39459. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  39460. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  39461. this._scene = scene;
  39462. this._audioEngine = BABYLON.Engine.audioEngine;
  39463. if (this._audioEngine.canUseWebAudio) {
  39464. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  39465. this._webAudioAnalyser.minDecibels = -140;
  39466. this._webAudioAnalyser.maxDecibels = 0;
  39467. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  39468. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  39469. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  39470. }
  39471. }
  39472. Analyser.prototype.getFrequencyBinCount = function () {
  39473. if (this._audioEngine.canUseWebAudio) {
  39474. return this._webAudioAnalyser.frequencyBinCount;
  39475. }
  39476. else {
  39477. return 0;
  39478. }
  39479. };
  39480. Analyser.prototype.getByteFrequencyData = function () {
  39481. if (this._audioEngine.canUseWebAudio) {
  39482. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  39483. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  39484. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  39485. }
  39486. return this._byteFreqs;
  39487. };
  39488. Analyser.prototype.getByteTimeDomainData = function () {
  39489. if (this._audioEngine.canUseWebAudio) {
  39490. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  39491. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  39492. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  39493. }
  39494. return this._byteTime;
  39495. };
  39496. Analyser.prototype.getFloatFrequencyData = function () {
  39497. if (this._audioEngine.canUseWebAudio) {
  39498. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  39499. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  39500. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  39501. }
  39502. return this._floatFreqs;
  39503. };
  39504. Analyser.prototype.drawDebugCanvas = function () {
  39505. var _this = this;
  39506. if (this._audioEngine.canUseWebAudio) {
  39507. if (!this._debugCanvas) {
  39508. this._debugCanvas = document.createElement("canvas");
  39509. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  39510. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  39511. this._debugCanvas.style.position = "absolute";
  39512. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  39513. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  39514. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  39515. document.body.appendChild(this._debugCanvas);
  39516. this._registerFunc = function () {
  39517. _this.drawDebugCanvas();
  39518. };
  39519. this._scene.registerBeforeRender(this._registerFunc);
  39520. }
  39521. if (this._registerFunc) {
  39522. var workingArray = this.getByteFrequencyData();
  39523. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  39524. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  39525. // Draw the frequency domain chart.
  39526. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  39527. var value = workingArray[i];
  39528. var percent = value / this.BARGRAPHAMPLITUDE;
  39529. var height = this.DEBUGCANVASSIZE.height * percent;
  39530. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  39531. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  39532. var hue = i / this.getFrequencyBinCount() * 360;
  39533. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  39534. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  39535. }
  39536. }
  39537. }
  39538. };
  39539. Analyser.prototype.stopDebugCanvas = function () {
  39540. if (this._debugCanvas) {
  39541. this._scene.unregisterBeforeRender(this._registerFunc);
  39542. this._registerFunc = null;
  39543. document.body.removeChild(this._debugCanvas);
  39544. this._debugCanvas = null;
  39545. this._debugCanvasContext = null;
  39546. }
  39547. };
  39548. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  39549. if (this._audioEngine.canUseWebAudio) {
  39550. inputAudioNode.connect(this._webAudioAnalyser);
  39551. this._webAudioAnalyser.connect(outputAudioNode);
  39552. }
  39553. };
  39554. Analyser.prototype.dispose = function () {
  39555. if (this._audioEngine.canUseWebAudio) {
  39556. this._webAudioAnalyser.disconnect();
  39557. }
  39558. };
  39559. return Analyser;
  39560. })();
  39561. BABYLON.Analyser = Analyser;
  39562. })(BABYLON || (BABYLON = {}));
  39563. var BABYLON;
  39564. (function (BABYLON) {
  39565. var DepthRenderer = (function () {
  39566. function DepthRenderer(scene, type) {
  39567. var _this = this;
  39568. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  39569. this._viewMatrix = BABYLON.Matrix.Zero();
  39570. this._projectionMatrix = BABYLON.Matrix.Zero();
  39571. this._transformMatrix = BABYLON.Matrix.Zero();
  39572. this._worldViewProjection = BABYLON.Matrix.Zero();
  39573. this._scene = scene;
  39574. var engine = scene.getEngine();
  39575. // Render target
  39576. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  39577. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39578. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39579. this._depthMap.refreshRate = 1;
  39580. this._depthMap.renderParticles = false;
  39581. this._depthMap.renderList = null;
  39582. // set default depth value to 1.0 (far away)
  39583. this._depthMap.onClear = function (engine) {
  39584. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  39585. };
  39586. // Custom render function
  39587. var renderSubMesh = function (subMesh) {
  39588. var mesh = subMesh.getRenderingMesh();
  39589. var scene = _this._scene;
  39590. var engine = scene.getEngine();
  39591. // Culling
  39592. engine.setState(subMesh.getMaterial().backFaceCulling);
  39593. // Managing instances
  39594. var batch = mesh._getInstancesRenderList(subMesh._id);
  39595. if (batch.mustReturn) {
  39596. return;
  39597. }
  39598. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  39599. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  39600. engine.enableEffect(_this._effect);
  39601. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  39602. var material = subMesh.getMaterial();
  39603. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  39604. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  39605. // Alpha test
  39606. if (material && material.needAlphaTesting()) {
  39607. var alphaTexture = material.getAlphaTestTexture();
  39608. _this._effect.setTexture("diffuseSampler", alphaTexture);
  39609. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  39610. }
  39611. // Bones
  39612. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  39613. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  39614. }
  39615. // Draw
  39616. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  39617. }
  39618. };
  39619. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  39620. var index;
  39621. for (index = 0; index < opaqueSubMeshes.length; index++) {
  39622. renderSubMesh(opaqueSubMeshes.data[index]);
  39623. }
  39624. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  39625. renderSubMesh(alphaTestSubMeshes.data[index]);
  39626. }
  39627. };
  39628. }
  39629. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  39630. var material = subMesh.getMaterial();
  39631. if (material.disableDepthWrite) {
  39632. return false;
  39633. }
  39634. var defines = [];
  39635. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39636. var mesh = subMesh.getMesh();
  39637. var scene = mesh.getScene();
  39638. // Alpha test
  39639. if (material && material.needAlphaTesting()) {
  39640. defines.push("#define ALPHATEST");
  39641. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39642. attribs.push(BABYLON.VertexBuffer.UVKind);
  39643. defines.push("#define UV1");
  39644. }
  39645. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39646. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39647. defines.push("#define UV2");
  39648. }
  39649. }
  39650. // Bones
  39651. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  39652. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39653. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39654. if (mesh.numBoneInfluencers > 4) {
  39655. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39656. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39657. }
  39658. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  39659. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  39660. }
  39661. else {
  39662. defines.push("#define NUM_BONE_INFLUENCERS 0");
  39663. }
  39664. // Instances
  39665. if (useInstances) {
  39666. defines.push("#define INSTANCES");
  39667. attribs.push("world0");
  39668. attribs.push("world1");
  39669. attribs.push("world2");
  39670. attribs.push("world3");
  39671. }
  39672. // Get correct effect
  39673. var join = defines.join("\n");
  39674. if (this._cachedDefines !== join) {
  39675. this._cachedDefines = join;
  39676. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  39677. }
  39678. return this._effect.isReady();
  39679. };
  39680. DepthRenderer.prototype.getDepthMap = function () {
  39681. return this._depthMap;
  39682. };
  39683. // Methods
  39684. DepthRenderer.prototype.dispose = function () {
  39685. this._depthMap.dispose();
  39686. };
  39687. return DepthRenderer;
  39688. })();
  39689. BABYLON.DepthRenderer = DepthRenderer;
  39690. })(BABYLON || (BABYLON = {}));
  39691. var BABYLON;
  39692. (function (BABYLON) {
  39693. var SSAORenderingPipeline = (function (_super) {
  39694. __extends(SSAORenderingPipeline, _super);
  39695. /**
  39696. * @constructor
  39697. * @param {string} name - The rendering pipeline name
  39698. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  39699. * @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 }
  39700. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  39701. */
  39702. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  39703. var _this = this;
  39704. _super.call(this, scene.getEngine(), name);
  39705. // Members
  39706. /**
  39707. * The PassPostProcess id in the pipeline that contains the original scene color
  39708. * @type {string}
  39709. */
  39710. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  39711. /**
  39712. * The SSAO PostProcess id in the pipeline
  39713. * @type {string}
  39714. */
  39715. this.SSAORenderEffect = "SSAORenderEffect";
  39716. /**
  39717. * The horizontal blur PostProcess id in the pipeline
  39718. * @type {string}
  39719. */
  39720. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  39721. /**
  39722. * The vertical blur PostProcess id in the pipeline
  39723. * @type {string}
  39724. */
  39725. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  39726. /**
  39727. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  39728. * @type {string}
  39729. */
  39730. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  39731. /**
  39732. * The output strength of the SSAO post-process. Default value is 1.0.
  39733. * @type {number}
  39734. */
  39735. this.totalStrength = 1.0;
  39736. /**
  39737. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  39738. * @type {number}
  39739. */
  39740. this.radius = 0.0001;
  39741. /**
  39742. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  39743. * Must not be equal to fallOff and superior to fallOff.
  39744. * Default value is 0.975
  39745. * @type {number}
  39746. */
  39747. this.area = 0.0075;
  39748. /**
  39749. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  39750. * Must not be equal to area and inferior to area.
  39751. * Default value is 0.0
  39752. * @type {number}
  39753. */
  39754. this.fallOff = 0.000001;
  39755. /**
  39756. * The base color of the SSAO post-process
  39757. * The final result is "base + ssao" between [0, 1]
  39758. * @type {number}
  39759. */
  39760. this.base = 0.5;
  39761. this._firstUpdate = true;
  39762. this._scene = scene;
  39763. // Set up assets
  39764. this._createRandomTexture();
  39765. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  39766. var ssaoRatio = ratio.ssaoRatio || ratio;
  39767. var combineRatio = ratio.combineRatio || ratio;
  39768. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  39769. this._createSSAOPostProcess(ssaoRatio);
  39770. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(1.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  39771. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 1.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  39772. this._createSSAOCombinePostProcess(combineRatio);
  39773. // Set up pipeline
  39774. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  39775. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  39776. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  39777. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  39778. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  39779. // Finish
  39780. scene.postProcessRenderPipelineManager.addPipeline(this);
  39781. if (cameras)
  39782. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  39783. }
  39784. // Public Methods
  39785. /**
  39786. * Returns the horizontal blur PostProcess
  39787. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  39788. */
  39789. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  39790. return this._blurHPostProcess;
  39791. };
  39792. /**
  39793. * Returns the vertical blur PostProcess
  39794. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  39795. */
  39796. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  39797. return this._blurVPostProcess;
  39798. };
  39799. /**
  39800. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  39801. */
  39802. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  39803. if (disableDepthRender === void 0) { disableDepthRender = false; }
  39804. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  39805. this._originalColorPostProcess = undefined;
  39806. this._ssaoPostProcess = undefined;
  39807. this._blurHPostProcess = undefined;
  39808. this._blurVPostProcess = undefined;
  39809. this._ssaoCombinePostProcess = undefined;
  39810. this._randomTexture.dispose();
  39811. if (disableDepthRender)
  39812. this._scene.disableDepthRenderer();
  39813. };
  39814. // Private Methods
  39815. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  39816. var _this = this;
  39817. var numSamples = 16;
  39818. var sampleSphere = [
  39819. 0.5381, 0.1856, -0.4319,
  39820. 0.1379, 0.2486, 0.4430,
  39821. 0.3371, 0.5679, -0.0057,
  39822. -0.6999, -0.0451, -0.0019,
  39823. 0.0689, -0.1598, -0.8547,
  39824. 0.0560, 0.0069, -0.1843,
  39825. -0.0146, 0.1402, 0.0762,
  39826. 0.0100, -0.1924, -0.0344,
  39827. -0.3577, -0.5301, -0.4358,
  39828. -0.3169, 0.1063, 0.0158,
  39829. 0.0103, -0.5869, 0.0046,
  39830. -0.0897, -0.4940, 0.3287,
  39831. 0.7119, -0.0154, -0.0918,
  39832. -0.0533, 0.0596, -0.5411,
  39833. 0.0352, -0.0631, 0.5460,
  39834. -0.4776, 0.2847, -0.0271
  39835. ];
  39836. var samplesFactor = 1.0 / numSamples;
  39837. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  39838. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  39839. "area", "fallOff", "base"
  39840. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples);
  39841. this._ssaoPostProcess.onApply = function (effect) {
  39842. if (_this._firstUpdate) {
  39843. effect.setArray3("sampleSphere", sampleSphere);
  39844. effect.setFloat("samplesFactor", samplesFactor);
  39845. effect.setFloat("randTextureTiles", 4.0);
  39846. _this._firstUpdate = false;
  39847. }
  39848. effect.setFloat("totalStrength", _this.totalStrength);
  39849. effect.setFloat("radius", _this.radius);
  39850. effect.setFloat("area", _this.area);
  39851. effect.setFloat("fallOff", _this.fallOff);
  39852. effect.setFloat("base", _this.base);
  39853. effect.setTexture("textureSampler", _this._depthTexture);
  39854. effect.setTexture("randomSampler", _this._randomTexture);
  39855. };
  39856. };
  39857. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  39858. var _this = this;
  39859. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  39860. this._ssaoCombinePostProcess.onApply = function (effect) {
  39861. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  39862. };
  39863. };
  39864. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  39865. var size = 512;
  39866. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  39867. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  39868. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  39869. var context = this._randomTexture.getContext();
  39870. var rand = function (min, max) {
  39871. return Math.random() * (max - min) + min;
  39872. };
  39873. var randVector = BABYLON.Vector3.Zero();
  39874. for (var x = 0; x < size; x++) {
  39875. for (var y = 0; y < size; y++) {
  39876. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  39877. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  39878. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  39879. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  39880. context.fillRect(x, y, 1, 1);
  39881. }
  39882. }
  39883. this._randomTexture.update(false);
  39884. };
  39885. return SSAORenderingPipeline;
  39886. })(BABYLON.PostProcessRenderPipeline);
  39887. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  39888. })(BABYLON || (BABYLON = {}));
  39889. var BABYLON;
  39890. (function (BABYLON) {
  39891. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  39892. var VolumetricLightScatteringPostProcess = (function (_super) {
  39893. __extends(VolumetricLightScatteringPostProcess, _super);
  39894. /**
  39895. * @constructor
  39896. * @param {string} name - The post-process name
  39897. * @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)
  39898. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  39899. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  39900. * @param {number} samples - The post-process quality, default 100
  39901. * @param {number} samplingMode - The post-process filtering mode
  39902. * @param {BABYLON.Engine} engine - The babylon engine
  39903. * @param {boolean} reusable - If the post-process is reusable
  39904. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  39905. */
  39906. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  39907. var _this = this;
  39908. if (samples === void 0) { samples = 100; }
  39909. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  39910. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  39911. this._screenCoordinates = BABYLON.Vector2.Zero();
  39912. /**
  39913. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  39914. * @type {Vector3}
  39915. */
  39916. this.customMeshPosition = BABYLON.Vector3.Zero();
  39917. /**
  39918. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  39919. * @type {boolean}
  39920. */
  39921. this.useCustomMeshPosition = false;
  39922. /**
  39923. * If the post-process should inverse the light scattering direction
  39924. * @type {boolean}
  39925. */
  39926. this.invert = true;
  39927. /**
  39928. * Array containing the excluded meshes not rendered in the internal pass
  39929. */
  39930. this.excludedMeshes = new Array();
  39931. /**
  39932. * Controls the overall intensity of the post-process
  39933. * @type {number}
  39934. */
  39935. this.exposure = 0.3;
  39936. /**
  39937. * Dissipates each sample's contribution in range [0, 1]
  39938. * @type {number}
  39939. */
  39940. this.decay = 0.96815;
  39941. /**
  39942. * Controls the overall intensity of each sample
  39943. * @type {number}
  39944. */
  39945. this.weight = 0.58767;
  39946. /**
  39947. * Controls the density of each sample
  39948. * @type {number}
  39949. */
  39950. this.density = 0.926;
  39951. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  39952. var engine = scene.getEngine();
  39953. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  39954. // Configure mesh
  39955. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  39956. // Configure
  39957. this._createPass(scene, ratio.passRatio || ratio);
  39958. this.onActivate = function (camera) {
  39959. if (!_this.isSupported) {
  39960. _this.dispose(camera);
  39961. }
  39962. _this.onActivate = null;
  39963. };
  39964. this.onApply = function (effect) {
  39965. _this._updateMeshScreenCoordinates(scene);
  39966. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  39967. effect.setFloat("exposure", _this.exposure);
  39968. effect.setFloat("decay", _this.decay);
  39969. effect.setFloat("weight", _this.weight);
  39970. effect.setFloat("density", _this.density);
  39971. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  39972. };
  39973. }
  39974. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  39975. get: function () {
  39976. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  39977. return false;
  39978. },
  39979. set: function (useDiffuseColor) {
  39980. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  39981. },
  39982. enumerable: true,
  39983. configurable: true
  39984. });
  39985. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  39986. var mesh = subMesh.getMesh();
  39987. // Render this.mesh as default
  39988. if (mesh === this.mesh) {
  39989. return mesh.material.isReady(mesh);
  39990. }
  39991. var defines = [];
  39992. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39993. var material = subMesh.getMaterial();
  39994. var needUV = false;
  39995. // Alpha test
  39996. if (material) {
  39997. if (material.needAlphaTesting()) {
  39998. defines.push("#define ALPHATEST");
  39999. }
  40000. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  40001. attribs.push(BABYLON.VertexBuffer.UVKind);
  40002. defines.push("#define UV1");
  40003. }
  40004. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  40005. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40006. defines.push("#define UV2");
  40007. }
  40008. }
  40009. // Bones
  40010. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  40011. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40012. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40013. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  40014. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  40015. }
  40016. else {
  40017. defines.push("#define NUM_BONE_INFLUENCERS 0");
  40018. }
  40019. // Instances
  40020. if (useInstances) {
  40021. defines.push("#define INSTANCES");
  40022. attribs.push("world0");
  40023. attribs.push("world1");
  40024. attribs.push("world2");
  40025. attribs.push("world3");
  40026. }
  40027. // Get correct effect
  40028. var join = defines.join("\n");
  40029. if (this._cachedDefines !== join) {
  40030. this._cachedDefines = join;
  40031. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  40032. }
  40033. return this._volumetricLightScatteringPass.isReady();
  40034. };
  40035. /**
  40036. * Sets the new light position for light scattering effect
  40037. * @param {BABYLON.Vector3} The new custom light position
  40038. */
  40039. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  40040. this.customMeshPosition = position;
  40041. };
  40042. /**
  40043. * Returns the light position for light scattering effect
  40044. * @return {BABYLON.Vector3} The custom light position
  40045. */
  40046. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  40047. return this.customMeshPosition;
  40048. };
  40049. /**
  40050. * Disposes the internal assets and detaches the post-process from the camera
  40051. */
  40052. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  40053. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  40054. if (rttIndex !== -1) {
  40055. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  40056. }
  40057. this._volumetricLightScatteringRTT.dispose();
  40058. _super.prototype.dispose.call(this, camera);
  40059. };
  40060. /**
  40061. * Returns the render target texture used by the post-process
  40062. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  40063. */
  40064. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  40065. return this._volumetricLightScatteringRTT;
  40066. };
  40067. // Private methods
  40068. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  40069. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  40070. return true;
  40071. }
  40072. return false;
  40073. };
  40074. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  40075. var _this = this;
  40076. var engine = scene.getEngine();
  40077. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  40078. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40079. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40080. this._volumetricLightScatteringRTT.renderList = null;
  40081. this._volumetricLightScatteringRTT.renderParticles = false;
  40082. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  40083. // Custom render function for submeshes
  40084. var renderSubMesh = function (subMesh) {
  40085. var mesh = subMesh.getRenderingMesh();
  40086. if (_this._meshExcluded(mesh)) {
  40087. return;
  40088. }
  40089. var scene = mesh.getScene();
  40090. var engine = scene.getEngine();
  40091. // Culling
  40092. engine.setState(subMesh.getMaterial().backFaceCulling);
  40093. // Managing instances
  40094. var batch = mesh._getInstancesRenderList(subMesh._id);
  40095. if (batch.mustReturn) {
  40096. return;
  40097. }
  40098. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  40099. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  40100. var effect = _this._volumetricLightScatteringPass;
  40101. if (mesh === _this.mesh) {
  40102. effect = subMesh.getMaterial().getEffect();
  40103. }
  40104. engine.enableEffect(effect);
  40105. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  40106. if (mesh === _this.mesh) {
  40107. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  40108. }
  40109. else {
  40110. var material = subMesh.getMaterial();
  40111. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  40112. // Alpha test
  40113. if (material && material.needAlphaTesting()) {
  40114. var alphaTexture = material.getAlphaTestTexture();
  40115. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  40116. if (alphaTexture) {
  40117. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  40118. }
  40119. }
  40120. // Bones
  40121. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  40122. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  40123. }
  40124. }
  40125. // Draw
  40126. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  40127. }
  40128. };
  40129. // Render target texture callbacks
  40130. var savedSceneClearColor;
  40131. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  40132. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  40133. savedSceneClearColor = scene.clearColor;
  40134. scene.clearColor = sceneClearColor;
  40135. };
  40136. this._volumetricLightScatteringRTT.onAfterRender = function () {
  40137. scene.clearColor = savedSceneClearColor;
  40138. };
  40139. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  40140. var engine = scene.getEngine();
  40141. var index;
  40142. for (index = 0; index < opaqueSubMeshes.length; index++) {
  40143. renderSubMesh(opaqueSubMeshes.data[index]);
  40144. }
  40145. engine.setAlphaTesting(true);
  40146. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  40147. renderSubMesh(alphaTestSubMeshes.data[index]);
  40148. }
  40149. engine.setAlphaTesting(false);
  40150. if (transparentSubMeshes.length) {
  40151. // Sort sub meshes
  40152. for (index = 0; index < transparentSubMeshes.length; index++) {
  40153. var submesh = transparentSubMeshes.data[index];
  40154. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  40155. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  40156. }
  40157. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  40158. sortedArray.sort(function (a, b) {
  40159. // Alpha index first
  40160. if (a._alphaIndex > b._alphaIndex) {
  40161. return 1;
  40162. }
  40163. if (a._alphaIndex < b._alphaIndex) {
  40164. return -1;
  40165. }
  40166. // Then distance to camera
  40167. if (a._distanceToCamera < b._distanceToCamera) {
  40168. return 1;
  40169. }
  40170. if (a._distanceToCamera > b._distanceToCamera) {
  40171. return -1;
  40172. }
  40173. return 0;
  40174. });
  40175. // Render sub meshes
  40176. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  40177. for (index = 0; index < sortedArray.length; index++) {
  40178. renderSubMesh(sortedArray[index]);
  40179. }
  40180. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40181. }
  40182. };
  40183. };
  40184. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  40185. var transform = scene.getTransformMatrix();
  40186. var meshPosition;
  40187. if (this.useCustomMeshPosition) {
  40188. meshPosition = this.customMeshPosition;
  40189. }
  40190. else if (this.attachedNode) {
  40191. meshPosition = this.attachedNode.position;
  40192. }
  40193. else {
  40194. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  40195. }
  40196. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  40197. this._screenCoordinates.x = pos.x / this._viewPort.width;
  40198. this._screenCoordinates.y = pos.y / this._viewPort.height;
  40199. if (this.invert)
  40200. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  40201. };
  40202. // Static methods
  40203. /**
  40204. * Creates a default mesh for the Volumeric Light Scattering post-process
  40205. * @param {string} The mesh name
  40206. * @param {BABYLON.Scene} The scene where to create the mesh
  40207. * @return {BABYLON.Mesh} the default mesh
  40208. */
  40209. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  40210. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  40211. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  40212. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  40213. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  40214. mesh.material = material;
  40215. return mesh;
  40216. };
  40217. __decorate([
  40218. BABYLON.serializeAsVector3()
  40219. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  40220. __decorate([
  40221. BABYLON.serialize()
  40222. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  40223. __decorate([
  40224. BABYLON.serialize()
  40225. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  40226. __decorate([
  40227. BABYLON.serializeAsMeshReference()
  40228. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  40229. __decorate([
  40230. BABYLON.serialize()
  40231. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  40232. __decorate([
  40233. BABYLON.serialize()
  40234. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  40235. __decorate([
  40236. BABYLON.serialize()
  40237. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  40238. __decorate([
  40239. BABYLON.serialize()
  40240. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  40241. __decorate([
  40242. BABYLON.serialize()
  40243. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  40244. return VolumetricLightScatteringPostProcess;
  40245. })(BABYLON.PostProcess);
  40246. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  40247. })(BABYLON || (BABYLON = {}));
  40248. // BABYLON.JS Chromatic Aberration GLSL Shader
  40249. // Author: Olivier Guyot
  40250. // Separates very slightly R, G and B colors on the edges of the screen
  40251. // Inspired by Francois Tarlier & Martins Upitis
  40252. var BABYLON;
  40253. (function (BABYLON) {
  40254. var LensRenderingPipeline = (function (_super) {
  40255. __extends(LensRenderingPipeline, _super);
  40256. /**
  40257. * @constructor
  40258. *
  40259. * Effect parameters are as follow:
  40260. * {
  40261. * chromatic_aberration: number; // from 0 to x (1 for realism)
  40262. * edge_blur: number; // from 0 to x (1 for realism)
  40263. * distortion: number; // from 0 to x (1 for realism)
  40264. * grain_amount: number; // from 0 to 1
  40265. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  40266. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  40267. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  40268. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  40269. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  40270. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  40271. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  40272. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  40273. * }
  40274. * Note: if an effect parameter is unset, effect is disabled
  40275. *
  40276. * @param {string} name - The rendering pipeline name
  40277. * @param {object} parameters - An object containing all parameters (see above)
  40278. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  40279. * @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)
  40280. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  40281. */
  40282. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  40283. var _this = this;
  40284. if (ratio === void 0) { ratio = 1.0; }
  40285. _super.call(this, scene.getEngine(), name);
  40286. // Lens effects can be of the following:
  40287. // - chromatic aberration (slight shift of RGB colors)
  40288. // - blur on the edge of the lens
  40289. // - lens distortion
  40290. // - depth-of-field blur & highlights enhancing
  40291. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  40292. // - grain effect (noise or custom texture)
  40293. // Two additional texture samplers are needed:
  40294. // - depth map (for depth-of-field)
  40295. // - grain texture
  40296. /**
  40297. * The chromatic aberration PostProcess id in the pipeline
  40298. * @type {string}
  40299. */
  40300. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  40301. /**
  40302. * The highlights enhancing PostProcess id in the pipeline
  40303. * @type {string}
  40304. */
  40305. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  40306. /**
  40307. * The depth-of-field PostProcess id in the pipeline
  40308. * @type {string}
  40309. */
  40310. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  40311. this._scene = scene;
  40312. // Fetch texture samplers
  40313. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  40314. if (parameters.grain_texture) {
  40315. this._grainTexture = parameters.grain_texture;
  40316. }
  40317. else {
  40318. this._createGrainTexture();
  40319. }
  40320. // save parameters
  40321. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  40322. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  40323. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  40324. this._distortion = parameters.distortion ? parameters.distortion : 0;
  40325. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  40326. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  40327. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  40328. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  40329. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  40330. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  40331. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  40332. // Create effects
  40333. this._createChromaticAberrationPostProcess(ratio);
  40334. this._createHighlightsPostProcess(ratio);
  40335. this._createDepthOfFieldPostProcess(ratio / 4);
  40336. // Set up pipeline
  40337. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  40338. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  40339. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  40340. if (this._highlightsGain === -1) {
  40341. this._disableEffect(this.HighlightsEnhancingEffect, null);
  40342. }
  40343. // Finish
  40344. scene.postProcessRenderPipelineManager.addPipeline(this);
  40345. if (cameras) {
  40346. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  40347. }
  40348. }
  40349. // public methods (self explanatory)
  40350. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  40351. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  40352. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  40353. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  40354. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  40355. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  40356. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  40357. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  40358. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  40359. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  40360. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  40361. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  40362. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  40363. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  40364. };
  40365. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  40366. this._highlightsPostProcess.updateEffect();
  40367. };
  40368. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  40369. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  40370. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  40371. this._highlightsGain = amount;
  40372. };
  40373. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  40374. if (this._highlightsGain === -1) {
  40375. this._highlightsGain = 1.0;
  40376. }
  40377. this._highlightsThreshold = amount;
  40378. };
  40379. LensRenderingPipeline.prototype.disableHighlights = function () {
  40380. this._highlightsGain = -1;
  40381. };
  40382. /**
  40383. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  40384. */
  40385. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  40386. if (disableDepthRender === void 0) { disableDepthRender = false; }
  40387. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  40388. this._chromaticAberrationPostProcess = undefined;
  40389. this._highlightsPostProcess = undefined;
  40390. this._depthOfFieldPostProcess = undefined;
  40391. this._grainTexture.dispose();
  40392. if (disableDepthRender)
  40393. this._scene.disableDepthRenderer();
  40394. };
  40395. // colors shifting and distortion
  40396. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  40397. var _this = this;
  40398. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  40399. [], // samplers
  40400. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  40401. this._chromaticAberrationPostProcess.onApply = function (effect) {
  40402. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  40403. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  40404. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  40405. };
  40406. };
  40407. // highlights enhancing
  40408. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  40409. var _this = this;
  40410. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  40411. [], // samplers
  40412. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  40413. this._highlightsPostProcess.onApply = function (effect) {
  40414. effect.setFloat('gain', _this._highlightsGain);
  40415. effect.setFloat('threshold', _this._highlightsThreshold);
  40416. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  40417. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  40418. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  40419. };
  40420. };
  40421. // colors shifting and distortion
  40422. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  40423. var _this = this;
  40424. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  40425. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  40426. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  40427. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  40428. this._depthOfFieldPostProcess.onApply = function (effect) {
  40429. effect.setTexture("depthSampler", _this._depthTexture);
  40430. effect.setTexture("grainSampler", _this._grainTexture);
  40431. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  40432. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  40433. effect.setFloat('grain_amount', _this._grainAmount);
  40434. effect.setBool('blur_noise', _this._blurNoise);
  40435. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  40436. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  40437. effect.setFloat('distortion', _this._distortion);
  40438. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  40439. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  40440. effect.setFloat('aperture', _this._dofAperture);
  40441. effect.setFloat('darken', _this._dofDarken);
  40442. effect.setFloat('edge_blur', _this._edgeBlur);
  40443. effect.setBool('highlights', (_this._highlightsGain !== -1));
  40444. effect.setFloat('near', _this._scene.activeCamera.minZ);
  40445. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  40446. };
  40447. };
  40448. // creates a black and white random noise texture, 512x512
  40449. LensRenderingPipeline.prototype._createGrainTexture = function () {
  40450. var size = 512;
  40451. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  40452. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  40453. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  40454. var context = this._grainTexture.getContext();
  40455. var rand = function (min, max) {
  40456. return Math.random() * (max - min) + min;
  40457. };
  40458. var value;
  40459. for (var x = 0; x < size; x++) {
  40460. for (var y = 0; y < size; y++) {
  40461. value = Math.floor(rand(0.42, 0.58) * 255);
  40462. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  40463. context.fillRect(x, y, 1, 1);
  40464. }
  40465. }
  40466. this._grainTexture.update(false);
  40467. };
  40468. return LensRenderingPipeline;
  40469. })(BABYLON.PostProcessRenderPipeline);
  40470. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  40471. })(BABYLON || (BABYLON = {}));
  40472. //
  40473. // This post-process allows the modification of rendered colors by using
  40474. // a 'look-up table' (LUT). This effect is also called Color Grading.
  40475. //
  40476. // The object needs to be provided an url to a texture containing the color
  40477. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  40478. // Use an image editing software to tweak the LUT to match your needs.
  40479. //
  40480. // For an example of a color LUT, see here:
  40481. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  40482. // For explanations on color grading, see here:
  40483. // http://udn.epicgames.com/Three/ColorGrading.html
  40484. //
  40485. var BABYLON;
  40486. (function (BABYLON) {
  40487. var ColorCorrectionPostProcess = (function (_super) {
  40488. __extends(ColorCorrectionPostProcess, _super);
  40489. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  40490. var _this = this;
  40491. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  40492. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  40493. this._colorTableTexture.anisotropicFilteringLevel = 1;
  40494. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40495. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40496. this.onApply = function (effect) {
  40497. effect.setTexture("colorTable", _this._colorTableTexture);
  40498. };
  40499. }
  40500. return ColorCorrectionPostProcess;
  40501. })(BABYLON.PostProcess);
  40502. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  40503. })(BABYLON || (BABYLON = {}));
  40504. var BABYLON;
  40505. (function (BABYLON) {
  40506. var AnaglyphFreeCamera = (function (_super) {
  40507. __extends(AnaglyphFreeCamera, _super);
  40508. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  40509. _super.call(this, name, position, scene);
  40510. this.interaxialDistance = interaxialDistance;
  40511. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  40512. }
  40513. AnaglyphFreeCamera.prototype.getTypeName = function () {
  40514. return "AnaglyphFreeCamera";
  40515. };
  40516. return AnaglyphFreeCamera;
  40517. })(BABYLON.FreeCamera);
  40518. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  40519. var AnaglyphArcRotateCamera = (function (_super) {
  40520. __extends(AnaglyphArcRotateCamera, _super);
  40521. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  40522. _super.call(this, name, alpha, beta, radius, target, scene);
  40523. this.interaxialDistance = interaxialDistance;
  40524. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  40525. }
  40526. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  40527. return "AnaglyphArcRotateCamera";
  40528. };
  40529. return AnaglyphArcRotateCamera;
  40530. })(BABYLON.ArcRotateCamera);
  40531. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  40532. var AnaglyphGamepadCamera = (function (_super) {
  40533. __extends(AnaglyphGamepadCamera, _super);
  40534. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  40535. _super.call(this, name, position, scene);
  40536. this.interaxialDistance = interaxialDistance;
  40537. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  40538. }
  40539. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  40540. return "AnaglyphGamepadCamera";
  40541. };
  40542. return AnaglyphGamepadCamera;
  40543. })(BABYLON.GamepadCamera);
  40544. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  40545. var AnaglyphUniversalCamera = (function (_super) {
  40546. __extends(AnaglyphUniversalCamera, _super);
  40547. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  40548. _super.call(this, name, position, scene);
  40549. this.interaxialDistance = interaxialDistance;
  40550. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  40551. }
  40552. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  40553. return "AnaglyphUniversalCamera";
  40554. };
  40555. return AnaglyphUniversalCamera;
  40556. })(BABYLON.UniversalCamera);
  40557. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  40558. var StereoscopicFreeCamera = (function (_super) {
  40559. __extends(StereoscopicFreeCamera, _super);
  40560. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  40561. _super.call(this, name, position, scene);
  40562. this.interaxialDistance = interaxialDistance;
  40563. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  40564. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  40565. }
  40566. StereoscopicFreeCamera.prototype.getTypeName = function () {
  40567. return "StereoscopicFreeCamera";
  40568. };
  40569. return StereoscopicFreeCamera;
  40570. })(BABYLON.FreeCamera);
  40571. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  40572. var StereoscopicArcRotateCamera = (function (_super) {
  40573. __extends(StereoscopicArcRotateCamera, _super);
  40574. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  40575. _super.call(this, name, alpha, beta, radius, target, scene);
  40576. this.interaxialDistance = interaxialDistance;
  40577. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  40578. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  40579. }
  40580. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  40581. return "StereoscopicArcRotateCamera";
  40582. };
  40583. return StereoscopicArcRotateCamera;
  40584. })(BABYLON.ArcRotateCamera);
  40585. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  40586. var StereoscopicGamepadCamera = (function (_super) {
  40587. __extends(StereoscopicGamepadCamera, _super);
  40588. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  40589. _super.call(this, name, position, scene);
  40590. this.interaxialDistance = interaxialDistance;
  40591. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  40592. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  40593. }
  40594. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  40595. return "StereoscopicGamepadCamera";
  40596. };
  40597. return StereoscopicGamepadCamera;
  40598. })(BABYLON.GamepadCamera);
  40599. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  40600. var StereoscopicUniversalCamera = (function (_super) {
  40601. __extends(StereoscopicUniversalCamera, _super);
  40602. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  40603. _super.call(this, name, position, scene);
  40604. this.interaxialDistance = interaxialDistance;
  40605. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  40606. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  40607. }
  40608. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  40609. return "StereoscopicUniversalCamera";
  40610. };
  40611. return StereoscopicUniversalCamera;
  40612. })(BABYLON.UniversalCamera);
  40613. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  40614. })(BABYLON || (BABYLON = {}));
  40615. var BABYLON;
  40616. (function (BABYLON) {
  40617. var HDRRenderingPipeline = (function (_super) {
  40618. __extends(HDRRenderingPipeline, _super);
  40619. /**
  40620. * @constructor
  40621. * @param {string} name - The rendering pipeline name
  40622. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  40623. * @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)
  40624. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  40625. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  40626. */
  40627. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  40628. var _this = this;
  40629. if (originalPostProcess === void 0) { originalPostProcess = null; }
  40630. _super.call(this, scene.getEngine(), name);
  40631. /**
  40632. * Public members
  40633. */
  40634. // Gaussian Blur
  40635. /**
  40636. * Gaussian blur coefficient
  40637. * @type {number}
  40638. */
  40639. this.gaussCoeff = 0.3;
  40640. /**
  40641. * Gaussian blur mean
  40642. * @type {number}
  40643. */
  40644. this.gaussMean = 1.0;
  40645. /**
  40646. * Gaussian blur standard deviation
  40647. * @type {number}
  40648. */
  40649. this.gaussStandDev = 0.8;
  40650. /**
  40651. * Gaussian blur multiplier. Multiplies the blur effect
  40652. * @type {number}
  40653. */
  40654. this.gaussMultiplier = 4.0;
  40655. // HDR
  40656. /**
  40657. * Exposure, controls the overall intensity of the pipeline
  40658. * @type {number}
  40659. */
  40660. this.exposure = 1.0;
  40661. /**
  40662. * Minimum luminance that the post-process can output. Luminance is >= 0
  40663. * @type {number}
  40664. */
  40665. this.minimumLuminance = 1.0;
  40666. /**
  40667. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  40668. * @type {number}
  40669. */
  40670. this.maximumLuminance = 1e20;
  40671. /**
  40672. * Increase rate for luminance: eye adaptation speed to dark
  40673. * @type {number}
  40674. */
  40675. this.luminanceIncreaserate = 0.5;
  40676. /**
  40677. * Decrease rate for luminance: eye adaptation speed to bright
  40678. * @type {number}
  40679. */
  40680. this.luminanceDecreaseRate = 0.5;
  40681. // Bright pass
  40682. /**
  40683. * Minimum luminance needed to compute HDR
  40684. * @type {number}
  40685. */
  40686. this.brightThreshold = 0.8;
  40687. this._needUpdate = true;
  40688. this._scene = scene;
  40689. // Bright pass
  40690. this._createBrightPassPostProcess(scene, ratio);
  40691. // Down sample X4
  40692. this._createDownSampleX4PostProcess(scene, ratio);
  40693. // Create gaussian blur post-processes
  40694. this._createGaussianBlurPostProcess(scene, ratio);
  40695. // Texture adder
  40696. this._createTextureAdderPostProcess(scene, ratio);
  40697. // Luminance generator
  40698. this._createLuminanceGeneratorPostProcess(scene);
  40699. // HDR
  40700. this._createHDRPostProcess(scene, ratio);
  40701. // Pass postprocess
  40702. if (originalPostProcess === null) {
  40703. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  40704. }
  40705. else {
  40706. this._originalPostProcess = originalPostProcess;
  40707. }
  40708. // Configure pipeline
  40709. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  40710. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  40711. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  40712. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  40713. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  40714. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  40715. var addDownSamplerPostProcess = function (id) {
  40716. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  40717. };
  40718. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  40719. addDownSamplerPostProcess(i);
  40720. }
  40721. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  40722. // Finish
  40723. scene.postProcessRenderPipelineManager.addPipeline(this);
  40724. if (cameras !== null) {
  40725. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  40726. }
  40727. this.update();
  40728. }
  40729. /**
  40730. * Tells the pipeline to update its post-processes
  40731. */
  40732. HDRRenderingPipeline.prototype.update = function () {
  40733. this._needUpdate = true;
  40734. };
  40735. /**
  40736. * Returns the current calculated luminance
  40737. */
  40738. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  40739. return this._hdrCurrentLuminance;
  40740. };
  40741. /**
  40742. * Returns the currently drawn luminance
  40743. */
  40744. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  40745. return this._hdrOutputLuminance;
  40746. };
  40747. /**
  40748. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  40749. */
  40750. HDRRenderingPipeline.prototype.dispose = function () {
  40751. this._originalPostProcess = undefined;
  40752. this._brightPassPostProcess = undefined;
  40753. this._downSampleX4PostProcess = undefined;
  40754. this._guassianBlurHPostProcess = undefined;
  40755. this._guassianBlurVPostProcess = undefined;
  40756. this._textureAdderPostProcess = undefined;
  40757. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  40758. this._downSamplePostProcesses[i] = undefined;
  40759. }
  40760. this._hdrPostProcess = undefined;
  40761. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  40762. };
  40763. /**
  40764. * Creates the HDR post-process and computes the luminance adaptation
  40765. */
  40766. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  40767. var _this = this;
  40768. var hdrLastLuminance = 0.0;
  40769. this._hdrOutputLuminance = -1.0;
  40770. this._hdrCurrentLuminance = 1.0;
  40771. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  40772. this._hdrPostProcess.onApply = function (effect) {
  40773. if (_this._hdrOutputLuminance < 0.0) {
  40774. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  40775. }
  40776. else {
  40777. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  40778. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  40779. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  40780. }
  40781. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  40782. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  40783. }
  40784. else {
  40785. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  40786. }
  40787. }
  40788. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  40789. hdrLastLuminance += scene.getEngine().getDeltaTime();
  40790. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  40791. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  40792. effect.setFloat("exposure", _this.exposure);
  40793. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  40794. _this._needUpdate = false;
  40795. };
  40796. };
  40797. /**
  40798. * Texture Adder post-process
  40799. */
  40800. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  40801. var _this = this;
  40802. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  40803. this._textureAdderPostProcess.onApply = function (effect) {
  40804. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  40805. };
  40806. };
  40807. /**
  40808. * Down sample X4 post-process
  40809. */
  40810. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  40811. var _this = this;
  40812. var downSampleX4Offsets = new Array(32);
  40813. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  40814. this._downSampleX4PostProcess.onApply = function (effect) {
  40815. if (_this._needUpdate) {
  40816. var id = 0;
  40817. for (var i = -2; i < 2; i++) {
  40818. for (var j = -2; j < 2; j++) {
  40819. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  40820. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  40821. id += 2;
  40822. }
  40823. }
  40824. }
  40825. effect.setArray2("dsOffsets", downSampleX4Offsets);
  40826. };
  40827. };
  40828. /**
  40829. * Bright pass post-process
  40830. */
  40831. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  40832. var _this = this;
  40833. var brightOffsets = new Array(8);
  40834. var brightPassCallback = function (effect) {
  40835. if (_this._needUpdate) {
  40836. var sU = (1.0 / _this._brightPassPostProcess.width);
  40837. var sV = (1.0 / _this._brightPassPostProcess.height);
  40838. brightOffsets[0] = -0.5 * sU;
  40839. brightOffsets[1] = 0.5 * sV;
  40840. brightOffsets[2] = 0.5 * sU;
  40841. brightOffsets[3] = 0.5 * sV;
  40842. brightOffsets[4] = -0.5 * sU;
  40843. brightOffsets[5] = -0.5 * sV;
  40844. brightOffsets[6] = 0.5 * sU;
  40845. brightOffsets[7] = -0.5 * sV;
  40846. }
  40847. effect.setArray2("dsOffsets", brightOffsets);
  40848. effect.setFloat("brightThreshold", _this.brightThreshold);
  40849. };
  40850. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  40851. this._brightPassPostProcess.onApply = brightPassCallback;
  40852. };
  40853. /**
  40854. * Luminance generator. Creates the luminance post-process and down sample post-processes
  40855. */
  40856. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  40857. var _this = this;
  40858. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  40859. var luminanceOffsets = new Array(8);
  40860. var downSampleOffsets = new Array(18);
  40861. var halfDestPixelSize;
  40862. this._downSamplePostProcesses = new Array(lumSteps);
  40863. // Utils for luminance
  40864. var luminanceUpdateSourceOffsets = function (width, height) {
  40865. var sU = (1.0 / width);
  40866. var sV = (1.0 / height);
  40867. luminanceOffsets[0] = -0.5 * sU;
  40868. luminanceOffsets[1] = 0.5 * sV;
  40869. luminanceOffsets[2] = 0.5 * sU;
  40870. luminanceOffsets[3] = 0.5 * sV;
  40871. luminanceOffsets[4] = -0.5 * sU;
  40872. luminanceOffsets[5] = -0.5 * sV;
  40873. luminanceOffsets[6] = 0.5 * sU;
  40874. luminanceOffsets[7] = -0.5 * sV;
  40875. };
  40876. var luminanceUpdateDestOffsets = function (width, height) {
  40877. var id = 0;
  40878. for (var x = -1; x < 2; x++) {
  40879. for (var y = -1; y < 2; y++) {
  40880. downSampleOffsets[id] = (x) / width;
  40881. downSampleOffsets[id + 1] = (y) / height;
  40882. id += 2;
  40883. }
  40884. }
  40885. };
  40886. // Luminance callback
  40887. var luminanceCallback = function (effect) {
  40888. if (_this._needUpdate) {
  40889. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  40890. }
  40891. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  40892. effect.setArray2("lumOffsets", luminanceOffsets);
  40893. };
  40894. // Down sample callbacks
  40895. var downSampleCallback = function (indice) {
  40896. var i = indice;
  40897. return function (effect) {
  40898. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  40899. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  40900. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  40901. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  40902. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  40903. effect.setArray2("dsOffsets", downSampleOffsets);
  40904. };
  40905. };
  40906. var downSampleAfterRenderCallback = function (effect) {
  40907. // Unpack result
  40908. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  40909. 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);
  40910. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  40911. };
  40912. // Create luminance post-process
  40913. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  40914. 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);
  40915. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  40916. // Create down sample post-processes
  40917. for (var i = lumSteps - 2; i >= 0; i--) {
  40918. var length = Math.pow(3, i);
  40919. ratio = { width: length, height: length };
  40920. var defines = "#define DOWN_SAMPLE\n";
  40921. if (i === 0) {
  40922. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  40923. }
  40924. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  40925. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  40926. if (i === 0) {
  40927. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  40928. }
  40929. }
  40930. };
  40931. /**
  40932. * Gaussian blur post-processes. Horizontal and Vertical
  40933. */
  40934. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  40935. var _this = this;
  40936. var blurOffsetsW = new Array(9);
  40937. var blurOffsetsH = new Array(9);
  40938. var blurWeights = new Array(9);
  40939. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  40940. // Utils for gaussian blur
  40941. var calculateBlurOffsets = function (height) {
  40942. var lastOutputDimensions = {
  40943. width: scene.getEngine().getRenderWidth(),
  40944. height: scene.getEngine().getRenderHeight()
  40945. };
  40946. for (var i = 0; i < 9; i++) {
  40947. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  40948. if (height) {
  40949. blurOffsetsH[i] = value;
  40950. }
  40951. else {
  40952. blurOffsetsW[i] = value;
  40953. }
  40954. }
  40955. };
  40956. var calculateWeights = function () {
  40957. var x = 0.0;
  40958. for (var i = 0; i < 9; i++) {
  40959. x = (i - 4.0) / 4.0;
  40960. 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));
  40961. }
  40962. };
  40963. // Callback
  40964. var gaussianBlurCallback = function (height) {
  40965. return function (effect) {
  40966. if (_this._needUpdate) {
  40967. calculateWeights();
  40968. calculateBlurOffsets(height);
  40969. }
  40970. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  40971. effect.setArray("blurWeights", blurWeights);
  40972. effect.setFloat("multiplier", _this.gaussMultiplier);
  40973. };
  40974. };
  40975. // Create horizontal gaussian blur post-processes
  40976. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  40977. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  40978. // Create vertical gaussian blur post-process
  40979. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  40980. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  40981. };
  40982. // Luminance generator
  40983. HDRRenderingPipeline.LUM_STEPS = 6;
  40984. return HDRRenderingPipeline;
  40985. })(BABYLON.PostProcessRenderPipeline);
  40986. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  40987. })(BABYLON || (BABYLON = {}));
  40988. var BABYLON;
  40989. (function (BABYLON) {
  40990. var FaceAdjacencies = (function () {
  40991. function FaceAdjacencies() {
  40992. this.edges = new Array();
  40993. this.edgesConnectedCount = 0;
  40994. }
  40995. return FaceAdjacencies;
  40996. })();
  40997. var EdgesRenderer = (function () {
  40998. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  40999. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  41000. if (epsilon === void 0) { epsilon = 0.95; }
  41001. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  41002. this.edgesWidthScalerForOrthographic = 1000.0;
  41003. this.edgesWidthScalerForPerspective = 50.0;
  41004. this._linesPositions = new Array();
  41005. this._linesNormals = new Array();
  41006. this._linesIndices = new Array();
  41007. this._buffers = new Array();
  41008. this._checkVerticesInsteadOfIndices = false;
  41009. this._source = source;
  41010. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  41011. this._epsilon = epsilon;
  41012. this._prepareRessources();
  41013. this._generateEdgesLines();
  41014. }
  41015. EdgesRenderer.prototype._prepareRessources = function () {
  41016. if (this._lineShader) {
  41017. return;
  41018. }
  41019. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  41020. attributes: ["position", "normal"],
  41021. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  41022. });
  41023. this._lineShader.disableDepthWrite = true;
  41024. this._lineShader.backFaceCulling = false;
  41025. };
  41026. EdgesRenderer.prototype.dispose = function () {
  41027. this._vb0.dispose();
  41028. this._vb1.dispose();
  41029. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  41030. this._lineShader.dispose();
  41031. };
  41032. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  41033. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  41034. return 0;
  41035. }
  41036. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  41037. return 1;
  41038. }
  41039. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  41040. return 2;
  41041. }
  41042. return -1;
  41043. };
  41044. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  41045. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  41046. return 0;
  41047. }
  41048. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  41049. return 1;
  41050. }
  41051. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  41052. return 2;
  41053. }
  41054. return -1;
  41055. };
  41056. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  41057. var needToCreateLine;
  41058. if (edge === undefined) {
  41059. needToCreateLine = true;
  41060. }
  41061. else {
  41062. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  41063. needToCreateLine = dotProduct < this._epsilon;
  41064. }
  41065. if (needToCreateLine) {
  41066. var offset = this._linesPositions.length / 3;
  41067. var normal = p0.subtract(p1);
  41068. normal.normalize();
  41069. // Positions
  41070. this._linesPositions.push(p0.x);
  41071. this._linesPositions.push(p0.y);
  41072. this._linesPositions.push(p0.z);
  41073. this._linesPositions.push(p0.x);
  41074. this._linesPositions.push(p0.y);
  41075. this._linesPositions.push(p0.z);
  41076. this._linesPositions.push(p1.x);
  41077. this._linesPositions.push(p1.y);
  41078. this._linesPositions.push(p1.z);
  41079. this._linesPositions.push(p1.x);
  41080. this._linesPositions.push(p1.y);
  41081. this._linesPositions.push(p1.z);
  41082. // Normals
  41083. this._linesNormals.push(p1.x);
  41084. this._linesNormals.push(p1.y);
  41085. this._linesNormals.push(p1.z);
  41086. this._linesNormals.push(-1);
  41087. this._linesNormals.push(p1.x);
  41088. this._linesNormals.push(p1.y);
  41089. this._linesNormals.push(p1.z);
  41090. this._linesNormals.push(1);
  41091. this._linesNormals.push(p0.x);
  41092. this._linesNormals.push(p0.y);
  41093. this._linesNormals.push(p0.z);
  41094. this._linesNormals.push(-1);
  41095. this._linesNormals.push(p0.x);
  41096. this._linesNormals.push(p0.y);
  41097. this._linesNormals.push(p0.z);
  41098. this._linesNormals.push(1);
  41099. // Indices
  41100. this._linesIndices.push(offset);
  41101. this._linesIndices.push(offset + 1);
  41102. this._linesIndices.push(offset + 2);
  41103. this._linesIndices.push(offset);
  41104. this._linesIndices.push(offset + 2);
  41105. this._linesIndices.push(offset + 3);
  41106. }
  41107. };
  41108. EdgesRenderer.prototype._generateEdgesLines = function () {
  41109. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41110. var indices = this._source.getIndices();
  41111. // First let's find adjacencies
  41112. var adjacencies = new Array();
  41113. var faceNormals = new Array();
  41114. var index;
  41115. var faceAdjacencies;
  41116. // Prepare faces
  41117. for (index = 0; index < indices.length; index += 3) {
  41118. faceAdjacencies = new FaceAdjacencies();
  41119. var p0Index = indices[index];
  41120. var p1Index = indices[index + 1];
  41121. var p2Index = indices[index + 2];
  41122. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  41123. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  41124. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  41125. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  41126. faceNormal.normalize();
  41127. faceNormals.push(faceNormal);
  41128. adjacencies.push(faceAdjacencies);
  41129. }
  41130. // Scan
  41131. for (index = 0; index < adjacencies.length; index++) {
  41132. faceAdjacencies = adjacencies[index];
  41133. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  41134. var otherFaceAdjacencies = adjacencies[otherIndex];
  41135. if (faceAdjacencies.edgesConnectedCount === 3) {
  41136. break;
  41137. }
  41138. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  41139. continue;
  41140. }
  41141. var otherP0 = indices[otherIndex * 3];
  41142. var otherP1 = indices[otherIndex * 3 + 1];
  41143. var otherP2 = indices[otherIndex * 3 + 2];
  41144. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  41145. var otherEdgeIndex;
  41146. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  41147. continue;
  41148. }
  41149. switch (edgeIndex) {
  41150. case 0:
  41151. if (this._checkVerticesInsteadOfIndices) {
  41152. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  41153. }
  41154. else {
  41155. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  41156. }
  41157. break;
  41158. case 1:
  41159. if (this._checkVerticesInsteadOfIndices) {
  41160. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  41161. }
  41162. else {
  41163. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  41164. }
  41165. break;
  41166. case 2:
  41167. if (this._checkVerticesInsteadOfIndices) {
  41168. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  41169. }
  41170. else {
  41171. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  41172. }
  41173. break;
  41174. }
  41175. if (otherEdgeIndex === -1) {
  41176. continue;
  41177. }
  41178. faceAdjacencies.edges[edgeIndex] = otherIndex;
  41179. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  41180. faceAdjacencies.edgesConnectedCount++;
  41181. otherFaceAdjacencies.edgesConnectedCount++;
  41182. if (faceAdjacencies.edgesConnectedCount === 3) {
  41183. break;
  41184. }
  41185. }
  41186. }
  41187. }
  41188. // Create lines
  41189. for (index = 0; index < adjacencies.length; index++) {
  41190. // 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
  41191. var current = adjacencies[index];
  41192. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  41193. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  41194. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  41195. }
  41196. // Merge into a single mesh
  41197. var engine = this._source.getScene().getEngine();
  41198. this._vb0 = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  41199. this._vb1 = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  41200. this._buffers[BABYLON.VertexBuffer.PositionKind] = this._vb0;
  41201. this._buffers[BABYLON.VertexBuffer.NormalKind] = this._vb1;
  41202. this._ib = engine.createIndexBuffer(this._linesIndices);
  41203. this._indicesCount = this._linesIndices.length;
  41204. };
  41205. EdgesRenderer.prototype.render = function () {
  41206. if (!this._lineShader.isReady()) {
  41207. return;
  41208. }
  41209. var scene = this._source.getScene();
  41210. var engine = scene.getEngine();
  41211. this._lineShader._preBind();
  41212. // VBOs
  41213. engine.bindMultiBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  41214. scene.resetCachedMaterial();
  41215. this._lineShader.setColor4("color", this._source.edgesColor);
  41216. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  41217. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  41218. }
  41219. else {
  41220. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  41221. }
  41222. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  41223. this._lineShader.bind(this._source.getWorldMatrix());
  41224. // Draw order
  41225. engine.draw(true, 0, this._indicesCount);
  41226. this._lineShader.unbind();
  41227. engine.setDepthWrite(true);
  41228. };
  41229. return EdgesRenderer;
  41230. })();
  41231. BABYLON.EdgesRenderer = EdgesRenderer;
  41232. })(BABYLON || (BABYLON = {}));
  41233. var BABYLON;
  41234. (function (BABYLON) {
  41235. (function (TonemappingOperator) {
  41236. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  41237. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  41238. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  41239. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  41240. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  41241. var TonemappingOperator = BABYLON.TonemappingOperator;
  41242. ;
  41243. var TonemapPostProcess = (function (_super) {
  41244. __extends(TonemapPostProcess, _super);
  41245. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  41246. var _this = this;
  41247. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  41248. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41249. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  41250. this._operator = _operator;
  41251. this.exposureAdjustment = exposureAdjustment;
  41252. var defines = "#define ";
  41253. if (this._operator === TonemappingOperator.Hable)
  41254. defines += "HABLE_TONEMAPPING";
  41255. else if (this._operator === TonemappingOperator.Reinhard)
  41256. defines += "REINHARD_TONEMAPPING";
  41257. else if (this._operator === TonemappingOperator.HejiDawson)
  41258. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  41259. else if (this._operator === TonemappingOperator.Photographic)
  41260. defines += "PHOTOGRAPHIC_TONEMAPPING";
  41261. //sadly a second call to create the effect.
  41262. this.updateEffect(defines);
  41263. this.onApply = function (effect) {
  41264. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  41265. };
  41266. }
  41267. return TonemapPostProcess;
  41268. })(BABYLON.PostProcess);
  41269. BABYLON.TonemapPostProcess = TonemapPostProcess;
  41270. })(BABYLON || (BABYLON = {}));
  41271. var BABYLON;
  41272. (function (BABYLON) {
  41273. var ReflectionProbe = (function () {
  41274. function ReflectionProbe(name, size, scene, generateMipMaps) {
  41275. var _this = this;
  41276. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41277. this.name = name;
  41278. this._viewMatrix = BABYLON.Matrix.Identity();
  41279. this._target = BABYLON.Vector3.Zero();
  41280. this._add = BABYLON.Vector3.Zero();
  41281. this.position = BABYLON.Vector3.Zero();
  41282. this._scene = scene;
  41283. this._scene.reflectionProbes.push(this);
  41284. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  41285. this._renderTargetTexture.onBeforeRender = function (faceIndex) {
  41286. switch (faceIndex) {
  41287. case 0:
  41288. _this._add.copyFromFloats(1, 0, 0);
  41289. break;
  41290. case 1:
  41291. _this._add.copyFromFloats(-1, 0, 0);
  41292. break;
  41293. case 2:
  41294. _this._add.copyFromFloats(0, -1, 0);
  41295. break;
  41296. case 3:
  41297. _this._add.copyFromFloats(0, 1, 0);
  41298. break;
  41299. case 4:
  41300. _this._add.copyFromFloats(0, 0, 1);
  41301. break;
  41302. case 5:
  41303. _this._add.copyFromFloats(0, 0, -1);
  41304. break;
  41305. }
  41306. if (_this._attachedMesh) {
  41307. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  41308. }
  41309. _this.position.addToRef(_this._add, _this._target);
  41310. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  41311. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  41312. };
  41313. this._renderTargetTexture.onAfterUnbind = function () {
  41314. scene.updateTransformMatrix(true);
  41315. };
  41316. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  41317. }
  41318. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  41319. get: function () {
  41320. return this._renderTargetTexture.refreshRate;
  41321. },
  41322. set: function (value) {
  41323. this._renderTargetTexture.refreshRate = value;
  41324. },
  41325. enumerable: true,
  41326. configurable: true
  41327. });
  41328. ReflectionProbe.prototype.getScene = function () {
  41329. return this._scene;
  41330. };
  41331. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  41332. get: function () {
  41333. return this._renderTargetTexture;
  41334. },
  41335. enumerable: true,
  41336. configurable: true
  41337. });
  41338. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  41339. get: function () {
  41340. return this._renderTargetTexture.renderList;
  41341. },
  41342. enumerable: true,
  41343. configurable: true
  41344. });
  41345. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  41346. this._attachedMesh = mesh;
  41347. };
  41348. ReflectionProbe.prototype.dispose = function () {
  41349. var index = this._scene.reflectionProbes.indexOf(this);
  41350. if (index !== -1) {
  41351. // Remove from the scene if found
  41352. this._scene.reflectionProbes.splice(index, 1);
  41353. }
  41354. if (this._renderTargetTexture) {
  41355. this._renderTargetTexture.dispose();
  41356. this._renderTargetTexture = null;
  41357. }
  41358. };
  41359. return ReflectionProbe;
  41360. })();
  41361. BABYLON.ReflectionProbe = ReflectionProbe;
  41362. })(BABYLON || (BABYLON = {}));
  41363. var BABYLON;
  41364. (function (BABYLON) {
  41365. var SolidParticle = (function () {
  41366. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  41367. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  41368. this.position = BABYLON.Vector3.Zero(); // position
  41369. this.rotation = BABYLON.Vector3.Zero(); // rotation
  41370. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  41371. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  41372. this.velocity = BABYLON.Vector3.Zero(); // velocity
  41373. this.alive = true; // alive
  41374. this.idx = particleIndex;
  41375. this._pos = positionIndex;
  41376. this._model = model;
  41377. this.shapeId = shapeId;
  41378. this.idxInShape = idxInShape;
  41379. }
  41380. Object.defineProperty(SolidParticle.prototype, "scale", {
  41381. //legacy support, changed scale to scaling
  41382. get: function () {
  41383. return this.scaling;
  41384. },
  41385. set: function (scale) {
  41386. this.scaling = scale;
  41387. },
  41388. enumerable: true,
  41389. configurable: true
  41390. });
  41391. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  41392. //legacy support, changed quaternion to rotationQuaternion
  41393. get: function () {
  41394. return this.rotationQuaternion;
  41395. },
  41396. set: function (q) {
  41397. this.rotationQuaternion = q;
  41398. },
  41399. enumerable: true,
  41400. configurable: true
  41401. });
  41402. return SolidParticle;
  41403. })();
  41404. BABYLON.SolidParticle = SolidParticle;
  41405. var ModelShape = (function () {
  41406. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  41407. this.shapeID = id;
  41408. this._shape = shape;
  41409. this._shapeUV = shapeUV;
  41410. this._positionFunction = posFunction;
  41411. this._vertexFunction = vtxFunction;
  41412. }
  41413. return ModelShape;
  41414. })();
  41415. BABYLON.ModelShape = ModelShape;
  41416. })(BABYLON || (BABYLON = {}));
  41417. var BABYLON;
  41418. (function (BABYLON) {
  41419. /**
  41420. * Full documentation here : http://doc.babylonjs.com/tutorials/Solid_Particle_System
  41421. */
  41422. var SolidParticleSystem = (function () {
  41423. /**
  41424. * Creates a SPS (Solid Particle System) object.
  41425. * `name` (String) is the SPS name, this will be the underlying mesh name.
  41426. * `scene` (Scene) is the scene in which the SPS is added.
  41427. * `updatableè (default true) : if the SPS must be updatable or immutable.
  41428. * `isPickable` (default false) : if the solid particles must be pickable.
  41429. */
  41430. function SolidParticleSystem(name, scene, options) {
  41431. // public members
  41432. /**
  41433. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  41434. * Example : var p = SPS.particles[i];
  41435. */
  41436. this.particles = new Array();
  41437. /**
  41438. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  41439. */
  41440. this.nbParticles = 0;
  41441. /**
  41442. * If the particles must ever face the camera (default false). Useful for planar particles.
  41443. */
  41444. this.billboard = false;
  41445. /**
  41446. * This a counter ofr your own usage. It's not set by any SPS functions.
  41447. */
  41448. this.counter = 0;
  41449. /**
  41450. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  41451. * Please read : http://doc.babylonjs.com/tutorials/Solid_Particle_System#garbage-collector-concerns
  41452. */
  41453. this.vars = {};
  41454. this._positions = new Array();
  41455. this._indices = new Array();
  41456. this._normals = new Array();
  41457. this._colors = new Array();
  41458. this._uvs = new Array();
  41459. this._index = 0; // indices index
  41460. this._updatable = true;
  41461. this._pickable = false;
  41462. this._isVisibilityBoxLocked = false;
  41463. this._alwaysVisible = false;
  41464. this._shapeCounter = 0;
  41465. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  41466. this._color = new BABYLON.Color4(0, 0, 0, 0);
  41467. this._computeParticleColor = true;
  41468. this._computeParticleTexture = true;
  41469. this._computeParticleRotation = true;
  41470. this._computeParticleVertex = false;
  41471. this._computeBoundingBox = false;
  41472. this._cam_axisZ = BABYLON.Vector3.Zero();
  41473. this._cam_axisY = BABYLON.Vector3.Zero();
  41474. this._cam_axisX = BABYLON.Vector3.Zero();
  41475. this._axisX = BABYLON.Axis.X;
  41476. this._axisY = BABYLON.Axis.Y;
  41477. this._axisZ = BABYLON.Axis.Z;
  41478. this._fakeCamPos = BABYLON.Vector3.Zero();
  41479. this._rotMatrix = new BABYLON.Matrix();
  41480. this._invertMatrix = new BABYLON.Matrix();
  41481. this._rotated = BABYLON.Vector3.Zero();
  41482. this._quaternion = new BABYLON.Quaternion();
  41483. this._vertex = BABYLON.Vector3.Zero();
  41484. this._normal = BABYLON.Vector3.Zero();
  41485. this._yaw = 0.0;
  41486. this._pitch = 0.0;
  41487. this._roll = 0.0;
  41488. this._halfroll = 0.0;
  41489. this._halfpitch = 0.0;
  41490. this._halfyaw = 0.0;
  41491. this._sinRoll = 0.0;
  41492. this._cosRoll = 0.0;
  41493. this._sinPitch = 0.0;
  41494. this._cosPitch = 0.0;
  41495. this._sinYaw = 0.0;
  41496. this._cosYaw = 0.0;
  41497. this._w = 0.0;
  41498. this._minimum = BABYLON.Tmp.Vector3[0];
  41499. this._maximum = BABYLON.Tmp.Vector3[1];
  41500. this.name = name;
  41501. this._scene = scene;
  41502. this._camera = scene.activeCamera;
  41503. this._pickable = options ? options.isPickable : false;
  41504. if (options && options.updatable) {
  41505. this._updatable = options.updatable;
  41506. }
  41507. else {
  41508. this._updatable = true;
  41509. }
  41510. if (this._pickable) {
  41511. this.pickedParticles = [];
  41512. }
  41513. }
  41514. /**
  41515. * Builds the SPS underlying mesh. Returns a standard Mesh.
  41516. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  41517. */
  41518. SolidParticleSystem.prototype.buildMesh = function () {
  41519. if (this.nbParticles === 0) {
  41520. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  41521. this.addShape(triangle, 1);
  41522. triangle.dispose();
  41523. }
  41524. this._positions32 = new Float32Array(this._positions);
  41525. this._uvs32 = new Float32Array(this._uvs);
  41526. this._colors32 = new Float32Array(this._colors);
  41527. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  41528. this._normals32 = new Float32Array(this._normals);
  41529. this._fixedNormal32 = new Float32Array(this._normals);
  41530. var vertexData = new BABYLON.VertexData();
  41531. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  41532. vertexData.indices = this._indices;
  41533. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  41534. if (this._uvs32) {
  41535. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  41536. ;
  41537. }
  41538. if (this._colors32) {
  41539. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  41540. }
  41541. var mesh = new BABYLON.Mesh(this.name, this._scene);
  41542. vertexData.applyToMesh(mesh, this._updatable);
  41543. this.mesh = mesh;
  41544. this.mesh.isPickable = this._pickable;
  41545. // free memory
  41546. this._positions = null;
  41547. this._normals = null;
  41548. this._uvs = null;
  41549. this._colors = null;
  41550. if (!this._updatable) {
  41551. this.particles.length = 0;
  41552. }
  41553. return mesh;
  41554. };
  41555. /**
  41556. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  41557. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  41558. * Thus the particles generated from `digest()` have their property `position` set yet.
  41559. * `mesh` (`Mesh`) is the mesh to be digested
  41560. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  41561. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  41562. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  41563. */
  41564. SolidParticleSystem.prototype.digest = function (mesh, options) {
  41565. var size = (options && options.facetNb) || 1;
  41566. var number = (options && options.number);
  41567. var delta = (options && options.delta) || 0;
  41568. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41569. var meshInd = mesh.getIndices();
  41570. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41571. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41572. var f = 0; // facet counter
  41573. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  41574. // compute size from number
  41575. if (number) {
  41576. number = (number > totalFacets) ? totalFacets : number;
  41577. size = Math.round(totalFacets / number);
  41578. delta = 0;
  41579. }
  41580. else {
  41581. size = (size > totalFacets) ? totalFacets : size;
  41582. }
  41583. var facetPos = []; // submesh positions
  41584. var facetInd = []; // submesh indices
  41585. var facetUV = []; // submesh UV
  41586. var facetCol = []; // submesh colors
  41587. var barycenter = BABYLON.Tmp.Vector3[0];
  41588. var rand;
  41589. var sizeO = size;
  41590. while (f < totalFacets) {
  41591. size = sizeO + Math.floor((1 + delta) * Math.random());
  41592. if (f > totalFacets - size) {
  41593. size = totalFacets - f;
  41594. }
  41595. // reset temp arrays
  41596. facetPos.length = 0;
  41597. facetInd.length = 0;
  41598. facetUV.length = 0;
  41599. facetCol.length = 0;
  41600. // iterate over "size" facets
  41601. var fi = 0;
  41602. for (var j = f * 3; j < (f + size) * 3; j++) {
  41603. facetInd.push(fi);
  41604. var i = meshInd[j];
  41605. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  41606. if (meshUV) {
  41607. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  41608. }
  41609. if (meshCol) {
  41610. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  41611. }
  41612. fi++;
  41613. }
  41614. // create a model shape for each single particle
  41615. var idx = this.nbParticles;
  41616. var shape = this._posToShape(facetPos);
  41617. var shapeUV = this._uvsToShapeUV(facetUV);
  41618. // compute the barycenter of the shape
  41619. var v;
  41620. for (v = 0; v < shape.length; v++) {
  41621. barycenter.addInPlace(shape[v]);
  41622. }
  41623. barycenter.scaleInPlace(1 / shape.length);
  41624. // shift the shape from its barycenter to the origin
  41625. for (v = 0; v < shape.length; v++) {
  41626. shape[v].subtractInPlace(barycenter);
  41627. }
  41628. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  41629. // add the particle in the SPS
  41630. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  41631. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  41632. // initialize the particle position
  41633. this.particles[this.nbParticles].position.addInPlace(barycenter);
  41634. this._index += shape.length;
  41635. idx++;
  41636. this.nbParticles++;
  41637. this._shapeCounter++;
  41638. f += size;
  41639. }
  41640. return this;
  41641. };
  41642. //reset copy
  41643. SolidParticleSystem.prototype._resetCopy = function () {
  41644. this._copy.position.x = 0;
  41645. this._copy.position.y = 0;
  41646. this._copy.position.z = 0;
  41647. this._copy.rotation.x = 0;
  41648. this._copy.rotation.y = 0;
  41649. this._copy.rotation.z = 0;
  41650. this._copy.rotationQuaternion = null;
  41651. this._copy.scaling.x = 1;
  41652. this._copy.scaling.y = 1;
  41653. this._copy.scaling.z = 1;
  41654. this._copy.uvs.x = 0;
  41655. this._copy.uvs.y = 0;
  41656. this._copy.uvs.z = 1;
  41657. this._copy.uvs.w = 1;
  41658. this._copy.color = null;
  41659. };
  41660. // _meshBuilder : inserts the shape model in the global SPS mesh
  41661. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  41662. var i;
  41663. var u = 0;
  41664. var c = 0;
  41665. this._resetCopy();
  41666. if (options && options.positionFunction) {
  41667. options.positionFunction(this._copy, idx, idxInShape);
  41668. }
  41669. if (this._copy.rotationQuaternion) {
  41670. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  41671. }
  41672. else {
  41673. this._yaw = this._copy.rotation.y;
  41674. this._pitch = this._copy.rotation.x;
  41675. this._roll = this._copy.rotation.z;
  41676. this._quaternionRotationYPR();
  41677. }
  41678. this._quaternionToRotationMatrix();
  41679. for (i = 0; i < shape.length; i++) {
  41680. this._vertex.x = shape[i].x;
  41681. this._vertex.y = shape[i].y;
  41682. this._vertex.z = shape[i].z;
  41683. if (options && options.vertexFunction) {
  41684. options.vertexFunction(this._copy, this._vertex, i);
  41685. }
  41686. this._vertex.x *= this._copy.scaling.x;
  41687. this._vertex.y *= this._copy.scaling.y;
  41688. this._vertex.z *= this._copy.scaling.z;
  41689. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  41690. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  41691. if (meshUV) {
  41692. 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);
  41693. u += 2;
  41694. }
  41695. if (this._copy.color) {
  41696. this._color = this._copy.color;
  41697. }
  41698. else if (meshCol && meshCol[c]) {
  41699. this._color.r = meshCol[c];
  41700. this._color.g = meshCol[c + 1];
  41701. this._color.b = meshCol[c + 2];
  41702. this._color.a = meshCol[c + 3];
  41703. }
  41704. else {
  41705. this._color.r = 1;
  41706. this._color.g = 1;
  41707. this._color.b = 1;
  41708. this._color.a = 1;
  41709. }
  41710. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  41711. c += 4;
  41712. }
  41713. for (i = 0; i < meshInd.length; i++) {
  41714. indices.push(p + meshInd[i]);
  41715. }
  41716. if (this._pickable) {
  41717. var nbfaces = meshInd.length / 3;
  41718. for (i = 0; i < nbfaces; i++) {
  41719. this.pickedParticles.push({ idx: idx, faceId: i });
  41720. }
  41721. }
  41722. };
  41723. // returns a shape array from positions array
  41724. SolidParticleSystem.prototype._posToShape = function (positions) {
  41725. var shape = [];
  41726. for (var i = 0; i < positions.length; i += 3) {
  41727. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  41728. }
  41729. return shape;
  41730. };
  41731. // returns a shapeUV array from a Vector4 uvs
  41732. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  41733. var shapeUV = [];
  41734. if (uvs) {
  41735. for (var i = 0; i < uvs.length; i++)
  41736. shapeUV.push(uvs[i]);
  41737. }
  41738. return shapeUV;
  41739. };
  41740. // adds a new particle object in the particles array
  41741. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  41742. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  41743. };
  41744. /**
  41745. * Adds some particles to the SPS from the model shape. Returns the shape id.
  41746. * Please read the doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#create-an-immutable-sps
  41747. * `mesh` is any `Mesh` object that will be used as a model for the solid particles.
  41748. * `nb` (positive integer) the number of particles to be created from this model
  41749. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  41750. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  41751. */
  41752. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  41753. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41754. var meshInd = mesh.getIndices();
  41755. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41756. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41757. var shape = this._posToShape(meshPos);
  41758. var shapeUV = this._uvsToShapeUV(meshUV);
  41759. var posfunc = options ? options.positionFunction : null;
  41760. var vtxfunc = options ? options.vertexFunction : null;
  41761. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  41762. // particles
  41763. var idx = this.nbParticles;
  41764. for (var i = 0; i < nb; i++) {
  41765. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  41766. if (this._updatable) {
  41767. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  41768. }
  41769. this._index += shape.length;
  41770. idx++;
  41771. }
  41772. this.nbParticles += nb;
  41773. this._shapeCounter++;
  41774. return this._shapeCounter - 1;
  41775. };
  41776. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  41777. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  41778. this._resetCopy();
  41779. if (particle._model._positionFunction) {
  41780. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  41781. }
  41782. if (this._copy.rotationQuaternion) {
  41783. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  41784. }
  41785. else {
  41786. this._yaw = this._copy.rotation.y;
  41787. this._pitch = this._copy.rotation.x;
  41788. this._roll = this._copy.rotation.z;
  41789. this._quaternionRotationYPR();
  41790. }
  41791. this._quaternionToRotationMatrix();
  41792. this._shape = particle._model._shape;
  41793. for (var pt = 0; pt < this._shape.length; pt++) {
  41794. this._vertex.x = this._shape[pt].x;
  41795. this._vertex.y = this._shape[pt].y;
  41796. this._vertex.z = this._shape[pt].z;
  41797. if (particle._model._vertexFunction) {
  41798. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  41799. }
  41800. this._vertex.x *= this._copy.scaling.x;
  41801. this._vertex.y *= this._copy.scaling.y;
  41802. this._vertex.z *= this._copy.scaling.z;
  41803. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  41804. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  41805. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  41806. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  41807. }
  41808. particle.position.x = 0;
  41809. particle.position.y = 0;
  41810. particle.position.z = 0;
  41811. particle.rotation.x = 0;
  41812. particle.rotation.y = 0;
  41813. particle.rotation.z = 0;
  41814. particle.rotationQuaternion = null;
  41815. particle.scaling.x = 1;
  41816. particle.scaling.y = 1;
  41817. particle.scaling.z = 1;
  41818. };
  41819. /**
  41820. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  41821. */
  41822. SolidParticleSystem.prototype.rebuildMesh = function () {
  41823. for (var p = 0; p < this.particles.length; p++) {
  41824. this._rebuildParticle(this.particles[p]);
  41825. }
  41826. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  41827. };
  41828. /**
  41829. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  41830. * This method calls `updateParticle()` for each particle of the SPS.
  41831. * For an animated SPS, it is usually called within the render loop.
  41832. * @param start (default 0) the particle index in the particle array where to start to compute the particle property values
  41833. * @param end (default nbParticle - 1) the particle index in the particle array where to stop to compute the particle property values
  41834. * @param update (default true) if the mesh must be finally updated on this call after all the particle computations.
  41835. */
  41836. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  41837. if (start === void 0) { start = 0; }
  41838. if (end === void 0) { end = this.nbParticles - 1; }
  41839. if (update === void 0) { update = true; }
  41840. if (!this._updatable) {
  41841. return;
  41842. }
  41843. // custom beforeUpdate
  41844. this.beforeUpdateParticles(start, end, update);
  41845. this._cam_axisX.x = 1;
  41846. this._cam_axisX.y = 0;
  41847. this._cam_axisX.z = 0;
  41848. this._cam_axisY.x = 0;
  41849. this._cam_axisY.y = 1;
  41850. this._cam_axisY.z = 0;
  41851. this._cam_axisZ.x = 0;
  41852. this._cam_axisZ.y = 0;
  41853. this._cam_axisZ.z = 1;
  41854. // if the particles will always face the camera
  41855. if (this.billboard) {
  41856. // compute a fake camera position : un-rotate the camera position by the current mesh rotation
  41857. this._yaw = this.mesh.rotation.y;
  41858. this._pitch = this.mesh.rotation.x;
  41859. this._roll = this.mesh.rotation.z;
  41860. this._quaternionRotationYPR();
  41861. this._quaternionToRotationMatrix();
  41862. this._rotMatrix.invertToRef(this._invertMatrix);
  41863. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._fakeCamPos);
  41864. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the cam-mesh axis (_cam_axisZ)
  41865. (this._fakeCamPos).subtractToRef(this.mesh.position, this._cam_axisZ);
  41866. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  41867. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._cam_axisY, this._cam_axisX);
  41868. this._cam_axisY.normalize();
  41869. this._cam_axisX.normalize();
  41870. this._cam_axisZ.normalize();
  41871. }
  41872. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  41873. var idx = 0;
  41874. var index = 0;
  41875. var colidx = 0;
  41876. var colorIndex = 0;
  41877. var uvidx = 0;
  41878. var uvIndex = 0;
  41879. if (this._computeBoundingBox) {
  41880. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  41881. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  41882. }
  41883. // particle loop
  41884. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  41885. for (var p = start; p <= end; p++) {
  41886. this._particle = this.particles[p];
  41887. this._shape = this._particle._model._shape;
  41888. this._shapeUV = this._particle._model._shapeUV;
  41889. // call to custom user function to update the particle properties
  41890. this.updateParticle(this._particle);
  41891. // particle rotation matrix
  41892. if (this.billboard) {
  41893. this._particle.rotation.x = 0.0;
  41894. this._particle.rotation.y = 0.0;
  41895. }
  41896. if (this._computeParticleRotation) {
  41897. if (this._particle.rotationQuaternion) {
  41898. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  41899. }
  41900. else {
  41901. this._yaw = this._particle.rotation.y;
  41902. this._pitch = this._particle.rotation.x;
  41903. this._roll = this._particle.rotation.z;
  41904. this._quaternionRotationYPR();
  41905. }
  41906. this._quaternionToRotationMatrix();
  41907. }
  41908. for (var pt = 0; pt < this._shape.length; pt++) {
  41909. idx = index + pt * 3;
  41910. colidx = colorIndex + pt * 4;
  41911. uvidx = uvIndex + pt * 2;
  41912. this._vertex.x = this._shape[pt].x;
  41913. this._vertex.y = this._shape[pt].y;
  41914. this._vertex.z = this._shape[pt].z;
  41915. if (this._computeParticleVertex) {
  41916. this.updateParticleVertex(this._particle, this._vertex, pt);
  41917. }
  41918. // positions
  41919. this._vertex.x *= this._particle.scaling.x;
  41920. this._vertex.y *= this._particle.scaling.y;
  41921. this._vertex.z *= this._particle.scaling.z;
  41922. 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];
  41923. 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;
  41924. 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;
  41925. 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;
  41926. 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;
  41927. 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;
  41928. 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;
  41929. if (this._computeBoundingBox) {
  41930. if (this._positions32[idx] < this._minimum.x) {
  41931. this._minimum.x = this._positions32[idx];
  41932. }
  41933. if (this._positions32[idx] > this._maximum.x) {
  41934. this._maximum.x = this._positions32[idx];
  41935. }
  41936. if (this._positions32[idx + 1] < this._minimum.y) {
  41937. this._minimum.y = this._positions32[idx + 1];
  41938. }
  41939. if (this._positions32[idx + 1] > this._maximum.y) {
  41940. this._maximum.y = this._positions32[idx + 1];
  41941. }
  41942. if (this._positions32[idx + 2] < this._minimum.z) {
  41943. this._minimum.z = this._positions32[idx + 2];
  41944. }
  41945. if (this._positions32[idx + 2] > this._maximum.z) {
  41946. this._maximum.z = this._positions32[idx + 2];
  41947. }
  41948. }
  41949. // normals : if the particles can't be morphed then just rotate the normals
  41950. if (!this._computeParticleVertex && !this.billboard) {
  41951. this._normal.x = this._fixedNormal32[idx];
  41952. this._normal.y = this._fixedNormal32[idx + 1];
  41953. this._normal.z = this._fixedNormal32[idx + 2];
  41954. 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];
  41955. 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;
  41956. 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;
  41957. 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;
  41958. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  41959. 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;
  41960. 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;
  41961. }
  41962. if (this._computeParticleColor) {
  41963. this._colors32[colidx] = this._particle.color.r;
  41964. this._colors32[colidx + 1] = this._particle.color.g;
  41965. this._colors32[colidx + 2] = this._particle.color.b;
  41966. this._colors32[colidx + 3] = this._particle.color.a;
  41967. }
  41968. if (this._computeParticleTexture) {
  41969. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  41970. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  41971. }
  41972. }
  41973. index = idx + 3;
  41974. colorIndex = colidx + 4;
  41975. uvIndex = uvidx + 2;
  41976. }
  41977. if (update) {
  41978. if (this._computeParticleColor) {
  41979. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  41980. }
  41981. if (this._computeParticleTexture) {
  41982. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  41983. }
  41984. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  41985. if (!this.mesh.areNormalsFrozen) {
  41986. if (this._computeParticleVertex || this.billboard) {
  41987. // recompute the normals only if the particles can be morphed, update then the normal reference array
  41988. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  41989. for (var i = 0; i < this._normals32.length; i++) {
  41990. this._fixedNormal32[i] = this._normals32[i];
  41991. }
  41992. }
  41993. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  41994. }
  41995. }
  41996. if (this._computeBoundingBox) {
  41997. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  41998. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  41999. }
  42000. this.afterUpdateParticles(start, end, update);
  42001. };
  42002. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  42003. this._halfroll = this._roll * 0.5;
  42004. this._halfpitch = this._pitch * 0.5;
  42005. this._halfyaw = this._yaw * 0.5;
  42006. this._sinRoll = Math.sin(this._halfroll);
  42007. this._cosRoll = Math.cos(this._halfroll);
  42008. this._sinPitch = Math.sin(this._halfpitch);
  42009. this._cosPitch = Math.cos(this._halfpitch);
  42010. this._sinYaw = Math.sin(this._halfyaw);
  42011. this._cosYaw = Math.cos(this._halfyaw);
  42012. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  42013. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  42014. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  42015. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  42016. };
  42017. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  42018. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  42019. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  42020. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  42021. this._rotMatrix.m[3] = 0;
  42022. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  42023. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  42024. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  42025. this._rotMatrix.m[7] = 0;
  42026. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  42027. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  42028. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  42029. this._rotMatrix.m[11] = 0;
  42030. this._rotMatrix.m[12] = 0;
  42031. this._rotMatrix.m[13] = 0;
  42032. this._rotMatrix.m[14] = 0;
  42033. this._rotMatrix.m[15] = 1.0;
  42034. };
  42035. /**
  42036. * Disposes the SPS
  42037. */
  42038. SolidParticleSystem.prototype.dispose = function () {
  42039. this.mesh.dispose();
  42040. this.vars = null;
  42041. // drop references to internal big arrays for the GC
  42042. this._positions = null;
  42043. this._indices = null;
  42044. this._normals = null;
  42045. this._uvs = null;
  42046. this._colors = null;
  42047. this._positions32 = null;
  42048. this._normals32 = null;
  42049. this._fixedNormal32 = null;
  42050. this._uvs32 = null;
  42051. this._colors32 = null;
  42052. this.pickedParticles = null;
  42053. };
  42054. /**
  42055. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  42056. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  42057. */
  42058. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  42059. if (!this._isVisibilityBoxLocked) {
  42060. this.mesh.refreshBoundingInfo();
  42061. }
  42062. };
  42063. /**
  42064. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  42065. * @param size the size (float) of the visibility box
  42066. * note : this doesn't lock the SPS mesh bounding box.
  42067. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  42068. */
  42069. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  42070. var vis = size / 2;
  42071. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  42072. };
  42073. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  42074. // getter and setter
  42075. get: function () {
  42076. return this._alwaysVisible;
  42077. },
  42078. /**
  42079. * Sets the SPS as always visible or not
  42080. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  42081. */
  42082. set: function (val) {
  42083. this._alwaysVisible = val;
  42084. this.mesh.alwaysSelectAsActiveMesh = val;
  42085. },
  42086. enumerable: true,
  42087. configurable: true
  42088. });
  42089. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  42090. get: function () {
  42091. return this._isVisibilityBoxLocked;
  42092. },
  42093. /**
  42094. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  42095. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#sps-visibility
  42096. */
  42097. set: function (val) {
  42098. this._isVisibilityBoxLocked = val;
  42099. this.mesh.getBoundingInfo().isLocked = val;
  42100. },
  42101. enumerable: true,
  42102. configurable: true
  42103. });
  42104. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  42105. // getters
  42106. get: function () {
  42107. return this._computeParticleRotation;
  42108. },
  42109. // Optimizer setters
  42110. /**
  42111. * Tells to `setParticles()` to compute the particle rotations or not.
  42112. * Default value : true. The SPS is faster when it's set to false.
  42113. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  42114. */
  42115. set: function (val) {
  42116. this._computeParticleRotation = val;
  42117. },
  42118. enumerable: true,
  42119. configurable: true
  42120. });
  42121. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  42122. get: function () {
  42123. return this._computeParticleColor;
  42124. },
  42125. /**
  42126. * Tells to `setParticles()` to compute the particle colors or not.
  42127. * Default value : true. The SPS is faster when it's set to false.
  42128. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  42129. */
  42130. set: function (val) {
  42131. this._computeParticleColor = val;
  42132. },
  42133. enumerable: true,
  42134. configurable: true
  42135. });
  42136. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  42137. get: function () {
  42138. return this._computeParticleTexture;
  42139. },
  42140. /**
  42141. * Tells to `setParticles()` to compute the particle textures or not.
  42142. * Default value : true. The SPS is faster when it's set to false.
  42143. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  42144. */
  42145. set: function (val) {
  42146. this._computeParticleTexture = val;
  42147. },
  42148. enumerable: true,
  42149. configurable: true
  42150. });
  42151. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  42152. get: function () {
  42153. return this._computeParticleVertex;
  42154. },
  42155. /**
  42156. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  42157. * Default value : false. The SPS is faster when it's set to false.
  42158. * Note : the particle custom vertex positions aren't stored values.
  42159. */
  42160. set: function (val) {
  42161. this._computeParticleVertex = val;
  42162. },
  42163. enumerable: true,
  42164. configurable: true
  42165. });
  42166. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  42167. get: function () {
  42168. return this._computeBoundingBox;
  42169. },
  42170. /**
  42171. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  42172. */
  42173. set: function (val) {
  42174. this._computeBoundingBox = val;
  42175. },
  42176. enumerable: true,
  42177. configurable: true
  42178. });
  42179. // =======================================================================
  42180. // Particle behavior logic
  42181. // these following methods may be overwritten by the user to fit his needs
  42182. /**
  42183. * This function does nothing. It may be overwritten to set all the particle first values.
  42184. * The SPS doesn't call this function, you may have to call it by your own.
  42185. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  42186. */
  42187. SolidParticleSystem.prototype.initParticles = function () {
  42188. };
  42189. /**
  42190. * This function does nothing. It may be overwritten to recycle a particle.
  42191. * The SPS doesn't call this function, you may have to call it by your own.
  42192. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  42193. */
  42194. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  42195. return particle;
  42196. };
  42197. /**
  42198. * Updates a particle : this function should be overwritten by the user.
  42199. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  42200. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#particle-management
  42201. * ex : just set a particle position or velocity and recycle conditions
  42202. */
  42203. SolidParticleSystem.prototype.updateParticle = function (particle) {
  42204. return particle;
  42205. };
  42206. /**
  42207. * Updates a vertex of a particle : it can be overwritten by the user.
  42208. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  42209. * @param particle the current particle
  42210. * @param vertex the current index of the current particle
  42211. * @param pt the index of the current vertex in the particle shape
  42212. * doc : http://doc.babylonjs.com/tutorials/Solid_Particle_System#update-each-particle-shape
  42213. * ex : just set a vertex particle position
  42214. */
  42215. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  42216. return vertex;
  42217. };
  42218. /**
  42219. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  42220. * This does nothing and may be overwritten by the user.
  42221. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42222. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42223. * @param update the boolean update value actually passed to setParticles()
  42224. */
  42225. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  42226. };
  42227. /**
  42228. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  42229. * This will be passed three parameters.
  42230. * This does nothing and may be overwritten by the user.
  42231. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42232. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  42233. * @param update the boolean update value actually passed to setParticles()
  42234. */
  42235. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  42236. };
  42237. return SolidParticleSystem;
  42238. })();
  42239. BABYLON.SolidParticleSystem = SolidParticleSystem;
  42240. })(BABYLON || (BABYLON = {}));
  42241. var BABYLON;
  42242. (function (BABYLON) {
  42243. var Internals;
  42244. (function (Internals) {
  42245. var FileFaceOrientation = (function () {
  42246. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  42247. this.name = name;
  42248. this.worldAxisForNormal = worldAxisForNormal;
  42249. this.worldAxisForFileX = worldAxisForFileX;
  42250. this.worldAxisForFileY = worldAxisForFileY;
  42251. }
  42252. return FileFaceOrientation;
  42253. })();
  42254. ;
  42255. /**
  42256. * Helper class dealing with the extraction of spherical polynomial dataArray
  42257. * from a cube map.
  42258. */
  42259. var CubeMapToSphericalPolynomialTools = (function () {
  42260. function CubeMapToSphericalPolynomialTools() {
  42261. }
  42262. /**
  42263. * Converts a cubemap to the according Spherical Polynomial data.
  42264. * This extracts the first 3 orders only as they are the only one used in the lighting.
  42265. *
  42266. * @param cubeInfo The Cube map to extract the information from.
  42267. * @return The Spherical Polynomial data.
  42268. */
  42269. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  42270. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  42271. var totalSolidAngle = 0.0;
  42272. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  42273. var du = 2.0 / cubeInfo.size;
  42274. var dv = du;
  42275. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  42276. var minUV = du * 0.5 - 1.0;
  42277. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  42278. var fileFace = this.FileFaces[faceIndex];
  42279. var dataArray = cubeInfo[fileFace.name];
  42280. var v = minUV;
  42281. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  42282. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  42283. // Because SP is still linear, so summation is fine in that basis.
  42284. for (var y = 0; y < cubeInfo.size; y++) {
  42285. var u = minUV;
  42286. for (var x = 0; x < cubeInfo.size; x++) {
  42287. // World direction (not normalised)
  42288. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  42289. worldDirection.normalize();
  42290. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  42291. if (1) {
  42292. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  42293. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  42294. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  42295. var color = new BABYLON.Color3(r, g, b);
  42296. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  42297. }
  42298. else {
  42299. if (faceIndex == 0) {
  42300. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  42301. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  42302. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  42303. }
  42304. else if (faceIndex == 1) {
  42305. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  42306. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  42307. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  42308. }
  42309. else if (faceIndex == 2) {
  42310. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  42311. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  42312. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  42313. }
  42314. else if (faceIndex == 3) {
  42315. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  42316. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  42317. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  42318. }
  42319. else if (faceIndex == 4) {
  42320. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  42321. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  42322. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  42323. }
  42324. else if (faceIndex == 5) {
  42325. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  42326. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  42327. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  42328. }
  42329. 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]);
  42330. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  42331. }
  42332. totalSolidAngle += deltaSolidAngle;
  42333. u += du;
  42334. }
  42335. v += dv;
  42336. }
  42337. }
  42338. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  42339. var correction = correctSolidAngle / totalSolidAngle;
  42340. sphericalHarmonics.scale(correction);
  42341. // Additionally scale by pi -- audit needed
  42342. sphericalHarmonics.scale(1.0 / Math.PI);
  42343. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  42344. };
  42345. CubeMapToSphericalPolynomialTools.FileFaces = [
  42346. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  42347. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  42348. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  42349. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  42350. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  42351. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  42352. ];
  42353. return CubeMapToSphericalPolynomialTools;
  42354. })();
  42355. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  42356. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  42357. })(BABYLON || (BABYLON = {}));
  42358. var BABYLON;
  42359. (function (BABYLON) {
  42360. var Internals;
  42361. (function (Internals) {
  42362. /**
  42363. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  42364. */
  42365. var PanoramaToCubeMapTools = (function () {
  42366. function PanoramaToCubeMapTools() {
  42367. }
  42368. /**
  42369. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  42370. *
  42371. * @param float32Array The source data.
  42372. * @param inputWidth The width of the input panorama.
  42373. * @param inputhHeight The height of the input panorama.
  42374. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  42375. * @return The cubemap data
  42376. */
  42377. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  42378. if (!float32Array) {
  42379. throw "ConvertPanoramaToCubemap: input cannot be null";
  42380. }
  42381. if (float32Array.length != inputWidth * inputHeight * 3) {
  42382. throw "ConvertPanoramaToCubemap: input size is wrong";
  42383. }
  42384. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  42385. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  42386. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  42387. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  42388. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  42389. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  42390. return {
  42391. front: textureFront,
  42392. back: textureBack,
  42393. left: textureLeft,
  42394. right: textureRight,
  42395. up: textureUp,
  42396. down: textureDown,
  42397. size: size
  42398. };
  42399. };
  42400. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  42401. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  42402. var textureArray = new Float32Array(buffer);
  42403. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  42404. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  42405. var dy = 1 / texSize;
  42406. var fy = 0;
  42407. for (var y = 0; y < texSize; y++) {
  42408. var xv1 = faceData[0];
  42409. var xv2 = faceData[2];
  42410. for (var x = 0; x < texSize; x++) {
  42411. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  42412. v.normalize();
  42413. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  42414. // 3 channels per pixels
  42415. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  42416. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  42417. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  42418. xv1 = xv1.add(rotDX1);
  42419. xv2 = xv2.add(rotDX2);
  42420. }
  42421. fy += dy;
  42422. }
  42423. return textureArray;
  42424. };
  42425. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  42426. var theta = Math.atan2(vDir.z, vDir.x);
  42427. var phi = Math.acos(vDir.y);
  42428. while (theta < -Math.PI)
  42429. theta += 2 * Math.PI;
  42430. while (theta > Math.PI)
  42431. theta -= 2 * Math.PI;
  42432. var dx = theta / Math.PI;
  42433. var dy = phi / Math.PI;
  42434. // recenter.
  42435. dx = dx * 0.5 + 0.5;
  42436. var px = Math.round(dx * inputWidth);
  42437. if (px < 0)
  42438. px = 0;
  42439. else if (px >= inputWidth)
  42440. px = inputWidth - 1;
  42441. var py = Math.round(dy * inputHeight);
  42442. if (py < 0)
  42443. py = 0;
  42444. else if (py >= inputHeight)
  42445. py = inputHeight - 1;
  42446. var inputY = (inputHeight - py - 1);
  42447. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  42448. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  42449. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  42450. return {
  42451. r: r,
  42452. g: g,
  42453. b: b
  42454. };
  42455. };
  42456. PanoramaToCubeMapTools.FACE_FRONT = [
  42457. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  42458. new BABYLON.Vector3(1.0, -1.0, -1.0),
  42459. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  42460. new BABYLON.Vector3(1.0, 1.0, -1.0)
  42461. ];
  42462. PanoramaToCubeMapTools.FACE_BACK = [
  42463. new BABYLON.Vector3(1.0, -1.0, 1.0),
  42464. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  42465. new BABYLON.Vector3(1.0, 1.0, 1.0),
  42466. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  42467. ];
  42468. PanoramaToCubeMapTools.FACE_RIGHT = [
  42469. new BABYLON.Vector3(1.0, -1.0, -1.0),
  42470. new BABYLON.Vector3(1.0, -1.0, 1.0),
  42471. new BABYLON.Vector3(1.0, 1.0, -1.0),
  42472. new BABYLON.Vector3(1.0, 1.0, 1.0)
  42473. ];
  42474. PanoramaToCubeMapTools.FACE_LEFT = [
  42475. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  42476. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  42477. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  42478. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  42479. ];
  42480. PanoramaToCubeMapTools.FACE_DOWN = [
  42481. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  42482. new BABYLON.Vector3(1.0, 1.0, -1.0),
  42483. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  42484. new BABYLON.Vector3(1.0, 1.0, 1.0)
  42485. ];
  42486. PanoramaToCubeMapTools.FACE_UP = [
  42487. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  42488. new BABYLON.Vector3(1.0, -1.0, 1.0),
  42489. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  42490. new BABYLON.Vector3(1.0, -1.0, -1.0)
  42491. ];
  42492. return PanoramaToCubeMapTools;
  42493. })();
  42494. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  42495. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  42496. })(BABYLON || (BABYLON = {}));
  42497. var BABYLON;
  42498. (function (BABYLON) {
  42499. var Internals;
  42500. (function (Internals) {
  42501. ;
  42502. /**
  42503. * This groups tools to convert HDR texture to native colors array.
  42504. */
  42505. var HDRTools = (function () {
  42506. function HDRTools() {
  42507. }
  42508. HDRTools.Ldexp = function (mantissa, exponent) {
  42509. if (exponent > 1023) {
  42510. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  42511. }
  42512. if (exponent < -1074) {
  42513. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  42514. }
  42515. return mantissa * Math.pow(2, exponent);
  42516. };
  42517. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  42518. if (exponent > 0) {
  42519. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  42520. float32array[index + 0] = red * exponent;
  42521. float32array[index + 1] = green * exponent;
  42522. float32array[index + 2] = blue * exponent;
  42523. }
  42524. else {
  42525. float32array[index + 0] = 0;
  42526. float32array[index + 1] = 0;
  42527. float32array[index + 2] = 0;
  42528. }
  42529. };
  42530. HDRTools.readStringLine = function (uint8array, startIndex) {
  42531. var line = "";
  42532. var character = "";
  42533. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  42534. character = String.fromCharCode(uint8array[i]);
  42535. if (character == "\n") {
  42536. break;
  42537. }
  42538. line += character;
  42539. }
  42540. return line;
  42541. };
  42542. /**
  42543. * Reads header information from an RGBE texture stored in a native array.
  42544. * More information on this format are available here:
  42545. * https://en.wikipedia.org/wiki/RGBE_image_format
  42546. *
  42547. * @param uint8array The binary file stored in native array.
  42548. * @return The header information.
  42549. */
  42550. HDRTools.RGBE_ReadHeader = function (uint8array) {
  42551. var height = 0;
  42552. var width = 0;
  42553. var line = this.readStringLine(uint8array, 0);
  42554. if (line[0] != '#' || line[1] != '?') {
  42555. throw "Bad HDR Format.";
  42556. }
  42557. var endOfHeader = false;
  42558. var findFormat = false;
  42559. var lineIndex = 0;
  42560. do {
  42561. lineIndex += (line.length + 1);
  42562. line = this.readStringLine(uint8array, lineIndex);
  42563. if (line == "FORMAT=32-bit_rle_rgbe") {
  42564. findFormat = true;
  42565. }
  42566. else if (line.length == 0) {
  42567. endOfHeader = true;
  42568. }
  42569. } while (!endOfHeader);
  42570. if (!findFormat) {
  42571. throw "HDR Bad header format, unsupported FORMAT";
  42572. }
  42573. lineIndex += (line.length + 1);
  42574. line = this.readStringLine(uint8array, lineIndex);
  42575. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  42576. var match = sizeRegexp.exec(line);
  42577. // TODO. Support +Y and -X if needed.
  42578. if (match.length < 3) {
  42579. throw "HDR Bad header format, no size";
  42580. }
  42581. width = parseInt(match[2]);
  42582. height = parseInt(match[1]);
  42583. if (width < 8 || width > 0x7fff) {
  42584. throw "HDR Bad header format, unsupported size";
  42585. }
  42586. lineIndex += (line.length + 1);
  42587. return {
  42588. height: height,
  42589. width: width,
  42590. dataPosition: lineIndex
  42591. };
  42592. };
  42593. /**
  42594. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  42595. * This RGBE texture needs to store the information as a panorama.
  42596. *
  42597. * More information on this format are available here:
  42598. * https://en.wikipedia.org/wiki/RGBE_image_format
  42599. *
  42600. * @param buffer The binary file stored in an array buffer.
  42601. * @param size The expected size of the extracted cubemap.
  42602. * @return The Cube Map information.
  42603. */
  42604. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  42605. var uint8array = new Uint8Array(buffer);
  42606. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  42607. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  42608. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  42609. return cubeMapData;
  42610. };
  42611. /**
  42612. * Returns the pixels data extracted from an RGBE texture.
  42613. * This pixels will be stored left to right up to down in the R G B order in one array.
  42614. *
  42615. * More information on this format are available here:
  42616. * https://en.wikipedia.org/wiki/RGBE_image_format
  42617. *
  42618. * @param uint8array The binary file stored in an array buffer.
  42619. * @param hdrInfo The header information of the file.
  42620. * @return The pixels data in RGB right to left up to down order.
  42621. */
  42622. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  42623. // Keep for multi format supports.
  42624. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  42625. };
  42626. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  42627. var num_scanlines = hdrInfo.height;
  42628. var scanline_width = hdrInfo.width;
  42629. var a, b, c, d, count;
  42630. var dataIndex = hdrInfo.dataPosition;
  42631. var index = 0, endIndex = 0, i = 0;
  42632. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  42633. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  42634. // 3 channels of 4 bytes per pixel in float.
  42635. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  42636. var resultArray = new Float32Array(resultBuffer);
  42637. // read in each successive scanline
  42638. while (num_scanlines > 0) {
  42639. a = uint8array[dataIndex++];
  42640. b = uint8array[dataIndex++];
  42641. c = uint8array[dataIndex++];
  42642. d = uint8array[dataIndex++];
  42643. if (a != 2 || b != 2 || (c & 0x80)) {
  42644. // this file is not run length encoded
  42645. throw "HDR Bad header format, not RLE";
  42646. }
  42647. if (((c << 8) | d) != scanline_width) {
  42648. throw "HDR Bad header format, wrong scan line width";
  42649. }
  42650. index = 0;
  42651. // read each of the four channels for the scanline into the buffer
  42652. for (i = 0; i < 4; i++) {
  42653. endIndex = (i + 1) * scanline_width;
  42654. while (index < endIndex) {
  42655. a = uint8array[dataIndex++];
  42656. b = uint8array[dataIndex++];
  42657. if (a > 128) {
  42658. // a run of the same value
  42659. count = a - 128;
  42660. if ((count == 0) || (count > endIndex - index)) {
  42661. throw "HDR Bad Format, bad scanline data (run)";
  42662. }
  42663. while (count-- > 0) {
  42664. scanLineArray[index++] = b;
  42665. }
  42666. }
  42667. else {
  42668. // a non-run
  42669. count = a;
  42670. if ((count == 0) || (count > endIndex - index)) {
  42671. throw "HDR Bad Format, bad scanline data (non-run)";
  42672. }
  42673. scanLineArray[index++] = b;
  42674. if (--count > 0) {
  42675. for (var j = 0; j < count; j++) {
  42676. scanLineArray[index++] = uint8array[dataIndex++];
  42677. }
  42678. }
  42679. }
  42680. }
  42681. }
  42682. // now convert data from buffer into floats
  42683. for (i = 0; i < scanline_width; i++) {
  42684. a = scanLineArray[i];
  42685. b = scanLineArray[i + scanline_width];
  42686. c = scanLineArray[i + 2 * scanline_width];
  42687. d = scanLineArray[i + 3 * scanline_width];
  42688. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  42689. }
  42690. num_scanlines--;
  42691. }
  42692. return resultArray;
  42693. };
  42694. return HDRTools;
  42695. })();
  42696. Internals.HDRTools = HDRTools;
  42697. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  42698. })(BABYLON || (BABYLON = {}));
  42699. //_______________________________________________________________
  42700. // Extracted from CubeMapGen:
  42701. // https://code.google.com/archive/p/cubemapgen/
  42702. //
  42703. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  42704. //_______________________________________________________________
  42705. var BABYLON;
  42706. (function (BABYLON) {
  42707. var Internals;
  42708. (function (Internals) {
  42709. /**
  42710. * The bounding box information used during the conversion process.
  42711. */
  42712. var CMGBoundinBox = (function () {
  42713. function CMGBoundinBox() {
  42714. this.min = new BABYLON.Vector3(0, 0, 0);
  42715. this.max = new BABYLON.Vector3(0, 0, 0);
  42716. this.clear();
  42717. }
  42718. CMGBoundinBox.prototype.clear = function () {
  42719. this.min.x = CMGBoundinBox.MAX;
  42720. this.min.y = CMGBoundinBox.MAX;
  42721. this.min.z = CMGBoundinBox.MAX;
  42722. this.max.x = CMGBoundinBox.MIN;
  42723. this.max.y = CMGBoundinBox.MIN;
  42724. this.max.z = CMGBoundinBox.MIN;
  42725. };
  42726. CMGBoundinBox.prototype.augment = function (x, y, z) {
  42727. this.min.x = Math.min(this.min.x, x);
  42728. this.min.y = Math.min(this.min.y, y);
  42729. this.min.z = Math.min(this.min.z, z);
  42730. this.max.x = Math.max(this.max.x, x);
  42731. this.max.y = Math.max(this.max.y, y);
  42732. this.max.z = Math.max(this.max.z, z);
  42733. };
  42734. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  42735. this.min.x = Math.max(this.min.x, x);
  42736. this.min.y = Math.max(this.min.y, y);
  42737. this.min.z = Math.max(this.min.z, z);
  42738. };
  42739. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  42740. this.max.x = Math.min(this.max.x, x);
  42741. this.max.y = Math.min(this.max.y, y);
  42742. this.max.z = Math.min(this.max.z, z);
  42743. };
  42744. CMGBoundinBox.prototype.empty = function () {
  42745. if ((this.min.x > this.max.y) ||
  42746. (this.min.y > this.max.y) ||
  42747. (this.min.z > this.max.y)) {
  42748. return true;
  42749. }
  42750. else {
  42751. return false;
  42752. }
  42753. };
  42754. CMGBoundinBox.MAX = Number.MAX_VALUE;
  42755. CMGBoundinBox.MIN = Number.MIN_VALUE;
  42756. return CMGBoundinBox;
  42757. })();
  42758. /**
  42759. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  42760. * required by the glossinees of a material.
  42761. *
  42762. * This only supports the cosine drop power as well as Warp fixup generation method.
  42763. *
  42764. * This is using the process from CubeMapGen described here:
  42765. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  42766. */
  42767. var PMREMGenerator = (function () {
  42768. /**
  42769. * Constructor of the generator.
  42770. *
  42771. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  42772. * @param inputSize The size of the cubemap faces
  42773. * @param outputSize The size of the output cubemap faces
  42774. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  42775. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  42776. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  42777. * @param specularPower The max specular level of the desired cubemap
  42778. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  42779. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  42780. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  42781. */
  42782. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  42783. this.input = input;
  42784. this.inputSize = inputSize;
  42785. this.outputSize = outputSize;
  42786. this.maxNumMipLevels = maxNumMipLevels;
  42787. this.numChannels = numChannels;
  42788. this.isFloat = isFloat;
  42789. this.specularPower = specularPower;
  42790. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  42791. this.excludeBase = excludeBase;
  42792. this.fixup = fixup;
  42793. this._outputSurface = [];
  42794. this._numMipLevels = 0;
  42795. }
  42796. /**
  42797. * Launches the filter process and return the result.
  42798. *
  42799. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  42800. */
  42801. PMREMGenerator.prototype.filterCubeMap = function () {
  42802. // Init cubemap processor
  42803. this.init();
  42804. // Filters the cubemap
  42805. this.filterCubeMapMipChain();
  42806. // Returns the filtered mips.
  42807. return this._outputSurface;
  42808. };
  42809. PMREMGenerator.prototype.init = function () {
  42810. var i;
  42811. var j;
  42812. var mipLevelSize;
  42813. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  42814. if (this.maxNumMipLevels == 0) {
  42815. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  42816. }
  42817. //first miplevel size
  42818. mipLevelSize = this.outputSize;
  42819. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  42820. for (j = 0; j < this.maxNumMipLevels; j++) {
  42821. this._outputSurface.length++;
  42822. this._outputSurface[j] = [];
  42823. //Iterate over faces for output images
  42824. for (i = 0; i < 6; i++) {
  42825. this._outputSurface[j].length++;
  42826. // Initializes a new array for the output.
  42827. if (this.isFloat) {
  42828. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  42829. }
  42830. else {
  42831. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  42832. }
  42833. }
  42834. //next mip level is half size
  42835. mipLevelSize >>= 1;
  42836. this._numMipLevels++;
  42837. //terminate if mip chain becomes too small
  42838. if (mipLevelSize == 0) {
  42839. this.maxNumMipLevels = j;
  42840. return;
  42841. }
  42842. }
  42843. };
  42844. //--------------------------------------------------------------------------------------
  42845. //Cube map filtering and mip chain generation.
  42846. // the cube map filtereing is specified using a number of parameters:
  42847. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  42848. // indicates the region of the hemisphere to filter over for each tap.
  42849. //
  42850. // Note that the top mip level is also a filtered version of the original input images
  42851. // as well in order to create mip chains for diffuse environment illumination.
  42852. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  42853. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  42854. //
  42855. // Then the mip angle used to genreate the next level of the mip chain from the first level
  42856. // is a_InitialMipAngle
  42857. //
  42858. // The angle for the subsequent levels of the mip chain are specified by their parents
  42859. // filtering angle and a per-level scale and bias
  42860. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  42861. //
  42862. //--------------------------------------------------------------------------------------
  42863. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  42864. // First, take count of the lighting model to modify SpecularPower
  42865. // 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;
  42866. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  42867. //Cone angle start (for generating subsequent mip levels)
  42868. var currentSpecularPower = this.specularPower;
  42869. //Build filter lookup tables based on the source miplevel size
  42870. this.precomputeFilterLookupTables(this.inputSize);
  42871. // Note that we need to filter the first level before generating mipmap
  42872. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  42873. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  42874. // TODO : Write a function to copy and scale the base mipmap in output
  42875. // I am just lazy here and just put a high specular power value, and do some if.
  42876. if (this.excludeBase && (levelIndex == 0)) {
  42877. // 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).
  42878. currentSpecularPower = 100000.0;
  42879. }
  42880. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  42881. var srcCubeImage = this.input;
  42882. var dstCubeImage = this._outputSurface[levelIndex];
  42883. var dstSize = this.outputSize >> levelIndex;
  42884. // Compute required angle.
  42885. var angle = this.getBaseFilterAngle(currentSpecularPower);
  42886. // filter cube surfaces
  42887. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  42888. // fix seams
  42889. if (this.fixup) {
  42890. this.fixupCubeEdges(dstCubeImage, dstSize);
  42891. }
  42892. // Decrease the specular power to generate the mipmap chain
  42893. // TODO : Use another method for Exclude (see first comment at start of the function
  42894. if (this.excludeBase && (levelIndex == 0)) {
  42895. currentSpecularPower = this.specularPower;
  42896. }
  42897. currentSpecularPower *= this.cosinePowerDropPerMip;
  42898. }
  42899. };
  42900. //--------------------------------------------------------------------------------------
  42901. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  42902. // It allow to optimize the texel to access base on the specular power.
  42903. //--------------------------------------------------------------------------------------
  42904. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  42905. // We want to find the alpha such that:
  42906. // cos(alpha)^cosinePower = epsilon
  42907. // That's: acos(epsilon^(1/cosinePower))
  42908. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  42909. var angle = 180.0;
  42910. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  42911. angle *= 180.0 / Math.PI; // Convert to degree
  42912. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  42913. return angle;
  42914. };
  42915. //--------------------------------------------------------------------------------------
  42916. //Builds the following lookup tables prior to filtering:
  42917. // -normalizer cube map
  42918. // -tap weight lookup table
  42919. //
  42920. //--------------------------------------------------------------------------------------
  42921. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  42922. var srcTexelAngle;
  42923. var iCubeFace;
  42924. //clear pre-existing normalizer cube map
  42925. this._normCubeMap = [];
  42926. //Normalized vectors per cubeface and per-texel solid angle
  42927. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  42928. };
  42929. //--------------------------------------------------------------------------------------
  42930. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  42931. //
  42932. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  42933. //
  42934. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  42935. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  42936. // below
  42937. //--------------------------------------------------------------------------------------
  42938. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  42939. var iCubeFace;
  42940. var u;
  42941. var v;
  42942. //iterate over cube faces
  42943. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  42944. //First three channels for norm cube, and last channel for solid angle
  42945. this._normCubeMap.push(new Float32Array(size * size * 4));
  42946. //fast texture walk, build normalizer cube map
  42947. var facesData = this.input[iCubeFace];
  42948. for (v = 0; v < size; v++) {
  42949. for (u = 0; u < size; u++) {
  42950. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  42951. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  42952. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  42953. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  42954. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  42955. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  42956. }
  42957. }
  42958. }
  42959. };
  42960. //--------------------------------------------------------------------------------------
  42961. // Convert cubemap face texel coordinates and face idx to 3D vector
  42962. // note the U and V coords are integer coords and range from 0 to size-1
  42963. // this routine can be used to generate a normalizer cube map
  42964. //--------------------------------------------------------------------------------------
  42965. // SL BEGIN
  42966. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  42967. var nvcU;
  42968. var nvcV;
  42969. var tempVec;
  42970. // Change from original AMD code
  42971. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  42972. // + 0.5f is for texel center addressing
  42973. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  42974. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  42975. // warp fixup
  42976. if (fixup && size > 1) {
  42977. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  42978. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  42979. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  42980. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  42981. }
  42982. // Get current vector
  42983. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  42984. // U contribution
  42985. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  42986. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  42987. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  42988. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  42989. // V contribution and Sum
  42990. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  42991. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  42992. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  42993. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  42994. //add face axis
  42995. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  42996. PMREMGenerator._vectorTemp.x += faceAxis[0];
  42997. PMREMGenerator._vectorTemp.y += faceAxis[1];
  42998. PMREMGenerator._vectorTemp.z += faceAxis[2];
  42999. //normalize vector
  43000. PMREMGenerator._vectorTemp.normalize();
  43001. return PMREMGenerator._vectorTemp;
  43002. };
  43003. //--------------------------------------------------------------------------------------
  43004. // Convert 3D vector to cubemap face texel coordinates and face idx
  43005. // note the U and V coords are integer coords and range from 0 to size-1
  43006. // this routine can be used to generate a normalizer cube map
  43007. //
  43008. // returns face IDX and texel coords
  43009. //--------------------------------------------------------------------------------------
  43010. // SL BEGIN
  43011. /*
  43012. Mapping Texture Coordinates to Cube Map Faces
  43013. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  43014. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  43015. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  43016. map arrangement in Pixar's RenderMan package.
  43017. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  43018. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  43019. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  43020. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  43021. the major axis direction). The target column in the table below explains how the major axis direction
  43022. maps to the 2D image of a particular cube map target.
  43023. major axis
  43024. direction target sc tc ma
  43025. ---------- --------------------------------- --- --- ---
  43026. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  43027. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  43028. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  43029. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  43030. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  43031. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  43032. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  43033. an updated (s,t) is calculated as follows
  43034. s = ( sc/|ma| + 1 ) / 2
  43035. t = ( tc/|ma| + 1 ) / 2
  43036. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  43037. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  43038. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  43039. */
  43040. // Note this method return U and V in range from 0 to size-1
  43041. // SL END
  43042. // Store the information in vector3 for convenience (faceindex, u, v)
  43043. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  43044. var maxCoord;
  43045. var faceIdx;
  43046. //absolute value 3
  43047. var absX = Math.abs(x);
  43048. var absY = Math.abs(y);
  43049. var absZ = Math.abs(z);
  43050. if (absX >= absY && absX >= absZ) {
  43051. maxCoord = absX;
  43052. if (x >= 0) {
  43053. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  43054. }
  43055. else {
  43056. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  43057. }
  43058. }
  43059. else if (absY >= absX && absY >= absZ) {
  43060. maxCoord = absY;
  43061. if (y >= 0) {
  43062. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  43063. }
  43064. else {
  43065. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  43066. }
  43067. }
  43068. else {
  43069. maxCoord = absZ;
  43070. if (z >= 0) {
  43071. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  43072. }
  43073. else {
  43074. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  43075. }
  43076. }
  43077. //divide through by max coord so face vector lies on cube face
  43078. var scale = 1 / maxCoord;
  43079. x *= scale;
  43080. y *= scale;
  43081. z *= scale;
  43082. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  43083. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  43084. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  43085. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  43086. // Modify original AMD code to return value from 0 to Size - 1
  43087. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  43088. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  43089. PMREMGenerator._vectorTemp.x = faceIdx;
  43090. PMREMGenerator._vectorTemp.y = u;
  43091. PMREMGenerator._vectorTemp.z = v;
  43092. return PMREMGenerator._vectorTemp;
  43093. };
  43094. //--------------------------------------------------------------------------------------
  43095. //Original code from Ignacio CastaÒo
  43096. // This formula is from Manne ÷hrstrˆm's thesis.
  43097. // Take two coordiantes in the range [-1, 1] that define a portion of a
  43098. // cube face and return the area of the projection of that portion on the
  43099. // surface of the sphere.
  43100. //--------------------------------------------------------------------------------------
  43101. PMREMGenerator.prototype.areaElement = function (x, y) {
  43102. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  43103. };
  43104. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  43105. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  43106. // (+ 0.5f is for texel center addressing)
  43107. u = (2.0 * (u + 0.5) / size) - 1.0;
  43108. v = (2.0 * (v + 0.5) / size) - 1.0;
  43109. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  43110. var invResolution = 1.0 / size;
  43111. // U and V are the -1..1 texture coordinate on the current face.
  43112. // Get projected area for this texel
  43113. var x0 = u - invResolution;
  43114. var y0 = v - invResolution;
  43115. var x1 = u + invResolution;
  43116. var y1 = v + invResolution;
  43117. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  43118. return solidAngle;
  43119. };
  43120. //--------------------------------------------------------------------------------------
  43121. //The key to the speed of these filtering routines is to quickly define a per-face
  43122. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  43123. // Later these pixels are selectively processed based on their dot products to see if
  43124. // they reside within the filtering cone.
  43125. //
  43126. //This is done by computing the smallest per-texel angle to get a conservative estimate
  43127. // of the number of texels needed to be covered in width and height order to filter the
  43128. // region. the bounding box for the center taps face is defined first, and if the
  43129. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  43130. // defined next
  43131. //--------------------------------------------------------------------------------------
  43132. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  43133. // note that pixels within these regions may be rejected
  43134. // based on the anlge
  43135. var iCubeFace;
  43136. var u;
  43137. var v;
  43138. // bounding box per face to specify region to process
  43139. var filterExtents = [];
  43140. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  43141. filterExtents.push(new CMGBoundinBox());
  43142. }
  43143. // min angle a src texel can cover (in degrees)
  43144. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  43145. // angle about center tap to define filter cone
  43146. // filter angle is 1/2 the cone angle
  43147. var filterAngle = filterConeAngle / 2.0;
  43148. //ensure filter angle is larger than a texel
  43149. if (filterAngle < srcTexelAngle) {
  43150. filterAngle = srcTexelAngle;
  43151. }
  43152. //ensure filter cone is always smaller than the hemisphere
  43153. if (filterAngle > 90.0) {
  43154. filterAngle = 90.0;
  43155. }
  43156. // the maximum number of texels in 1D the filter cone angle will cover
  43157. // used to determine bounding box size for filter extents
  43158. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  43159. // ensure conservative region always covers at least one texel
  43160. if (filterSize < 1) {
  43161. filterSize = 1;
  43162. }
  43163. // dotProdThresh threshold based on cone angle to determine whether or not taps
  43164. // reside within the cone angle
  43165. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  43166. // process required faces
  43167. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  43168. //iterate over dst cube map face texel
  43169. for (v = 0; v < dstSize; v++) {
  43170. for (u = 0; u < dstSize; u++) {
  43171. //get center tap direction
  43172. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  43173. //clear old per-face filter extents
  43174. this.clearFilterExtents(filterExtents);
  43175. //define per-face filter extents
  43176. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  43177. //perform filtering of src faces using filter extents
  43178. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  43179. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  43180. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  43181. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  43182. }
  43183. }
  43184. }
  43185. };
  43186. //--------------------------------------------------------------------------------------
  43187. //Clear filter extents for the 6 cube map faces
  43188. //--------------------------------------------------------------------------------------
  43189. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  43190. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  43191. filterExtents[iCubeFaces].clear();
  43192. }
  43193. };
  43194. //--------------------------------------------------------------------------------------
  43195. //Define per-face bounding box filter extents
  43196. //
  43197. // These define conservative texel regions in each of the faces the filter can possibly
  43198. // process. When the pixels in the regions are actually processed, the dot product
  43199. // between the tap vector and the center tap vector is used to determine the weight of
  43200. // the tap and whether or not the tap is within the cone.
  43201. //
  43202. //--------------------------------------------------------------------------------------
  43203. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  43204. //neighboring face and bleed over amount, and width of BBOX for
  43205. // left, right, top, and bottom edges of this face
  43206. var bleedOverAmount = [0, 0, 0, 0];
  43207. var bleedOverBBoxMin = [0, 0, 0, 0];
  43208. var bleedOverBBoxMax = [0, 0, 0, 0];
  43209. var neighborFace;
  43210. var neighborEdge;
  43211. var oppositeFaceIdx;
  43212. //get face idx, and u, v info from center tap dir
  43213. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  43214. var faceIdx = result.x;
  43215. var u = result.y;
  43216. var v = result.z;
  43217. //define bbox size within face
  43218. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  43219. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  43220. filterExtents[faceIdx].clampMin(0, 0, 0);
  43221. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  43222. //u and v extent in face corresponding to center tap
  43223. var minU = filterExtents[faceIdx].min.x;
  43224. var minV = filterExtents[faceIdx].min.y;
  43225. var maxU = filterExtents[faceIdx].max.x;
  43226. var maxV = filterExtents[faceIdx].max.y;
  43227. //bleed over amounts for face across u=0 edge (left)
  43228. bleedOverAmount[0] = (bboxSize - u);
  43229. bleedOverBBoxMin[0] = minV;
  43230. bleedOverBBoxMax[0] = maxV;
  43231. //bleed over amounts for face across u=1 edge (right)
  43232. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  43233. bleedOverBBoxMin[1] = minV;
  43234. bleedOverBBoxMax[1] = maxV;
  43235. //bleed over to face across v=0 edge (up)
  43236. bleedOverAmount[2] = (bboxSize - v);
  43237. bleedOverBBoxMin[2] = minU;
  43238. bleedOverBBoxMax[2] = maxU;
  43239. //bleed over to face across v=1 edge (down)
  43240. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  43241. bleedOverBBoxMin[3] = minU;
  43242. bleedOverBBoxMax[3] = maxU;
  43243. //compute bleed over regions in neighboring faces
  43244. for (var i = 0; i < 4; i++) {
  43245. if (bleedOverAmount[i] > 0) {
  43246. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  43247. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  43248. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  43249. // be flipped: the cases are
  43250. // if a left edge mates with a left or bottom edge on the neighbor
  43251. // if a top edge mates with a top or right edge on the neighbor
  43252. // if a right edge mates with a right or top edge on the neighbor
  43253. // if a bottom edge mates with a bottom or left edge on the neighbor
  43254. //Seeing as the edges are enumerated as follows
  43255. // left =0
  43256. // right =1
  43257. // top =2
  43258. // bottom =3
  43259. //
  43260. // so if the edge enums are the same, or the sum of the enums == 3,
  43261. // the bbox needs to be flipped
  43262. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  43263. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  43264. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  43265. }
  43266. //The way the bounding box is extended onto the neighboring face
  43267. // depends on which edge of neighboring face abuts with this one
  43268. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  43269. case PMREMGenerator.CP_EDGE_LEFT:
  43270. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  43271. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  43272. break;
  43273. case PMREMGenerator.CP_EDGE_RIGHT:
  43274. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  43275. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  43276. break;
  43277. case PMREMGenerator.CP_EDGE_TOP:
  43278. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  43279. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  43280. break;
  43281. case PMREMGenerator.CP_EDGE_BOTTOM:
  43282. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  43283. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  43284. break;
  43285. }
  43286. //clamp filter extents in non-center tap faces to remain within surface
  43287. filterExtents[neighborFace].clampMin(0, 0, 0);
  43288. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  43289. }
  43290. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  43291. // from the center tap face, then process the opposite face entirely for now.
  43292. //Note that the cases in which this happens, what usually happens is that
  43293. // more than one edge bleeds onto the opposite face, and the bounding box
  43294. // encompasses the entire cube map face.
  43295. if (bleedOverAmount[i] > srcSize) {
  43296. //determine opposite face
  43297. switch (faceIdx) {
  43298. case PMREMGenerator.CP_FACE_X_POS:
  43299. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  43300. break;
  43301. case PMREMGenerator.CP_FACE_X_NEG:
  43302. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  43303. break;
  43304. case PMREMGenerator.CP_FACE_Y_POS:
  43305. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  43306. break;
  43307. case PMREMGenerator.CP_FACE_Y_NEG:
  43308. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  43309. break;
  43310. case PMREMGenerator.CP_FACE_Z_POS:
  43311. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  43312. break;
  43313. case PMREMGenerator.CP_FACE_Z_NEG:
  43314. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  43315. break;
  43316. default:
  43317. break;
  43318. }
  43319. //just encompass entire face for now
  43320. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  43321. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  43322. }
  43323. }
  43324. };
  43325. //--------------------------------------------------------------------------------------
  43326. //ProcessFilterExtents
  43327. // Process bounding box in each cube face
  43328. //
  43329. //--------------------------------------------------------------------------------------
  43330. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  43331. //accumulators are 64-bit floats in order to have the precision needed
  43332. // over a summation of a large number of pixels
  43333. var dstAccum = [0, 0, 0, 0];
  43334. var weightAccum = 0;
  43335. var k = 0;
  43336. var nSrcChannels = this.numChannels;
  43337. // norm cube map and srcCubeMap have same face width
  43338. var faceWidth = srcSize;
  43339. //amount to add to pointer to move to next scanline in images
  43340. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  43341. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  43342. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  43343. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  43344. // iterate over cubefaces
  43345. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  43346. //if bbox is non empty
  43347. if (!filterExtents[iFaceIdx].empty()) {
  43348. var uStart = filterExtents[iFaceIdx].min.x;
  43349. var vStart = filterExtents[iFaceIdx].min.y;
  43350. var uEnd = filterExtents[iFaceIdx].max.x;
  43351. var vEnd = filterExtents[iFaceIdx].max.y;
  43352. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  43353. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  43354. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  43355. for (var v = vStart; v <= vEnd; v++) {
  43356. var normCubeRowWalk = 0;
  43357. var srcCubeRowWalk = 0;
  43358. for (var u = uStart; u <= uEnd; u++) {
  43359. //pointer to direction in cube map associated with texel
  43360. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  43361. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  43362. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  43363. //check dot product to see if texel is within cone
  43364. var tapDotProd = texelVectX * centerTapDir.x +
  43365. texelVectY * centerTapDir.y +
  43366. texelVectZ * centerTapDir.z;
  43367. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  43368. //solid angle stored in 4th channel of normalizer/solid angle cube map
  43369. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  43370. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  43371. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  43372. // so just adding one to specularpower do the trick.
  43373. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  43374. //iterate over channels
  43375. for (k = 0; k < nSrcChannels; k++) {
  43376. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  43377. srcCubeRowWalk++;
  43378. }
  43379. weightAccum += weight; //accumulate weight
  43380. }
  43381. else {
  43382. //step across source pixel
  43383. srcCubeRowWalk += nSrcChannels;
  43384. }
  43385. normCubeRowWalk += 4; // 4 channels per norm cube map.
  43386. }
  43387. startIndexNormCubeMap += normCubePitch;
  43388. startIndexSrcCubeMap += srcCubePitch;
  43389. }
  43390. }
  43391. }
  43392. //divide through by weights if weight is non zero
  43393. if (weightAccum != 0.0) {
  43394. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  43395. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  43396. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  43397. if (this.numChannels > 3) {
  43398. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  43399. }
  43400. }
  43401. else {
  43402. // otherwise sample nearest
  43403. // get face idx and u, v texel coordinate in face
  43404. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  43405. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  43406. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  43407. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  43408. if (this.numChannels > 3) {
  43409. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  43410. }
  43411. }
  43412. return PMREMGenerator._vectorTemp;
  43413. };
  43414. //--------------------------------------------------------------------------------------
  43415. // Fixup cube edges
  43416. //
  43417. // average texels on cube map faces across the edges
  43418. // WARP/BENT Method Only.
  43419. //--------------------------------------------------------------------------------------
  43420. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  43421. var k;
  43422. var j;
  43423. var i;
  43424. var iFace;
  43425. var iCorner = 0;
  43426. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  43427. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  43428. // note that if functionality to filter across the three texels for each corner, then
  43429. //indexed by corner and face idx. the array contains the face the start points belongs to.
  43430. var cornerPtr = [
  43431. [[], [], []],
  43432. [[], [], []],
  43433. [[], [], []],
  43434. [[], [], []],
  43435. [[], [], []],
  43436. [[], [], []],
  43437. [[], [], []],
  43438. [[], [], []]
  43439. ];
  43440. //if there is no fixup, or fixup width = 0, do nothing
  43441. if (cubeMapSize < 1) {
  43442. return;
  43443. }
  43444. //special case 1x1 cubemap, average face colors
  43445. if (cubeMapSize == 1) {
  43446. //iterate over channels
  43447. for (k = 0; k < this.numChannels; k++) {
  43448. var accum = 0.0;
  43449. //iterate over faces to accumulate face colors
  43450. for (iFace = 0; iFace < 6; iFace++) {
  43451. accum += cubeMap[iFace][k];
  43452. }
  43453. //compute average over 6 face colors
  43454. accum /= 6.0;
  43455. //iterate over faces to distribute face colors
  43456. for (iFace = 0; iFace < 6; iFace++) {
  43457. cubeMap[iFace][k] = accum;
  43458. }
  43459. }
  43460. return;
  43461. }
  43462. //iterate over faces to collect list of corner texel pointers
  43463. for (iFace = 0; iFace < 6; iFace++) {
  43464. //the 4 corner pointers for this face
  43465. faceCornerStartIndicies[0] = [iFace, 0];
  43466. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  43467. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  43468. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  43469. //iterate over face corners to collect cube corner pointers
  43470. for (iCorner = 0; iCorner < 4; iCorner++) {
  43471. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  43472. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  43473. cornerNumPtrs[corner]++;
  43474. }
  43475. }
  43476. //iterate over corners to average across corner tap values
  43477. for (iCorner = 0; iCorner < 8; iCorner++) {
  43478. for (k = 0; k < this.numChannels; k++) {
  43479. var cornerTapAccum = 0.0;
  43480. //iterate over corner texels and average results
  43481. for (i = 0; i < 3; i++) {
  43482. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  43483. }
  43484. //divide by 3 to compute average of corner tap values
  43485. cornerTapAccum *= (1.0 / 3.0);
  43486. //iterate over corner texels and average results
  43487. for (i = 0; i < 3; i++) {
  43488. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  43489. }
  43490. }
  43491. }
  43492. //iterate over the twelve edges of the cube to average across edges
  43493. for (i = 0; i < 12; i++) {
  43494. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  43495. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  43496. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  43497. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  43498. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  43499. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  43500. var edgeWalk = 0;
  43501. var neighborEdgeWalk = 0;
  43502. //Determine walking pointers based on edge type
  43503. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  43504. switch (edge) {
  43505. case PMREMGenerator.CP_EDGE_LEFT:
  43506. // no change to faceEdgeStartPtr
  43507. edgeWalk = this.numChannels * cubeMapSize;
  43508. break;
  43509. case PMREMGenerator.CP_EDGE_RIGHT:
  43510. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  43511. edgeWalk = this.numChannels * cubeMapSize;
  43512. break;
  43513. case PMREMGenerator.CP_EDGE_TOP:
  43514. // no change to faceEdgeStartPtr
  43515. edgeWalk = this.numChannels;
  43516. break;
  43517. case PMREMGenerator.CP_EDGE_BOTTOM:
  43518. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  43519. edgeWalk = this.numChannels;
  43520. break;
  43521. }
  43522. //For certain types of edge abutments, the neighbor edge walk needs to
  43523. // be flipped: the cases are
  43524. // if a left edge mates with a left or bottom edge on the neighbor
  43525. // if a top edge mates with a top or right edge on the neighbor
  43526. // if a right edge mates with a right or top edge on the neighbor
  43527. // if a bottom edge mates with a bottom or left edge on the neighbor
  43528. //Seeing as the edges are enumerated as follows
  43529. // left =0
  43530. // right =1
  43531. // top =2
  43532. // bottom =3
  43533. //
  43534. //If the edge enums are the same, or the sum of the enums == 3,
  43535. // the neighbor edge walk needs to be flipped
  43536. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  43537. switch (neighborEdge) {
  43538. case PMREMGenerator.CP_EDGE_LEFT:
  43539. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  43540. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  43541. break;
  43542. case PMREMGenerator.CP_EDGE_RIGHT:
  43543. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  43544. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  43545. break;
  43546. case PMREMGenerator.CP_EDGE_TOP:
  43547. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  43548. neighborEdgeWalk = -this.numChannels;
  43549. break;
  43550. case PMREMGenerator.CP_EDGE_BOTTOM:
  43551. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  43552. neighborEdgeWalk = -this.numChannels;
  43553. break;
  43554. }
  43555. }
  43556. else {
  43557. //swapped direction neighbor edge walk
  43558. switch (neighborEdge) {
  43559. case PMREMGenerator.CP_EDGE_LEFT:
  43560. //no change to neighborEdgeStartPtr for this case since it points
  43561. // to the upper left corner already
  43562. neighborEdgeWalk = this.numChannels * cubeMapSize;
  43563. break;
  43564. case PMREMGenerator.CP_EDGE_RIGHT:
  43565. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  43566. neighborEdgeWalk = this.numChannels * cubeMapSize;
  43567. break;
  43568. case PMREMGenerator.CP_EDGE_TOP:
  43569. //no change to neighborEdgeStartPtr for this case since it points
  43570. // to the upper left corner already
  43571. neighborEdgeWalk = this.numChannels;
  43572. break;
  43573. case PMREMGenerator.CP_EDGE_BOTTOM:
  43574. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  43575. neighborEdgeWalk = this.numChannels;
  43576. break;
  43577. }
  43578. }
  43579. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  43580. //nearby neighborhood
  43581. //step ahead one texel on edge
  43582. edgeStartIndex += edgeWalk;
  43583. neighborEdgeStartIndex += neighborEdgeWalk;
  43584. // note that this loop does not process the corner texels, since they have already been
  43585. // averaged across faces across earlier
  43586. for (j = 1; j < (cubeMapSize - 1); j++) {
  43587. //for each set of taps along edge, average them
  43588. // and rewrite the results into the edges
  43589. for (k = 0; k < this.numChannels; k++) {
  43590. var edgeTap = cubeMap[face][edgeStartIndex + k];
  43591. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  43592. //compute average of tap intensity values
  43593. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  43594. //propagate average of taps to edge taps
  43595. cubeMap[face][edgeStartIndex + k] = avgTap;
  43596. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  43597. }
  43598. edgeStartIndex += edgeWalk;
  43599. neighborEdgeStartIndex += neighborEdgeWalk;
  43600. }
  43601. }
  43602. };
  43603. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  43604. PMREMGenerator.CP_UDIR = 0;
  43605. PMREMGenerator.CP_VDIR = 1;
  43606. PMREMGenerator.CP_FACEAXIS = 2;
  43607. //used to index cube faces
  43608. PMREMGenerator.CP_FACE_X_POS = 0;
  43609. PMREMGenerator.CP_FACE_X_NEG = 1;
  43610. PMREMGenerator.CP_FACE_Y_POS = 2;
  43611. PMREMGenerator.CP_FACE_Y_NEG = 3;
  43612. PMREMGenerator.CP_FACE_Z_POS = 4;
  43613. PMREMGenerator.CP_FACE_Z_NEG = 5;
  43614. //used to index image edges
  43615. // NOTE.. the actual number corresponding to the edge is important
  43616. // do not change these, or the code will break
  43617. //
  43618. // CP_EDGE_LEFT is u = 0
  43619. // CP_EDGE_RIGHT is u = width-1
  43620. // CP_EDGE_TOP is v = 0
  43621. // CP_EDGE_BOTTOM is v = height-1
  43622. PMREMGenerator.CP_EDGE_LEFT = 0;
  43623. PMREMGenerator.CP_EDGE_RIGHT = 1;
  43624. PMREMGenerator.CP_EDGE_TOP = 2;
  43625. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  43626. //corners of CUBE map (P or N specifys if it corresponds to the
  43627. // positive or negative direction each of X, Y, and Z
  43628. PMREMGenerator.CP_CORNER_NNN = 0;
  43629. PMREMGenerator.CP_CORNER_NNP = 1;
  43630. PMREMGenerator.CP_CORNER_NPN = 2;
  43631. PMREMGenerator.CP_CORNER_NPP = 3;
  43632. PMREMGenerator.CP_CORNER_PNN = 4;
  43633. PMREMGenerator.CP_CORNER_PNP = 5;
  43634. PMREMGenerator.CP_CORNER_PPN = 6;
  43635. PMREMGenerator.CP_CORNER_PPP = 7;
  43636. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  43637. //3x2 matrices that map cube map indexing vectors in 3d
  43638. // (after face selection and divide through by the
  43639. // _ABSOLUTE VALUE_ of the max coord)
  43640. // into NVC space
  43641. //Note this currently assumes the D3D cube face ordering and orientation
  43642. PMREMGenerator._sgFace2DMapping = [
  43643. //XPOS face
  43644. [[0, 0, -1],
  43645. [0, -1, 0],
  43646. [1, 0, 0]],
  43647. //XNEG face
  43648. [[0, 0, 1],
  43649. [0, -1, 0],
  43650. [-1, 0, 0]],
  43651. //YPOS face
  43652. [[1, 0, 0],
  43653. [0, 0, 1],
  43654. [0, 1, 0]],
  43655. //YNEG face
  43656. [[1, 0, 0],
  43657. [0, 0, -1],
  43658. [0, -1, 0]],
  43659. //ZPOS face
  43660. [[1, 0, 0],
  43661. [0, -1, 0],
  43662. [0, 0, 1]],
  43663. //ZNEG face
  43664. [[-1, 0, 0],
  43665. [0, -1, 0],
  43666. [0, 0, -1]],
  43667. ];
  43668. //------------------------------------------------------------------------------
  43669. // D3D cube map face specification
  43670. // mapping from 3D x,y,z cube map lookup coordinates
  43671. // to 2D within face u,v coordinates
  43672. //
  43673. // --------------------> U direction
  43674. // | (within-face texture space)
  43675. // | _____
  43676. // | | |
  43677. // | | +Y |
  43678. // | _____|_____|_____ _____
  43679. // | | | | | |
  43680. // | | -X | +Z | +X | -Z |
  43681. // | |_____|_____|_____|_____|
  43682. // | | |
  43683. // | | -Y |
  43684. // | |_____|
  43685. // |
  43686. // v V direction
  43687. // (within-face texture space)
  43688. //------------------------------------------------------------------------------
  43689. //Information about neighbors and how texture coorrdinates change across faces
  43690. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  43691. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  43692. //Note this currently assumes the D3D cube face ordering and orientation
  43693. PMREMGenerator._sgCubeNgh = [
  43694. //XPOS face
  43695. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  43696. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  43697. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  43698. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  43699. //XNEG face
  43700. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  43701. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  43702. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  43703. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  43704. //YPOS face
  43705. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  43706. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  43707. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  43708. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  43709. //YNEG face
  43710. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  43711. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43712. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43713. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  43714. //ZPOS face
  43715. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  43716. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  43717. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43718. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  43719. //ZNEG face
  43720. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  43721. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  43722. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  43723. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  43724. ];
  43725. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  43726. // this table is used to average over the edges.
  43727. PMREMGenerator._sgCubeEdgeList = [
  43728. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  43729. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  43730. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  43731. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43732. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  43733. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  43734. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  43735. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  43736. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  43737. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  43738. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  43739. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  43740. ];
  43741. //Information about which of the 8 cube corners are correspond to the
  43742. // the 4 corners in each cube face
  43743. // the order is upper left, upper right, lower left, lower right
  43744. PMREMGenerator._sgCubeCornerList = [
  43745. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  43746. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  43747. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  43748. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  43749. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  43750. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  43751. ];
  43752. return PMREMGenerator;
  43753. })();
  43754. Internals.PMREMGenerator = PMREMGenerator;
  43755. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43756. })(BABYLON || (BABYLON = {}));
  43757. var BABYLON;
  43758. (function (BABYLON) {
  43759. /**
  43760. * This represents a texture coming from an HDR input.
  43761. *
  43762. * The only supported format is currently panorama picture stored in RGBE format.
  43763. * Example of such files can be found on HDRLib: http://hdrlib.com/
  43764. */
  43765. var HDRCubeTexture = (function (_super) {
  43766. __extends(HDRCubeTexture, _super);
  43767. /**
  43768. * Instantiates an HDRTexture from the following parameters.
  43769. *
  43770. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  43771. * @param scene The scene the texture will be used in
  43772. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  43773. * @param noMipmap Forces to not generate the mipmap if true
  43774. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  43775. * @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)
  43776. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  43777. */
  43778. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  43779. if (noMipmap === void 0) { noMipmap = false; }
  43780. if (generateHarmonics === void 0) { generateHarmonics = true; }
  43781. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  43782. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  43783. _super.call(this, scene);
  43784. this._useInGammaSpace = false;
  43785. this._generateHarmonics = true;
  43786. /**
  43787. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  43788. */
  43789. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  43790. /**
  43791. * The spherical polynomial data extracted from the texture.
  43792. */
  43793. this.sphericalPolynomial = null;
  43794. /**
  43795. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  43796. * This is usefull at run time to apply the good shader.
  43797. */
  43798. this.isPMREM = false;
  43799. this.name = url;
  43800. this.url = url;
  43801. this._noMipmap = noMipmap;
  43802. this.hasAlpha = false;
  43803. this._size = size;
  43804. this._useInGammaSpace = useInGammaSpace;
  43805. this._usePMREMGenerator = usePMREMGenerator && scene.getEngine().getCaps().textureLOD;
  43806. this.isPMREM = this._usePMREMGenerator;
  43807. if (!url) {
  43808. return;
  43809. }
  43810. this._texture = this._getFromCache(url, noMipmap);
  43811. if (!this._texture) {
  43812. if (!scene.useDelayedTextureLoading) {
  43813. this.loadTexture();
  43814. }
  43815. else {
  43816. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  43817. }
  43818. }
  43819. this.isCube = true;
  43820. this._textureMatrix = BABYLON.Matrix.Identity();
  43821. }
  43822. HDRCubeTexture.prototype.loadTexture = function () {
  43823. var _this = this;
  43824. var callback = function (buffer) {
  43825. // Extract the raw linear data.
  43826. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  43827. // Generate harmonics if needed.
  43828. if (_this._generateHarmonics) {
  43829. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  43830. }
  43831. var results = [];
  43832. var byteArray = null;
  43833. // Create uintarray fallback.
  43834. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  43835. // 3 channels of 1 bytes per pixel in bytes.
  43836. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  43837. byteArray = new Uint8Array(byteBuffer);
  43838. }
  43839. // Push each faces.
  43840. for (var j = 0; j < 6; j++) {
  43841. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  43842. // If special cases.
  43843. if (_this._useInGammaSpace || byteArray) {
  43844. for (var i = 0; i < _this._size * _this._size; i++) {
  43845. // Put in gamma space if requested.
  43846. if (_this._useInGammaSpace) {
  43847. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  43848. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  43849. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  43850. }
  43851. // Convert to int texture for fallback.
  43852. if (byteArray) {
  43853. // R
  43854. byteArray[(i * 3) + 0] = dataFace[(i * 3) + 0] * 255;
  43855. byteArray[(i * 3) + 0] = Math.min(255, byteArray[(i * 3) + 0]);
  43856. // G
  43857. byteArray[(i * 3) + 1] = dataFace[(i * 3) + 1] * 255;
  43858. byteArray[(i * 3) + 1] = Math.min(255, byteArray[(i * 3) + 1]);
  43859. // B
  43860. byteArray[(i * 3) + 2] = dataFace[(i * 3) + 2] * 255;
  43861. byteArray[(i * 3) + 2] = Math.min(255, byteArray[(i * 3) + 2]);
  43862. }
  43863. }
  43864. }
  43865. results.push(dataFace);
  43866. }
  43867. return results;
  43868. };
  43869. var mipmapGenerator = null;
  43870. if (!this._noMipmap && this._usePMREMGenerator) {
  43871. mipmapGenerator = function (data) {
  43872. // Custom setup of the generator matching with the PBR shader values.
  43873. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  43874. return generator.filterCubeMap();
  43875. };
  43876. }
  43877. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, BABYLON.Engine.TEXTURETYPE_FLOAT, this._noMipmap, callback, mipmapGenerator);
  43878. };
  43879. HDRCubeTexture.prototype.clone = function () {
  43880. var newTexture = new HDRCubeTexture(this.url, this.getScene(), this._size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  43881. // Base texture
  43882. newTexture.level = this.level;
  43883. newTexture.wrapU = this.wrapU;
  43884. newTexture.wrapV = this.wrapV;
  43885. newTexture.coordinatesIndex = this.coordinatesIndex;
  43886. newTexture.coordinatesMode = this.coordinatesMode;
  43887. return newTexture;
  43888. };
  43889. // Methods
  43890. HDRCubeTexture.prototype.delayLoad = function () {
  43891. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  43892. return;
  43893. }
  43894. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  43895. this._texture = this._getFromCache(this.url, this._noMipmap);
  43896. if (!this._texture) {
  43897. this.loadTexture();
  43898. }
  43899. };
  43900. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  43901. return this._textureMatrix;
  43902. };
  43903. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  43904. var texture = null;
  43905. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  43906. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  43907. texture.name = parsedTexture.name;
  43908. texture.hasAlpha = parsedTexture.hasAlpha;
  43909. texture.level = parsedTexture.level;
  43910. texture.coordinatesMode = parsedTexture.coordinatesMode;
  43911. }
  43912. return texture;
  43913. };
  43914. HDRCubeTexture.prototype.serialize = function () {
  43915. if (!this.name) {
  43916. return null;
  43917. }
  43918. var serializationObject = {};
  43919. serializationObject.name = this.name;
  43920. serializationObject.hasAlpha = this.hasAlpha;
  43921. serializationObject.isCube = true;
  43922. serializationObject.level = this.level;
  43923. serializationObject.size = this._size;
  43924. serializationObject.coordinatesMode = this.coordinatesMode;
  43925. serializationObject.useInGammaSpace = this._useInGammaSpace;
  43926. serializationObject.generateHarmonics = this._generateHarmonics;
  43927. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  43928. return serializationObject;
  43929. };
  43930. HDRCubeTexture._facesMapping = [
  43931. "right",
  43932. "up",
  43933. "front",
  43934. "left",
  43935. "down",
  43936. "back"
  43937. ];
  43938. return HDRCubeTexture;
  43939. })(BABYLON.BaseTexture);
  43940. BABYLON.HDRCubeTexture = HDRCubeTexture;
  43941. })(BABYLON || (BABYLON = {}));
  43942. var BABYLON;
  43943. (function (BABYLON) {
  43944. var Debug;
  43945. (function (Debug) {
  43946. /**
  43947. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  43948. */
  43949. var SkeletonViewer = (function () {
  43950. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  43951. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  43952. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  43953. this.skeleton = skeleton;
  43954. this.mesh = mesh;
  43955. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  43956. this.renderingGroupId = renderingGroupId;
  43957. this.color = BABYLON.Color3.White();
  43958. this._debugLines = [];
  43959. this._isEnabled = false;
  43960. this._scene = scene;
  43961. this.update();
  43962. this._renderFunction = this.update.bind(this);
  43963. }
  43964. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  43965. get: function () {
  43966. return this._isEnabled;
  43967. },
  43968. set: function (value) {
  43969. if (this._isEnabled === value) {
  43970. return;
  43971. }
  43972. this._isEnabled = value;
  43973. if (value) {
  43974. this._scene.registerBeforeRender(this._renderFunction);
  43975. }
  43976. else {
  43977. this._scene.unregisterBeforeRender(this._renderFunction);
  43978. }
  43979. },
  43980. enumerable: true,
  43981. configurable: true
  43982. });
  43983. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  43984. if (x === void 0) { x = 0; }
  43985. if (y === void 0) { y = 0; }
  43986. if (z === void 0) { z = 0; }
  43987. var tmat = BABYLON.Tmp.Matrix[0];
  43988. var parentBone = bone.getParent();
  43989. tmat.copyFrom(bone.getLocalMatrix());
  43990. if (x !== 0 || y !== 0 || z !== 0) {
  43991. var tmat2 = BABYLON.Tmp.Matrix[1];
  43992. BABYLON.Matrix.IdentityToRef(tmat2);
  43993. tmat2.m[12] = x;
  43994. tmat2.m[13] = y;
  43995. tmat2.m[14] = z;
  43996. tmat2.multiplyToRef(tmat, tmat);
  43997. }
  43998. if (parentBone) {
  43999. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  44000. }
  44001. tmat.multiplyToRef(meshMat, tmat);
  44002. position.x = tmat.m[12];
  44003. position.y = tmat.m[13];
  44004. position.z = tmat.m[14];
  44005. };
  44006. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  44007. var len = bones.length;
  44008. for (var i = 0; i < len; i++) {
  44009. var bone = bones[i];
  44010. var points = this._debugLines[i];
  44011. if (!points) {
  44012. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  44013. this._debugLines[i] = points;
  44014. }
  44015. this._getBonePosition(points[0], bone, meshMat);
  44016. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  44017. }
  44018. };
  44019. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  44020. var len = bones.length;
  44021. var boneNum = 0;
  44022. for (var i = len - 1; i >= 0; i--) {
  44023. var childBone = bones[i];
  44024. var parentBone = childBone.getParent();
  44025. if (!parentBone) {
  44026. continue;
  44027. }
  44028. var points = this._debugLines[boneNum];
  44029. if (!points) {
  44030. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  44031. this._debugLines[boneNum] = points;
  44032. }
  44033. this._getBonePosition(points[0], childBone, meshMat);
  44034. this._getBonePosition(points[1], parentBone, meshMat);
  44035. boneNum++;
  44036. }
  44037. };
  44038. SkeletonViewer.prototype.update = function () {
  44039. if (this.autoUpdateBonesMatrices) {
  44040. this._updateBoneMatrix(this.skeleton.bones[0]);
  44041. }
  44042. if (this.skeleton.bones[0].length === undefined) {
  44043. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  44044. }
  44045. else {
  44046. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  44047. }
  44048. if (!this._debugMesh) {
  44049. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  44050. this._debugMesh.renderingGroupId = this.renderingGroupId;
  44051. }
  44052. else {
  44053. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  44054. }
  44055. this._debugMesh.color = this.color;
  44056. };
  44057. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  44058. if (bone.getParent()) {
  44059. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  44060. }
  44061. var children = bone.children;
  44062. var len = children.length;
  44063. for (var i = 0; i < len; i++) {
  44064. this._updateBoneMatrix(children[i]);
  44065. }
  44066. };
  44067. SkeletonViewer.prototype.dispose = function () {
  44068. if (this._debugMesh) {
  44069. this.isEnabled = false;
  44070. this._debugMesh.dispose();
  44071. this._debugMesh = null;
  44072. }
  44073. };
  44074. return SkeletonViewer;
  44075. })();
  44076. Debug.SkeletonViewer = SkeletonViewer;
  44077. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  44078. })(BABYLON || (BABYLON = {}));
  44079. var BABYLON;
  44080. (function (BABYLON) {
  44081. var maxSimultaneousLights = 4;
  44082. var PBRMaterialDefines = (function (_super) {
  44083. __extends(PBRMaterialDefines, _super);
  44084. function PBRMaterialDefines() {
  44085. _super.call(this);
  44086. this.ALBEDO = false;
  44087. this.AMBIENT = false;
  44088. this.OPACITY = false;
  44089. this.OPACITYRGB = false;
  44090. this.REFLECTION = false;
  44091. this.EMISSIVE = false;
  44092. this.REFLECTIVITY = false;
  44093. this.BUMP = false;
  44094. this.PARALLAX = false;
  44095. this.PARALLAXOCCLUSION = false;
  44096. this.SPECULAROVERALPHA = false;
  44097. this.CLIPPLANE = false;
  44098. this.ALPHATEST = false;
  44099. this.ALPHAFROMALBEDO = false;
  44100. this.POINTSIZE = false;
  44101. this.FOG = false;
  44102. this.LIGHT0 = false;
  44103. this.LIGHT1 = false;
  44104. this.LIGHT2 = false;
  44105. this.LIGHT3 = false;
  44106. this.SPOTLIGHT0 = false;
  44107. this.SPOTLIGHT1 = false;
  44108. this.SPOTLIGHT2 = false;
  44109. this.SPOTLIGHT3 = false;
  44110. this.HEMILIGHT0 = false;
  44111. this.HEMILIGHT1 = false;
  44112. this.HEMILIGHT2 = false;
  44113. this.HEMILIGHT3 = false;
  44114. this.POINTLIGHT0 = false;
  44115. this.POINTLIGHT1 = false;
  44116. this.POINTLIGHT2 = false;
  44117. this.POINTLIGHT3 = false;
  44118. this.DIRLIGHT0 = false;
  44119. this.DIRLIGHT1 = false;
  44120. this.DIRLIGHT2 = false;
  44121. this.DIRLIGHT3 = false;
  44122. this.SPECULARTERM = false;
  44123. this.SHADOW0 = false;
  44124. this.SHADOW1 = false;
  44125. this.SHADOW2 = false;
  44126. this.SHADOW3 = false;
  44127. this.SHADOWS = false;
  44128. this.SHADOWVSM0 = false;
  44129. this.SHADOWVSM1 = false;
  44130. this.SHADOWVSM2 = false;
  44131. this.SHADOWVSM3 = false;
  44132. this.SHADOWPCF0 = false;
  44133. this.SHADOWPCF1 = false;
  44134. this.SHADOWPCF2 = false;
  44135. this.SHADOWPCF3 = false;
  44136. this.OPACITYFRESNEL = false;
  44137. this.EMISSIVEFRESNEL = false;
  44138. this.FRESNEL = false;
  44139. this.NORMAL = false;
  44140. this.UV1 = false;
  44141. this.UV2 = false;
  44142. this.VERTEXCOLOR = false;
  44143. this.VERTEXALPHA = false;
  44144. this.NUM_BONE_INFLUENCERS = 0;
  44145. this.BonesPerMesh = 0;
  44146. this.INSTANCES = false;
  44147. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44148. this.MICROSURFACEAUTOMATIC = false;
  44149. this.EMISSIVEASILLUMINATION = false;
  44150. this.LINKEMISSIVEWITHALBEDO = false;
  44151. this.LIGHTMAP = false;
  44152. this.USELIGHTMAPASSHADOWMAP = false;
  44153. this.REFLECTIONMAP_3D = false;
  44154. this.REFLECTIONMAP_SPHERICAL = false;
  44155. this.REFLECTIONMAP_PLANAR = false;
  44156. this.REFLECTIONMAP_CUBIC = false;
  44157. this.REFLECTIONMAP_PROJECTION = false;
  44158. this.REFLECTIONMAP_SKYBOX = false;
  44159. this.REFLECTIONMAP_EXPLICIT = false;
  44160. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44161. this.INVERTCUBICMAP = false;
  44162. this.LOGARITHMICDEPTH = false;
  44163. this.CAMERATONEMAP = false;
  44164. this.CAMERACONTRAST = false;
  44165. this.OVERLOADEDVALUES = false;
  44166. this.OVERLOADEDSHADOWVALUES = false;
  44167. this.USESPHERICALFROMREFLECTIONMAP = false;
  44168. this.REFRACTION = false;
  44169. this.REFRACTIONMAP_3D = false;
  44170. this.LINKREFRACTIONTOTRANSPARENCY = false;
  44171. this.REFRACTIONMAPINLINEARSPACE = false;
  44172. this.LODBASEDMICROSFURACE = false;
  44173. this.USEPHYSICALLIGHTFALLOFF = false;
  44174. this.RADIANCEOVERALPHA = false;
  44175. this.USEPMREMREFLECTION = false;
  44176. this.USEPMREMREFRACTION = false;
  44177. this._keys = Object.keys(this);
  44178. }
  44179. return PBRMaterialDefines;
  44180. })(BABYLON.MaterialDefines);
  44181. /**
  44182. * The Physically based material of BJS.
  44183. *
  44184. * This offers the main features of a standard PBR material.
  44185. * For more information, please refer to the documentation :
  44186. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44187. */
  44188. var PBRMaterial = (function (_super) {
  44189. __extends(PBRMaterial, _super);
  44190. /**
  44191. * Instantiates a new PBRMaterial instance.
  44192. *
  44193. * @param name The material name
  44194. * @param scene The scene the material will be use in.
  44195. */
  44196. function PBRMaterial(name, scene) {
  44197. var _this = this;
  44198. _super.call(this, name, scene);
  44199. /**
  44200. * Intensity of the direct lights e.g. the four lights available in your scene.
  44201. * This impacts both the direct diffuse and specular highlights.
  44202. */
  44203. this.directIntensity = 1.0;
  44204. /**
  44205. * Intensity of the emissive part of the material.
  44206. * This helps controlling the emissive effect without modifying the emissive color.
  44207. */
  44208. this.emissiveIntensity = 1.0;
  44209. /**
  44210. * Intensity of the environment e.g. how much the environment will light the object
  44211. * either through harmonics for rough material or through the refelction for shiny ones.
  44212. */
  44213. this.environmentIntensity = 1.0;
  44214. /**
  44215. * This is a special control allowing the reduction of the specular highlights coming from the
  44216. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44217. */
  44218. this.specularIntensity = 1.0;
  44219. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  44220. /**
  44221. * Debug Control allowing disabling the bump map on this material.
  44222. */
  44223. this.disableBumpMap = false;
  44224. /**
  44225. * Debug Control helping enforcing or dropping the darkness of shadows.
  44226. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  44227. */
  44228. this.overloadedShadowIntensity = 1.0;
  44229. /**
  44230. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  44231. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  44232. */
  44233. this.overloadedShadeIntensity = 1.0;
  44234. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  44235. /**
  44236. * The camera exposure used on this material.
  44237. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  44238. * This corresponds to a photographic exposure.
  44239. */
  44240. this.cameraExposure = 1.0;
  44241. /**
  44242. * The camera contrast used on this material.
  44243. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  44244. */
  44245. this.cameraContrast = 1.0;
  44246. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  44247. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  44248. /**
  44249. * Debug Control allowing to overload the ambient color.
  44250. * This as to be use with the overloadedAmbientIntensity parameter.
  44251. */
  44252. this.overloadedAmbient = BABYLON.Color3.White();
  44253. /**
  44254. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  44255. */
  44256. this.overloadedAmbientIntensity = 0.0;
  44257. /**
  44258. * Debug Control allowing to overload the albedo color.
  44259. * This as to be use with the overloadedAlbedoIntensity parameter.
  44260. */
  44261. this.overloadedAlbedo = BABYLON.Color3.White();
  44262. /**
  44263. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  44264. */
  44265. this.overloadedAlbedoIntensity = 0.0;
  44266. /**
  44267. * Debug Control allowing to overload the reflectivity color.
  44268. * This as to be use with the overloadedReflectivityIntensity parameter.
  44269. */
  44270. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  44271. /**
  44272. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  44273. */
  44274. this.overloadedReflectivityIntensity = 0.0;
  44275. /**
  44276. * Debug Control allowing to overload the emissive color.
  44277. * This as to be use with the overloadedEmissiveIntensity parameter.
  44278. */
  44279. this.overloadedEmissive = BABYLON.Color3.White();
  44280. /**
  44281. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  44282. */
  44283. this.overloadedEmissiveIntensity = 0.0;
  44284. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  44285. /**
  44286. * Debug Control allowing to overload the reflection color.
  44287. * This as to be use with the overloadedReflectionIntensity parameter.
  44288. */
  44289. this.overloadedReflection = BABYLON.Color3.White();
  44290. /**
  44291. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  44292. */
  44293. this.overloadedReflectionIntensity = 0.0;
  44294. /**
  44295. * Debug Control allowing to overload the microsurface.
  44296. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  44297. */
  44298. this.overloadedMicroSurface = 0.0;
  44299. /**
  44300. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  44301. */
  44302. this.overloadedMicroSurfaceIntensity = 0.0;
  44303. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  44304. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44305. /**
  44306. * AKA Diffuse Color in other nomenclature.
  44307. */
  44308. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44309. /**
  44310. * AKA Specular Color in other nomenclature.
  44311. */
  44312. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44313. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  44314. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44315. /**
  44316. * AKA Glossiness in other nomenclature.
  44317. */
  44318. this.microSurface = 0.9;
  44319. /**
  44320. * source material index of refraction (IOR)' / 'destination material IOR.
  44321. */
  44322. this.indexOfRefraction = 0.66;
  44323. /**
  44324. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44325. */
  44326. this.invertRefractionY = false;
  44327. /**
  44328. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44329. * Materials half opaque for instance using refraction could benefit from this control.
  44330. */
  44331. this.linkRefractionWithTransparency = false;
  44332. /**
  44333. * The emissive and albedo are linked to never be more than one (Energy conservation).
  44334. */
  44335. this.linkEmissiveWithAlbedo = false;
  44336. this.useLightmapAsShadowmap = false;
  44337. /**
  44338. * In this mode, the emissive informtaion will always be added to the lighting once.
  44339. * A light for instance can be thought as emissive.
  44340. */
  44341. this.useEmissiveAsIllumination = false;
  44342. /**
  44343. * Secifies that the alpha is coming form the albedo channel alpha channel.
  44344. */
  44345. this.useAlphaFromAlbedoTexture = false;
  44346. /**
  44347. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44348. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44349. */
  44350. this.useSpecularOverAlpha = true;
  44351. /**
  44352. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44353. */
  44354. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44355. /**
  44356. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44357. * The material will try to infer what glossiness each pixel should be.
  44358. */
  44359. this.useAutoMicroSurfaceFromReflectivityMap = false;
  44360. /**
  44361. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  44362. * the creation of the material.
  44363. */
  44364. this.useScalarInLinearSpace = false;
  44365. /**
  44366. * BJS is using an harcoded light falloff based on a manually sets up range.
  44367. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44368. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44369. */
  44370. this.usePhysicalLightFalloff = true;
  44371. /**
  44372. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44373. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44374. */
  44375. this.useRadianceOverAlpha = true;
  44376. /**
  44377. * Allows using the bump map in parallax mode.
  44378. */
  44379. this.useParallax = false;
  44380. /**
  44381. * Allows using the bump map in parallax occlusion mode.
  44382. */
  44383. this.useParallaxOcclusion = false;
  44384. /**
  44385. * Controls the scale bias of the parallax mode.
  44386. */
  44387. this.parallaxScaleBias = 0.05;
  44388. this.disableLighting = false;
  44389. this._renderTargets = new BABYLON.SmartArray(16);
  44390. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  44391. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44392. this._tempColor = new BABYLON.Color3();
  44393. this._defines = new PBRMaterialDefines();
  44394. this._cachedDefines = new PBRMaterialDefines();
  44395. this._myScene = null;
  44396. this._myShadowGenerator = null;
  44397. this._cachedDefines.BonesPerMesh = -1;
  44398. this.getRenderTargetTextures = function () {
  44399. _this._renderTargets.reset();
  44400. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  44401. _this._renderTargets.push(_this.reflectionTexture);
  44402. }
  44403. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  44404. _this._renderTargets.push(_this.refractionTexture);
  44405. }
  44406. return _this._renderTargets;
  44407. };
  44408. }
  44409. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  44410. get: function () {
  44411. return this._useLogarithmicDepth;
  44412. },
  44413. set: function (value) {
  44414. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44415. },
  44416. enumerable: true,
  44417. configurable: true
  44418. });
  44419. PBRMaterial.prototype.needAlphaBlending = function () {
  44420. if (this.linkRefractionWithTransparency) {
  44421. return false;
  44422. }
  44423. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  44424. };
  44425. PBRMaterial.prototype.needAlphaTesting = function () {
  44426. if (this.linkRefractionWithTransparency) {
  44427. return false;
  44428. }
  44429. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  44430. };
  44431. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44432. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  44433. };
  44434. PBRMaterial.prototype.getAlphaTestTexture = function () {
  44435. return this.albedoTexture;
  44436. };
  44437. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  44438. if (!mesh) {
  44439. return true;
  44440. }
  44441. if (this._defines.INSTANCES !== useInstances) {
  44442. return false;
  44443. }
  44444. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  44445. return true;
  44446. }
  44447. return false;
  44448. };
  44449. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  44450. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  44451. };
  44452. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  44453. if (!useScalarInLinear) {
  44454. color.toLinearSpaceToRef(ref);
  44455. }
  44456. else {
  44457. ref.r = color.r;
  44458. ref.g = color.g;
  44459. ref.b = color.b;
  44460. }
  44461. };
  44462. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace) {
  44463. var lightIndex = 0;
  44464. var depthValuesAlreadySet = false;
  44465. for (var index = 0; index < scene.lights.length; index++) {
  44466. var light = scene.lights[index];
  44467. if (!light.isEnabled()) {
  44468. continue;
  44469. }
  44470. if (!light.canAffectMesh(mesh)) {
  44471. continue;
  44472. }
  44473. this._lightRadiuses[lightIndex] = light.radius;
  44474. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  44475. // GAMMA CORRECTION.
  44476. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  44477. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  44478. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, light.range);
  44479. if (defines["SPECULARTERM"]) {
  44480. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  44481. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  44482. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  44483. }
  44484. // Shadows
  44485. if (scene.shadowsEnabled) {
  44486. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  44487. }
  44488. lightIndex++;
  44489. if (lightIndex === maxSimultaneousLights)
  44490. break;
  44491. }
  44492. effect.setFloat4("vLightRadiuses", this._lightRadiuses[0], this._lightRadiuses[1], this._lightRadiuses[2], this._lightRadiuses[3]);
  44493. };
  44494. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  44495. if (this.checkReadyOnlyOnce) {
  44496. if (this._wasPreviouslyReady) {
  44497. return true;
  44498. }
  44499. }
  44500. var scene = this.getScene();
  44501. if (!this.checkReadyOnEveryCall) {
  44502. if (this._renderId === scene.getRenderId()) {
  44503. if (this._checkCache(scene, mesh, useInstances)) {
  44504. return true;
  44505. }
  44506. }
  44507. }
  44508. var engine = scene.getEngine();
  44509. var needNormals = false;
  44510. var needUVs = false;
  44511. this._defines.reset();
  44512. if (scene.texturesEnabled) {
  44513. // Textures
  44514. if (scene.texturesEnabled) {
  44515. if (scene.getEngine().getCaps().textureLOD) {
  44516. this._defines.LODBASEDMICROSFURACE = true;
  44517. }
  44518. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44519. if (!this.albedoTexture.isReady()) {
  44520. return false;
  44521. }
  44522. else {
  44523. needUVs = true;
  44524. this._defines.ALBEDO = true;
  44525. }
  44526. }
  44527. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44528. if (!this.ambientTexture.isReady()) {
  44529. return false;
  44530. }
  44531. else {
  44532. needUVs = true;
  44533. this._defines.AMBIENT = true;
  44534. }
  44535. }
  44536. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44537. if (!this.opacityTexture.isReady()) {
  44538. return false;
  44539. }
  44540. else {
  44541. needUVs = true;
  44542. this._defines.OPACITY = true;
  44543. if (this.opacityTexture.getAlphaFromRGB) {
  44544. this._defines.OPACITYRGB = true;
  44545. }
  44546. }
  44547. }
  44548. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44549. if (!this.reflectionTexture.isReady()) {
  44550. return false;
  44551. }
  44552. else {
  44553. needNormals = true;
  44554. this._defines.REFLECTION = true;
  44555. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44556. this._defines.INVERTCUBICMAP = true;
  44557. }
  44558. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  44559. switch (this.reflectionTexture.coordinatesMode) {
  44560. case BABYLON.Texture.CUBIC_MODE:
  44561. case BABYLON.Texture.INVCUBIC_MODE:
  44562. this._defines.REFLECTIONMAP_CUBIC = true;
  44563. break;
  44564. case BABYLON.Texture.EXPLICIT_MODE:
  44565. this._defines.REFLECTIONMAP_EXPLICIT = true;
  44566. break;
  44567. case BABYLON.Texture.PLANAR_MODE:
  44568. this._defines.REFLECTIONMAP_PLANAR = true;
  44569. break;
  44570. case BABYLON.Texture.PROJECTION_MODE:
  44571. this._defines.REFLECTIONMAP_PROJECTION = true;
  44572. break;
  44573. case BABYLON.Texture.SKYBOX_MODE:
  44574. this._defines.REFLECTIONMAP_SKYBOX = true;
  44575. break;
  44576. case BABYLON.Texture.SPHERICAL_MODE:
  44577. this._defines.REFLECTIONMAP_SPHERICAL = true;
  44578. break;
  44579. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44580. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44581. break;
  44582. }
  44583. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  44584. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  44585. needNormals = true;
  44586. if (this.reflectionTexture.isPMREM) {
  44587. this._defines.USEPMREMREFLECTION = true;
  44588. }
  44589. }
  44590. }
  44591. }
  44592. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44593. if (!this.lightmapTexture.isReady()) {
  44594. return false;
  44595. }
  44596. else {
  44597. needUVs = true;
  44598. this._defines.LIGHTMAP = true;
  44599. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  44600. }
  44601. }
  44602. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44603. if (!this.emissiveTexture.isReady()) {
  44604. return false;
  44605. }
  44606. else {
  44607. needUVs = true;
  44608. this._defines.EMISSIVE = true;
  44609. }
  44610. }
  44611. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44612. if (!this.reflectivityTexture.isReady()) {
  44613. return false;
  44614. }
  44615. else {
  44616. needUVs = true;
  44617. this._defines.REFLECTIVITY = true;
  44618. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  44619. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  44620. }
  44621. }
  44622. }
  44623. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  44624. if (!this.bumpTexture.isReady()) {
  44625. return false;
  44626. }
  44627. else {
  44628. needUVs = true;
  44629. this._defines.BUMP = true;
  44630. if (this.useParallax) {
  44631. this._defines.PARALLAX = true;
  44632. if (this.useParallaxOcclusion) {
  44633. this._defines.PARALLAXOCCLUSION = true;
  44634. }
  44635. }
  44636. }
  44637. }
  44638. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44639. if (!this.refractionTexture.isReady()) {
  44640. return false;
  44641. }
  44642. else {
  44643. needUVs = true;
  44644. this._defines.REFRACTION = true;
  44645. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  44646. if (this.linkRefractionWithTransparency) {
  44647. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44648. }
  44649. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  44650. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  44651. if (this.refractionTexture.isPMREM) {
  44652. this._defines.USEPMREMREFRACTION = true;
  44653. }
  44654. }
  44655. }
  44656. }
  44657. }
  44658. // Effect
  44659. if (scene.clipPlane) {
  44660. this._defines.CLIPPLANE = true;
  44661. }
  44662. if (engine.getAlphaTesting()) {
  44663. this._defines.ALPHATEST = true;
  44664. }
  44665. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44666. this._defines.ALPHAFROMALBEDO = true;
  44667. }
  44668. if (this.useEmissiveAsIllumination) {
  44669. this._defines.EMISSIVEASILLUMINATION = true;
  44670. }
  44671. if (this.linkEmissiveWithAlbedo) {
  44672. this._defines.LINKEMISSIVEWITHALBEDO = true;
  44673. }
  44674. if (this.useLogarithmicDepth) {
  44675. this._defines.LOGARITHMICDEPTH = true;
  44676. }
  44677. if (this.cameraContrast != 1) {
  44678. this._defines.CAMERACONTRAST = true;
  44679. }
  44680. if (this.cameraExposure != 1) {
  44681. this._defines.CAMERATONEMAP = true;
  44682. }
  44683. if (this.overloadedShadeIntensity != 1 ||
  44684. this.overloadedShadowIntensity != 1) {
  44685. this._defines.OVERLOADEDSHADOWVALUES = true;
  44686. }
  44687. if (this.overloadedMicroSurfaceIntensity > 0 ||
  44688. this.overloadedEmissiveIntensity > 0 ||
  44689. this.overloadedReflectivityIntensity > 0 ||
  44690. this.overloadedAlbedoIntensity > 0 ||
  44691. this.overloadedAmbientIntensity > 0 ||
  44692. this.overloadedReflectionIntensity > 0) {
  44693. this._defines.OVERLOADEDVALUES = true;
  44694. }
  44695. // Point size
  44696. if (this.pointsCloud || scene.forcePointsCloud) {
  44697. this._defines.POINTSIZE = true;
  44698. }
  44699. // Fog
  44700. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  44701. this._defines.FOG = true;
  44702. }
  44703. if (scene.lightsEnabled && !this.disableLighting) {
  44704. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines) || needNormals;
  44705. }
  44706. if (BABYLON.StandardMaterial.FresnelEnabled) {
  44707. // Fresnel
  44708. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  44709. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44710. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  44711. this._defines.OPACITYFRESNEL = true;
  44712. }
  44713. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44714. this._defines.EMISSIVEFRESNEL = true;
  44715. }
  44716. needNormals = true;
  44717. this._defines.FRESNEL = true;
  44718. }
  44719. }
  44720. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  44721. this._defines.SPECULAROVERALPHA = true;
  44722. }
  44723. if (this.usePhysicalLightFalloff) {
  44724. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  44725. }
  44726. if (this.useRadianceOverAlpha) {
  44727. this._defines.RADIANCEOVERALPHA = true;
  44728. }
  44729. // Attribs
  44730. if (mesh) {
  44731. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44732. this._defines.NORMAL = true;
  44733. }
  44734. if (needUVs) {
  44735. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44736. this._defines.UV1 = true;
  44737. }
  44738. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  44739. this._defines.UV2 = true;
  44740. }
  44741. }
  44742. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  44743. this._defines.VERTEXCOLOR = true;
  44744. if (mesh.hasVertexAlpha) {
  44745. this._defines.VERTEXALPHA = true;
  44746. }
  44747. }
  44748. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44749. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  44750. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  44751. }
  44752. // Instances
  44753. if (useInstances) {
  44754. this._defines.INSTANCES = true;
  44755. }
  44756. }
  44757. // Get correct effect
  44758. if (!this._defines.isEqual(this._cachedDefines)) {
  44759. this._defines.cloneTo(this._cachedDefines);
  44760. scene.resetCachedMaterial();
  44761. // Fallbacks
  44762. var fallbacks = new BABYLON.EffectFallbacks();
  44763. if (this._defines.REFLECTION) {
  44764. fallbacks.addFallback(0, "REFLECTION");
  44765. }
  44766. if (this._defines.REFRACTION) {
  44767. fallbacks.addFallback(0, "REFRACTION");
  44768. }
  44769. if (this._defines.REFLECTIVITY) {
  44770. fallbacks.addFallback(0, "REFLECTIVITY");
  44771. }
  44772. if (this._defines.BUMP) {
  44773. fallbacks.addFallback(0, "BUMP");
  44774. }
  44775. if (this._defines.PARALLAX) {
  44776. fallbacks.addFallback(1, "PARALLAX");
  44777. }
  44778. if (this._defines.PARALLAXOCCLUSION) {
  44779. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  44780. }
  44781. if (this._defines.SPECULAROVERALPHA) {
  44782. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  44783. }
  44784. if (this._defines.FOG) {
  44785. fallbacks.addFallback(1, "FOG");
  44786. }
  44787. if (this._defines.POINTSIZE) {
  44788. fallbacks.addFallback(0, "POINTSIZE");
  44789. }
  44790. if (this._defines.LOGARITHMICDEPTH) {
  44791. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  44792. }
  44793. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks);
  44794. if (this._defines.SPECULARTERM) {
  44795. fallbacks.addFallback(0, "SPECULARTERM");
  44796. }
  44797. if (this._defines.OPACITYFRESNEL) {
  44798. fallbacks.addFallback(1, "OPACITYFRESNEL");
  44799. }
  44800. if (this._defines.EMISSIVEFRESNEL) {
  44801. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  44802. }
  44803. if (this._defines.FRESNEL) {
  44804. fallbacks.addFallback(3, "FRESNEL");
  44805. }
  44806. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  44807. fallbacks.addCPUSkinningFallback(0, mesh);
  44808. }
  44809. //Attributes
  44810. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44811. if (this._defines.NORMAL) {
  44812. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44813. }
  44814. if (this._defines.UV1) {
  44815. attribs.push(BABYLON.VertexBuffer.UVKind);
  44816. }
  44817. if (this._defines.UV2) {
  44818. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44819. }
  44820. if (this._defines.VERTEXCOLOR) {
  44821. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44822. }
  44823. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  44824. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  44825. // Legacy browser patch
  44826. var shaderName = "pbr";
  44827. if (!scene.getEngine().getCaps().standardDerivatives) {
  44828. shaderName = "legacypbr";
  44829. }
  44830. var join = this._defines.toString();
  44831. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44832. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  44833. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  44834. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  44835. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  44836. "vFogInfos", "vFogColor", "pointSize",
  44837. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44838. "mBones",
  44839. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44840. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "depthValues",
  44841. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  44842. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vCameraInfos", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  44843. "logarithmicDepthConstant",
  44844. "vSphericalX", "vSphericalY", "vSphericalZ",
  44845. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44846. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44847. "vMicrosurfaceTextureLods", "vLightRadiuses"
  44848. ], ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler",
  44849. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  44850. ], join, fallbacks, this.onCompiled, this.onError);
  44851. }
  44852. if (!this._effect.isReady()) {
  44853. return false;
  44854. }
  44855. this._renderId = scene.getRenderId();
  44856. this._wasPreviouslyReady = true;
  44857. if (mesh) {
  44858. if (!mesh._materialDefines) {
  44859. mesh._materialDefines = new PBRMaterialDefines();
  44860. }
  44861. this._defines.cloneTo(mesh._materialDefines);
  44862. }
  44863. return true;
  44864. };
  44865. PBRMaterial.prototype.unbind = function () {
  44866. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  44867. this._effect.setTexture("reflection2DSampler", null);
  44868. }
  44869. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  44870. this._effect.setTexture("refraction2DSampler", null);
  44871. }
  44872. _super.prototype.unbind.call(this);
  44873. };
  44874. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  44875. this._effect.setMatrix("world", world);
  44876. };
  44877. PBRMaterial.prototype.bind = function (world, mesh) {
  44878. this._myScene = this.getScene();
  44879. // Matrices
  44880. this.bindOnlyWorldMatrix(world);
  44881. // Bones
  44882. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  44883. if (this._myScene.getCachedMaterial() !== this) {
  44884. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  44885. if (BABYLON.StandardMaterial.FresnelEnabled) {
  44886. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  44887. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  44888. }
  44889. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  44890. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  44891. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  44892. }
  44893. }
  44894. // Textures
  44895. if (this._myScene.texturesEnabled) {
  44896. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44897. this._effect.setTexture("albedoSampler", this.albedoTexture);
  44898. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  44899. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  44900. }
  44901. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44902. this._effect.setTexture("ambientSampler", this.ambientTexture);
  44903. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  44904. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  44905. }
  44906. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44907. this._effect.setTexture("opacitySampler", this.opacityTexture);
  44908. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  44909. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  44910. }
  44911. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44912. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  44913. if (this.reflectionTexture.isCube) {
  44914. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  44915. }
  44916. else {
  44917. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  44918. }
  44919. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  44920. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  44921. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  44922. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  44923. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  44924. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  44925. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  44926. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  44927. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  44928. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  44929. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  44930. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  44931. }
  44932. }
  44933. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44934. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  44935. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  44936. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  44937. }
  44938. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44939. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  44940. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  44941. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  44942. }
  44943. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44944. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  44945. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  44946. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  44947. }
  44948. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  44949. this._effect.setTexture("bumpSampler", this.bumpTexture);
  44950. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  44951. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  44952. }
  44953. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44954. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  44955. var depth = 1.0;
  44956. if (this.refractionTexture.isCube) {
  44957. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  44958. }
  44959. else {
  44960. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  44961. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  44962. if (this.refractionTexture.depth) {
  44963. depth = this.refractionTexture.depth;
  44964. }
  44965. }
  44966. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  44967. }
  44968. if ((this.reflectionTexture || this.refractionTexture)) {
  44969. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  44970. }
  44971. }
  44972. // Clip plane
  44973. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  44974. // Point size
  44975. if (this.pointsCloud) {
  44976. this._effect.setFloat("pointSize", this.pointSize);
  44977. }
  44978. // Colors
  44979. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  44980. // GAMMA CORRECTION.
  44981. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  44982. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  44983. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44984. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  44985. // GAMMA CORRECTION.
  44986. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  44987. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  44988. // GAMMA CORRECTION.
  44989. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  44990. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  44991. }
  44992. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  44993. // GAMMA CORRECTION.
  44994. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  44995. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  44996. // Lights
  44997. if (this._myScene.lightsEnabled && !this.disableLighting) {
  44998. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace);
  44999. }
  45000. // View
  45001. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  45002. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  45003. }
  45004. // Fog
  45005. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  45006. this._lightingInfos.x = this.directIntensity;
  45007. this._lightingInfos.y = this.emissiveIntensity;
  45008. this._lightingInfos.z = this.environmentIntensity;
  45009. this._lightingInfos.w = this.specularIntensity;
  45010. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  45011. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  45012. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  45013. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  45014. this._cameraInfos.x = this.cameraExposure;
  45015. this._cameraInfos.y = this.cameraContrast;
  45016. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  45017. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  45018. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  45019. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  45020. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  45021. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  45022. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  45023. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  45024. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  45025. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  45026. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  45027. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  45028. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  45029. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  45030. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  45031. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  45032. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  45033. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  45034. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  45035. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  45036. // Log. depth
  45037. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  45038. }
  45039. _super.prototype.bind.call(this, world, mesh);
  45040. this._myScene = null;
  45041. };
  45042. PBRMaterial.prototype.getAnimatables = function () {
  45043. var results = [];
  45044. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  45045. results.push(this.albedoTexture);
  45046. }
  45047. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  45048. results.push(this.ambientTexture);
  45049. }
  45050. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  45051. results.push(this.opacityTexture);
  45052. }
  45053. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  45054. results.push(this.reflectionTexture);
  45055. }
  45056. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  45057. results.push(this.emissiveTexture);
  45058. }
  45059. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  45060. results.push(this.reflectivityTexture);
  45061. }
  45062. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  45063. results.push(this.bumpTexture);
  45064. }
  45065. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  45066. results.push(this.lightmapTexture);
  45067. }
  45068. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  45069. results.push(this.refractionTexture);
  45070. }
  45071. return results;
  45072. };
  45073. PBRMaterial.prototype.dispose = function (forceDisposeEffect) {
  45074. if (this.albedoTexture) {
  45075. this.albedoTexture.dispose();
  45076. }
  45077. if (this.ambientTexture) {
  45078. this.ambientTexture.dispose();
  45079. }
  45080. if (this.opacityTexture) {
  45081. this.opacityTexture.dispose();
  45082. }
  45083. if (this.reflectionTexture) {
  45084. this.reflectionTexture.dispose();
  45085. }
  45086. if (this.emissiveTexture) {
  45087. this.emissiveTexture.dispose();
  45088. }
  45089. if (this.reflectivityTexture) {
  45090. this.reflectivityTexture.dispose();
  45091. }
  45092. if (this.bumpTexture) {
  45093. this.bumpTexture.dispose();
  45094. }
  45095. if (this.lightmapTexture) {
  45096. this.lightmapTexture.dispose();
  45097. }
  45098. if (this.refractionTexture) {
  45099. this.refractionTexture.dispose();
  45100. }
  45101. _super.prototype.dispose.call(this, forceDisposeEffect);
  45102. };
  45103. PBRMaterial.prototype.clone = function (name) {
  45104. var _this = this;
  45105. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45106. };
  45107. PBRMaterial.prototype.serialize = function () {
  45108. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45109. serializationObject.customType = "BABYLON.PBRMaterial";
  45110. return serializationObject;
  45111. };
  45112. // Statics
  45113. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45114. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45115. };
  45116. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  45117. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  45118. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  45119. PBRMaterial._scaledReflection = new BABYLON.Color3();
  45120. PBRMaterial._lightRadiuses = [1, 1, 1, 1];
  45121. __decorate([
  45122. BABYLON.serialize()
  45123. ], PBRMaterial.prototype, "directIntensity", void 0);
  45124. __decorate([
  45125. BABYLON.serialize()
  45126. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45127. __decorate([
  45128. BABYLON.serialize()
  45129. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45130. __decorate([
  45131. BABYLON.serialize()
  45132. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45133. __decorate([
  45134. BABYLON.serialize()
  45135. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45136. __decorate([
  45137. BABYLON.serialize()
  45138. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  45139. __decorate([
  45140. BABYLON.serialize()
  45141. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  45142. __decorate([
  45143. BABYLON.serialize()
  45144. ], PBRMaterial.prototype, "cameraExposure", void 0);
  45145. __decorate([
  45146. BABYLON.serialize()
  45147. ], PBRMaterial.prototype, "cameraContrast", void 0);
  45148. __decorate([
  45149. BABYLON.serializeAsColor3()
  45150. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  45151. __decorate([
  45152. BABYLON.serialize()
  45153. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  45154. __decorate([
  45155. BABYLON.serializeAsColor3()
  45156. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  45157. __decorate([
  45158. BABYLON.serialize()
  45159. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  45160. __decorate([
  45161. BABYLON.serializeAsColor3()
  45162. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  45163. __decorate([
  45164. BABYLON.serialize()
  45165. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  45166. __decorate([
  45167. BABYLON.serializeAsColor3()
  45168. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  45169. __decorate([
  45170. BABYLON.serialize()
  45171. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  45172. __decorate([
  45173. BABYLON.serializeAsColor3()
  45174. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  45175. __decorate([
  45176. BABYLON.serialize()
  45177. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  45178. __decorate([
  45179. BABYLON.serialize()
  45180. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  45181. __decorate([
  45182. BABYLON.serialize()
  45183. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  45184. __decorate([
  45185. BABYLON.serializeAsTexture()
  45186. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45187. __decorate([
  45188. BABYLON.serializeAsTexture()
  45189. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45190. __decorate([
  45191. BABYLON.serializeAsTexture()
  45192. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45193. __decorate([
  45194. BABYLON.serializeAsTexture()
  45195. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45196. __decorate([
  45197. BABYLON.serializeAsTexture()
  45198. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45199. __decorate([
  45200. BABYLON.serializeAsTexture()
  45201. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45202. __decorate([
  45203. BABYLON.serializeAsTexture()
  45204. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45205. __decorate([
  45206. BABYLON.serializeAsTexture()
  45207. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45208. __decorate([
  45209. BABYLON.serializeAsTexture()
  45210. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45211. __decorate([
  45212. BABYLON.serializeAsColor3("ambient")
  45213. ], PBRMaterial.prototype, "ambientColor", void 0);
  45214. __decorate([
  45215. BABYLON.serializeAsColor3("albedo")
  45216. ], PBRMaterial.prototype, "albedoColor", void 0);
  45217. __decorate([
  45218. BABYLON.serializeAsColor3("reflectivity")
  45219. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45220. __decorate([
  45221. BABYLON.serializeAsColor3("reflection")
  45222. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45223. __decorate([
  45224. BABYLON.serializeAsColor3("emissive")
  45225. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45226. __decorate([
  45227. BABYLON.serialize()
  45228. ], PBRMaterial.prototype, "microSurface", void 0);
  45229. __decorate([
  45230. BABYLON.serialize()
  45231. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45232. __decorate([
  45233. BABYLON.serialize()
  45234. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45235. __decorate([
  45236. BABYLON.serializeAsFresnelParameters()
  45237. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  45238. __decorate([
  45239. BABYLON.serializeAsFresnelParameters()
  45240. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  45241. __decorate([
  45242. BABYLON.serialize()
  45243. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45244. __decorate([
  45245. BABYLON.serialize()
  45246. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  45247. __decorate([
  45248. BABYLON.serialize()
  45249. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45250. __decorate([
  45251. BABYLON.serialize()
  45252. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  45253. __decorate([
  45254. BABYLON.serialize()
  45255. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45256. __decorate([
  45257. BABYLON.serialize()
  45258. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45259. __decorate([
  45260. BABYLON.serialize()
  45261. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45262. __decorate([
  45263. BABYLON.serialize()
  45264. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45265. __decorate([
  45266. BABYLON.serialize()
  45267. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  45268. __decorate([
  45269. BABYLON.serialize()
  45270. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45271. __decorate([
  45272. BABYLON.serialize()
  45273. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45274. __decorate([
  45275. BABYLON.serialize()
  45276. ], PBRMaterial.prototype, "useParallax", void 0);
  45277. __decorate([
  45278. BABYLON.serialize()
  45279. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45280. __decorate([
  45281. BABYLON.serialize()
  45282. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45283. __decorate([
  45284. BABYLON.serialize()
  45285. ], PBRMaterial.prototype, "disableLighting", void 0);
  45286. __decorate([
  45287. BABYLON.serialize()
  45288. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  45289. return PBRMaterial;
  45290. })(BABYLON.Material);
  45291. BABYLON.PBRMaterial = PBRMaterial;
  45292. })(BABYLON || (BABYLON = {}));
  45293. 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}"};
  45294. 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"};
  45295. 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.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.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.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),n},t.Invert=function(i){var n=new t;return i.invertToRef(n),n},t.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationY=function(i){var n=new t;return t.RotationYToRef(i,n),n},t.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);\ni.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={}));";
  45296. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  45297. module.exports = BABYLON;
  45298. };