babylon.max.js 3.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572
  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 () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. BABYLON.ToGammaSpace = 1 / 2.2;
  20. BABYLON.ToLinearSpace = 2.2;
  21. BABYLON.Epsilon = 0.001;
  22. var MathTools = (function () {
  23. function MathTools() {
  24. }
  25. /**
  26. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  27. */
  28. MathTools.WithinEpsilon = function (a, b, epsilon) {
  29. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  30. var num = a - b;
  31. return -epsilon <= num && num <= epsilon;
  32. };
  33. /**
  34. * Returns a string : the upper case translation of the number i to hexadecimal.
  35. */
  36. MathTools.ToHex = function (i) {
  37. var str = i.toString(16);
  38. if (i <= 15) {
  39. return ("0" + str).toUpperCase();
  40. }
  41. return str.toUpperCase();
  42. };
  43. /**
  44. * Returns -1 if value is negative and +1 is value is positive.
  45. * Returns the value itself if it's equal to zero.
  46. */
  47. MathTools.Sign = function (value) {
  48. value = +value; // convert to a number
  49. if (value === 0 || isNaN(value))
  50. return value;
  51. return value > 0 ? 1 : -1;
  52. };
  53. /**
  54. * Returns the value itself if it's between min and max.
  55. * Returns min if the value is lower than min.
  56. * Returns max if the value is greater than max.
  57. */
  58. MathTools.Clamp = function (value, min, max) {
  59. if (min === void 0) { min = 0; }
  60. if (max === void 0) { max = 1; }
  61. return Math.min(max, Math.max(min, value));
  62. };
  63. return MathTools;
  64. }());
  65. BABYLON.MathTools = MathTools;
  66. var Scalar = (function () {
  67. function Scalar() {
  68. }
  69. /**
  70. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  71. */
  72. Scalar.Lerp = function (start, end, amount) {
  73. return start + ((end - start) * amount);
  74. };
  75. /**
  76. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  77. */
  78. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  79. var squared = amount * amount;
  80. var cubed = amount * squared;
  81. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  82. var part2 = (-2.0 * cubed) + (3.0 * squared);
  83. var part3 = (cubed - (2.0 * squared)) + amount;
  84. var part4 = cubed - squared;
  85. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  86. };
  87. return Scalar;
  88. }());
  89. BABYLON.Scalar = Scalar;
  90. var Color3 = (function () {
  91. /**
  92. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  93. */
  94. function Color3(r, g, b) {
  95. if (r === void 0) { r = 0; }
  96. if (g === void 0) { g = 0; }
  97. if (b === void 0) { b = 0; }
  98. this.r = r;
  99. this.g = g;
  100. this.b = b;
  101. }
  102. /**
  103. * Returns a string with the Color3 current values.
  104. */
  105. Color3.prototype.toString = function () {
  106. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  107. };
  108. /**
  109. * Returns the string "Color3".
  110. */
  111. Color3.prototype.getClassName = function () {
  112. return "Color3";
  113. };
  114. /**
  115. * Returns the Color3 hash code.
  116. */
  117. Color3.prototype.getHashCode = function () {
  118. var hash = this.r || 0;
  119. hash = (hash * 397) ^ (this.g || 0);
  120. hash = (hash * 397) ^ (this.b || 0);
  121. return hash;
  122. };
  123. // Operators
  124. /**
  125. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  126. * Returns the Color3.
  127. */
  128. Color3.prototype.toArray = function (array, index) {
  129. if (index === undefined) {
  130. index = 0;
  131. }
  132. array[index] = this.r;
  133. array[index + 1] = this.g;
  134. array[index + 2] = this.b;
  135. return this;
  136. };
  137. /**
  138. * Returns a new Color4 object from the current Color3 and the passed alpha.
  139. */
  140. Color3.prototype.toColor4 = function (alpha) {
  141. if (alpha === void 0) { alpha = 1; }
  142. return new Color4(this.r, this.g, this.b, alpha);
  143. };
  144. /**
  145. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  146. */
  147. Color3.prototype.asArray = function () {
  148. var result = [];
  149. this.toArray(result, 0);
  150. return result;
  151. };
  152. /**
  153. * Returns the luminance value (float).
  154. */
  155. Color3.prototype.toLuminance = function () {
  156. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  157. };
  158. /**
  159. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  160. * Returns this new object.
  161. */
  162. Color3.prototype.multiply = function (otherColor) {
  163. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  164. };
  165. /**
  166. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  167. * Returns the current Color3.
  168. */
  169. Color3.prototype.multiplyToRef = function (otherColor, result) {
  170. result.r = this.r * otherColor.r;
  171. result.g = this.g * otherColor.g;
  172. result.b = this.b * otherColor.b;
  173. return this;
  174. };
  175. /**
  176. * Boolean : True if the rgb values are equal to the passed ones.
  177. */
  178. Color3.prototype.equals = function (otherColor) {
  179. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  180. };
  181. /**
  182. * Boolean : True if the rgb values are equal to the passed ones.
  183. */
  184. Color3.prototype.equalsFloats = function (r, g, b) {
  185. return this.r === r && this.g === g && this.b === b;
  186. };
  187. /**
  188. * Multiplies in place each rgb value by scale.
  189. * Returns the updated Color3.
  190. */
  191. Color3.prototype.scale = function (scale) {
  192. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  193. };
  194. /**
  195. * Multiplies the rgb values by scale and stores the result into "result".
  196. * Returns the unmodified current Color3.
  197. */
  198. Color3.prototype.scaleToRef = function (scale, result) {
  199. result.r = this.r * scale;
  200. result.g = this.g * scale;
  201. result.b = this.b * scale;
  202. return this;
  203. };
  204. /**
  205. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  206. */
  207. Color3.prototype.add = function (otherColor) {
  208. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  209. };
  210. /**
  211. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  212. * Returns the unmodified current Color3.
  213. */
  214. Color3.prototype.addToRef = function (otherColor, result) {
  215. result.r = this.r + otherColor.r;
  216. result.g = this.g + otherColor.g;
  217. result.b = this.b + otherColor.b;
  218. return this;
  219. };
  220. /**
  221. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  222. */
  223. Color3.prototype.subtract = function (otherColor) {
  224. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  225. };
  226. /**
  227. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  228. * Returns the unmodified current Color3.
  229. */
  230. Color3.prototype.subtractToRef = function (otherColor, result) {
  231. result.r = this.r - otherColor.r;
  232. result.g = this.g - otherColor.g;
  233. result.b = this.b - otherColor.b;
  234. return this;
  235. };
  236. /**
  237. * Returns a new Color3 copied the current one.
  238. */
  239. Color3.prototype.clone = function () {
  240. return new Color3(this.r, this.g, this.b);
  241. };
  242. /**
  243. * Copies the rgb values from the source in the current Color3.
  244. * Returns the updated Color3.
  245. */
  246. Color3.prototype.copyFrom = function (source) {
  247. this.r = source.r;
  248. this.g = source.g;
  249. this.b = source.b;
  250. return this;
  251. };
  252. /**
  253. * Updates the Color3 rgb values from the passed floats.
  254. * Returns the Color3.
  255. */
  256. Color3.prototype.copyFromFloats = function (r, g, b) {
  257. this.r = r;
  258. this.g = g;
  259. this.b = b;
  260. return this;
  261. };
  262. /**
  263. * Updates the Color3 rgb values from the passed floats.
  264. * Returns the Color3.
  265. */
  266. Color3.prototype.set = function (r, g, b) {
  267. return this.copyFromFloats(r, g, b);
  268. };
  269. /**
  270. * Returns the Color3 hexadecimal code as a string.
  271. */
  272. Color3.prototype.toHexString = function () {
  273. var intR = (this.r * 255) | 0;
  274. var intG = (this.g * 255) | 0;
  275. var intB = (this.b * 255) | 0;
  276. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  277. };
  278. /**
  279. * Returns a new Color3 converted to linear space.
  280. */
  281. Color3.prototype.toLinearSpace = function () {
  282. var convertedColor = new Color3();
  283. this.toLinearSpaceToRef(convertedColor);
  284. return convertedColor;
  285. };
  286. /**
  287. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  288. * Returns the unmodified Color3.
  289. */
  290. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  291. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  292. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  293. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  294. return this;
  295. };
  296. /**
  297. * Returns a new Color3 converted to gamma space.
  298. */
  299. Color3.prototype.toGammaSpace = function () {
  300. var convertedColor = new Color3();
  301. this.toGammaSpaceToRef(convertedColor);
  302. return convertedColor;
  303. };
  304. /**
  305. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  306. * Returns the unmodified Color3.
  307. */
  308. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  309. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  310. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  311. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  312. return this;
  313. };
  314. // Statics
  315. /**
  316. * Creates a new Color3 from the string containing valid hexadecimal values.
  317. */
  318. Color3.FromHexString = function (hex) {
  319. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  320. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  321. return new Color3(0, 0, 0);
  322. }
  323. var r = parseInt(hex.substring(1, 3), 16);
  324. var g = parseInt(hex.substring(3, 5), 16);
  325. var b = parseInt(hex.substring(5, 7), 16);
  326. return Color3.FromInts(r, g, b);
  327. };
  328. /**
  329. * Creates a new Vector3 from the startind index of the passed array.
  330. */
  331. Color3.FromArray = function (array, offset) {
  332. if (offset === void 0) { offset = 0; }
  333. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  334. };
  335. /**
  336. * Creates a new Color3 from integer values ( < 256).
  337. */
  338. Color3.FromInts = function (r, g, b) {
  339. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  340. };
  341. /**
  342. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  343. */
  344. Color3.Lerp = function (start, end, amount) {
  345. var r = start.r + ((end.r - start.r) * amount);
  346. var g = start.g + ((end.g - start.g) * amount);
  347. var b = start.b + ((end.b - start.b) * amount);
  348. return new Color3(r, g, b);
  349. };
  350. Color3.Red = function () { return new Color3(1, 0, 0); };
  351. Color3.Green = function () { return new Color3(0, 1, 0); };
  352. Color3.Blue = function () { return new Color3(0, 0, 1); };
  353. Color3.Black = function () { return new Color3(0, 0, 0); };
  354. Color3.White = function () { return new Color3(1, 1, 1); };
  355. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  356. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  357. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  358. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  359. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  360. return Color3;
  361. }());
  362. BABYLON.Color3 = Color3;
  363. var Color4 = (function () {
  364. /**
  365. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  366. */
  367. function Color4(r, g, b, a) {
  368. this.r = r;
  369. this.g = g;
  370. this.b = b;
  371. this.a = a;
  372. }
  373. // Operators
  374. /**
  375. * Adds in place the passed Color4 values to the current Color4.
  376. * Returns the updated Color4.
  377. */
  378. Color4.prototype.addInPlace = function (right) {
  379. this.r += right.r;
  380. this.g += right.g;
  381. this.b += right.b;
  382. this.a += right.a;
  383. return this;
  384. };
  385. /**
  386. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  387. */
  388. Color4.prototype.asArray = function () {
  389. var result = [];
  390. this.toArray(result, 0);
  391. return result;
  392. };
  393. /**
  394. * Stores from the starting index in the passed array the Color4 successive values.
  395. * Returns the Color4.
  396. */
  397. Color4.prototype.toArray = function (array, index) {
  398. if (index === undefined) {
  399. index = 0;
  400. }
  401. array[index] = this.r;
  402. array[index + 1] = this.g;
  403. array[index + 2] = this.b;
  404. array[index + 3] = this.a;
  405. return this;
  406. };
  407. /**
  408. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  409. */
  410. Color4.prototype.add = function (right) {
  411. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  412. };
  413. /**
  414. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  415. */
  416. Color4.prototype.subtract = function (right) {
  417. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  418. };
  419. /**
  420. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  421. * Returns the Color4.
  422. */
  423. Color4.prototype.subtractToRef = function (right, result) {
  424. result.r = this.r - right.r;
  425. result.g = this.g - right.g;
  426. result.b = this.b - right.b;
  427. result.a = this.a - right.a;
  428. return this;
  429. };
  430. /**
  431. * Creates a new Color4 with the current Color4 values multiplied by scale.
  432. */
  433. Color4.prototype.scale = function (scale) {
  434. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  435. };
  436. /**
  437. * Multiplies the current Color4 values by scale and stores the result in "result".
  438. * Returns the Color4.
  439. */
  440. Color4.prototype.scaleToRef = function (scale, result) {
  441. result.r = this.r * scale;
  442. result.g = this.g * scale;
  443. result.b = this.b * scale;
  444. result.a = this.a * scale;
  445. return this;
  446. };
  447. /**
  448. * Multipy an RGBA Color4 value by another and return a new Color4 object
  449. * @param color The Color4 (RGBA) value to multiply by
  450. * @returns A new Color4.
  451. */
  452. Color4.prototype.multiply = function (color) {
  453. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  454. };
  455. /**
  456. * Multipy an RGBA Color4 value by another and push the result in a reference value
  457. * @param color The Color4 (RGBA) value to multiply by
  458. * @param result The Color4 (RGBA) to fill the result in
  459. * @returns the result Color4.
  460. */
  461. Color4.prototype.multiplyToRef = function (color, result) {
  462. result.r = this.r * color.r;
  463. result.g = this.g * color.g;
  464. result.b = this.b * color.b;
  465. result.a = this.a * color.a;
  466. return result;
  467. };
  468. /**
  469. * Returns a string with the Color4 values.
  470. */
  471. Color4.prototype.toString = function () {
  472. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  473. };
  474. /**
  475. * Returns the string "Color4"
  476. */
  477. Color4.prototype.getClassName = function () {
  478. return "Color4";
  479. };
  480. /**
  481. * Return the Color4 hash code as a number.
  482. */
  483. Color4.prototype.getHashCode = function () {
  484. var hash = this.r || 0;
  485. hash = (hash * 397) ^ (this.g || 0);
  486. hash = (hash * 397) ^ (this.b || 0);
  487. hash = (hash * 397) ^ (this.a || 0);
  488. return hash;
  489. };
  490. /**
  491. * Creates a new Color4 copied from the current one.
  492. */
  493. Color4.prototype.clone = function () {
  494. return new Color4(this.r, this.g, this.b, this.a);
  495. };
  496. /**
  497. * Copies the passed Color4 values into the current one.
  498. * Returns the updated Color4.
  499. */
  500. Color4.prototype.copyFrom = function (source) {
  501. this.r = source.r;
  502. this.g = source.g;
  503. this.b = source.b;
  504. this.a = source.a;
  505. return this;
  506. };
  507. /**
  508. * Copies the passed float values into the current one.
  509. * Returns the updated Color4.
  510. */
  511. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  512. this.r = r;
  513. this.g = g;
  514. this.b = b;
  515. this.a = a;
  516. return this;
  517. };
  518. /**
  519. * Copies the passed float values into the current one.
  520. * Returns the updated Color4.
  521. */
  522. Color4.prototype.set = function (r, g, b, a) {
  523. return this.copyFromFloats(r, g, b, a);
  524. };
  525. /**
  526. * Returns a string containing the hexadecimal Color4 code.
  527. */
  528. Color4.prototype.toHexString = function () {
  529. var intR = (this.r * 255) | 0;
  530. var intG = (this.g * 255) | 0;
  531. var intB = (this.b * 255) | 0;
  532. var intA = (this.a * 255) | 0;
  533. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  534. };
  535. // Statics
  536. /**
  537. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  538. */
  539. Color4.FromHexString = function (hex) {
  540. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  541. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  542. return new Color4(0.0, 0.0, 0.0, 0.0);
  543. }
  544. var r = parseInt(hex.substring(1, 3), 16);
  545. var g = parseInt(hex.substring(3, 5), 16);
  546. var b = parseInt(hex.substring(5, 7), 16);
  547. var a = parseInt(hex.substring(7, 9), 16);
  548. return Color4.FromInts(r, g, b, a);
  549. };
  550. /**
  551. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  552. */
  553. Color4.Lerp = function (left, right, amount) {
  554. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  555. Color4.LerpToRef(left, right, amount, result);
  556. return result;
  557. };
  558. /**
  559. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  560. */
  561. Color4.LerpToRef = function (left, right, amount, result) {
  562. result.r = left.r + (right.r - left.r) * amount;
  563. result.g = left.g + (right.g - left.g) * amount;
  564. result.b = left.b + (right.b - left.b) * amount;
  565. result.a = left.a + (right.a - left.a) * amount;
  566. };
  567. /**
  568. * Creates a new Color4 from the starting index element of the passed array.
  569. */
  570. Color4.FromArray = function (array, offset) {
  571. if (offset === void 0) { offset = 0; }
  572. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  573. };
  574. /**
  575. * Creates a new Color4 from the passed integers ( < 256 ).
  576. */
  577. Color4.FromInts = function (r, g, b, a) {
  578. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  579. };
  580. Color4.CheckColors4 = function (colors, count) {
  581. // Check if color3 was used
  582. if (colors.length === count * 3) {
  583. var colors4 = [];
  584. for (var index = 0; index < colors.length; index += 3) {
  585. var newIndex = (index / 3) * 4;
  586. colors4[newIndex] = colors[index];
  587. colors4[newIndex + 1] = colors[index + 1];
  588. colors4[newIndex + 2] = colors[index + 2];
  589. colors4[newIndex + 3] = 1.0;
  590. }
  591. return colors4;
  592. }
  593. return colors;
  594. };
  595. return Color4;
  596. }());
  597. BABYLON.Color4 = Color4;
  598. var Vector2 = (function () {
  599. /**
  600. * Creates a new Vector2 from the passed x and y coordinates.
  601. */
  602. function Vector2(x, y) {
  603. this.x = x;
  604. this.y = y;
  605. }
  606. /**
  607. * Returns a string with the Vector2 coordinates.
  608. */
  609. Vector2.prototype.toString = function () {
  610. return "{X: " + this.x + " Y:" + this.y + "}";
  611. };
  612. /**
  613. * Returns the string "Vector2"
  614. */
  615. Vector2.prototype.getClassName = function () {
  616. return "Vector2";
  617. };
  618. /**
  619. * Returns the Vector2 hash code as a number.
  620. */
  621. Vector2.prototype.getHashCode = function () {
  622. var hash = this.x || 0;
  623. hash = (hash * 397) ^ (this.y || 0);
  624. return hash;
  625. };
  626. // Operators
  627. /**
  628. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  629. * Returns the Vector2.
  630. */
  631. Vector2.prototype.toArray = function (array, index) {
  632. if (index === void 0) { index = 0; }
  633. array[index] = this.x;
  634. array[index + 1] = this.y;
  635. return this;
  636. };
  637. /**
  638. * Returns a new array with 2 elements : the Vector2 coordinates.
  639. */
  640. Vector2.prototype.asArray = function () {
  641. var result = [];
  642. this.toArray(result, 0);
  643. return result;
  644. };
  645. /**
  646. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  647. * Returns the updated Vector2.
  648. */
  649. Vector2.prototype.copyFrom = function (source) {
  650. this.x = source.x;
  651. this.y = source.y;
  652. return this;
  653. };
  654. /**
  655. * Sets the Vector2 coordinates with the passed floats.
  656. * Returns the updated Vector2.
  657. */
  658. Vector2.prototype.copyFromFloats = function (x, y) {
  659. this.x = x;
  660. this.y = y;
  661. return this;
  662. };
  663. /**
  664. * Sets the Vector2 coordinates with the passed floats.
  665. * Returns the updated Vector2.
  666. */
  667. Vector2.prototype.set = function (x, y) {
  668. return this.copyFromFloats(x, y);
  669. };
  670. /**
  671. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  672. */
  673. Vector2.prototype.add = function (otherVector) {
  674. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  675. };
  676. /**
  677. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  678. * Returns the Vector2.
  679. */
  680. Vector2.prototype.addToRef = function (otherVector, result) {
  681. result.x = this.x + otherVector.x;
  682. result.y = this.y + otherVector.y;
  683. return this;
  684. };
  685. /**
  686. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  687. * Returns the updated Vector2.
  688. */
  689. Vector2.prototype.addInPlace = function (otherVector) {
  690. this.x += otherVector.x;
  691. this.y += otherVector.y;
  692. return this;
  693. };
  694. /**
  695. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  696. */
  697. Vector2.prototype.addVector3 = function (otherVector) {
  698. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  699. };
  700. /**
  701. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  702. */
  703. Vector2.prototype.subtract = function (otherVector) {
  704. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  705. };
  706. /**
  707. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  708. * Returns the Vector2.
  709. */
  710. Vector2.prototype.subtractToRef = function (otherVector, result) {
  711. result.x = this.x - otherVector.x;
  712. result.y = this.y - otherVector.y;
  713. return this;
  714. };
  715. /**
  716. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  717. * Returns the updated Vector2.
  718. */
  719. Vector2.prototype.subtractInPlace = function (otherVector) {
  720. this.x -= otherVector.x;
  721. this.y -= otherVector.y;
  722. return this;
  723. };
  724. /**
  725. * Multiplies in place the current Vector2 coordinates by the passed ones.
  726. * Returns the updated Vector2.
  727. */
  728. Vector2.prototype.multiplyInPlace = function (otherVector) {
  729. this.x *= otherVector.x;
  730. this.y *= otherVector.y;
  731. return this;
  732. };
  733. /**
  734. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  735. */
  736. Vector2.prototype.multiply = function (otherVector) {
  737. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  738. };
  739. /**
  740. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  741. * Returns the Vector2.
  742. */
  743. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  744. result.x = this.x * otherVector.x;
  745. result.y = this.y * otherVector.y;
  746. return this;
  747. };
  748. /**
  749. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  750. */
  751. Vector2.prototype.multiplyByFloats = function (x, y) {
  752. return new Vector2(this.x * x, this.y * y);
  753. };
  754. /**
  755. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  756. */
  757. Vector2.prototype.divide = function (otherVector) {
  758. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  759. };
  760. /**
  761. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  762. * Returns the Vector2.
  763. */
  764. Vector2.prototype.divideToRef = function (otherVector, result) {
  765. result.x = this.x / otherVector.x;
  766. result.y = this.y / otherVector.y;
  767. return this;
  768. };
  769. /**
  770. * Returns a new Vector2 with current Vector2 negated coordinates.
  771. */
  772. Vector2.prototype.negate = function () {
  773. return new Vector2(-this.x, -this.y);
  774. };
  775. /**
  776. * Multiply the Vector2 coordinates by scale.
  777. * Returns the updated Vector2.
  778. */
  779. Vector2.prototype.scaleInPlace = function (scale) {
  780. this.x *= scale;
  781. this.y *= scale;
  782. return this;
  783. };
  784. /**
  785. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  786. */
  787. Vector2.prototype.scale = function (scale) {
  788. return new Vector2(this.x * scale, this.y * scale);
  789. };
  790. /**
  791. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  792. */
  793. Vector2.prototype.equals = function (otherVector) {
  794. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  795. };
  796. /**
  797. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  798. */
  799. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  800. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  801. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  802. };
  803. // Properties
  804. /**
  805. * Returns the vector length (float).
  806. */
  807. Vector2.prototype.length = function () {
  808. return Math.sqrt(this.x * this.x + this.y * this.y);
  809. };
  810. /**
  811. * Returns the vector squared length (float);
  812. */
  813. Vector2.prototype.lengthSquared = function () {
  814. return (this.x * this.x + this.y * this.y);
  815. };
  816. // Methods
  817. /**
  818. * Normalize the vector.
  819. * Returns the updated Vector2.
  820. */
  821. Vector2.prototype.normalize = function () {
  822. var len = this.length();
  823. if (len === 0)
  824. return this;
  825. var num = 1.0 / len;
  826. this.x *= num;
  827. this.y *= num;
  828. return this;
  829. };
  830. /**
  831. * Returns a new Vector2 copied from the Vector2.
  832. */
  833. Vector2.prototype.clone = function () {
  834. return new Vector2(this.x, this.y);
  835. };
  836. // Statics
  837. /**
  838. * Returns a new Vector2(0, 0)
  839. */
  840. Vector2.Zero = function () {
  841. return new Vector2(0, 0);
  842. };
  843. /**
  844. * Returns a new Vector2 set from the passed index element of the passed array.
  845. */
  846. Vector2.FromArray = function (array, offset) {
  847. if (offset === void 0) { offset = 0; }
  848. return new Vector2(array[offset], array[offset + 1]);
  849. };
  850. /**
  851. * Sets "result" from the passed index element of the passed array.
  852. */
  853. Vector2.FromArrayToRef = function (array, offset, result) {
  854. result.x = array[offset];
  855. result.y = array[offset + 1];
  856. };
  857. /**
  858. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  859. */
  860. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  861. var squared = amount * amount;
  862. var cubed = amount * squared;
  863. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  864. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  865. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  866. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  867. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  868. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  869. return new Vector2(x, y);
  870. };
  871. /**
  872. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  873. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  874. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  875. */
  876. Vector2.Clamp = function (value, min, max) {
  877. var x = value.x;
  878. x = (x > max.x) ? max.x : x;
  879. x = (x < min.x) ? min.x : x;
  880. var y = value.y;
  881. y = (y > max.y) ? max.y : y;
  882. y = (y < min.y) ? min.y : y;
  883. return new Vector2(x, y);
  884. };
  885. /**
  886. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  887. */
  888. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  889. var squared = amount * amount;
  890. var cubed = amount * squared;
  891. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  892. var part2 = (-2.0 * cubed) + (3.0 * squared);
  893. var part3 = (cubed - (2.0 * squared)) + amount;
  894. var part4 = cubed - squared;
  895. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  896. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  897. return new Vector2(x, y);
  898. };
  899. /**
  900. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  901. */
  902. Vector2.Lerp = function (start, end, amount) {
  903. var x = start.x + ((end.x - start.x) * amount);
  904. var y = start.y + ((end.y - start.y) * amount);
  905. return new Vector2(x, y);
  906. };
  907. /**
  908. * Returns the dot product (float) of the vector "left" and the vector "right".
  909. */
  910. Vector2.Dot = function (left, right) {
  911. return left.x * right.x + left.y * right.y;
  912. };
  913. /**
  914. * Returns a new Vector2 equal to the normalized passed vector.
  915. */
  916. Vector2.Normalize = function (vector) {
  917. var newVector = vector.clone();
  918. newVector.normalize();
  919. return newVector;
  920. };
  921. /**
  922. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  923. */
  924. Vector2.Minimize = function (left, right) {
  925. var x = (left.x < right.x) ? left.x : right.x;
  926. var y = (left.y < right.y) ? left.y : right.y;
  927. return new Vector2(x, y);
  928. };
  929. /**
  930. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  931. */
  932. Vector2.Maximize = function (left, right) {
  933. var x = (left.x > right.x) ? left.x : right.x;
  934. var y = (left.y > right.y) ? left.y : right.y;
  935. return new Vector2(x, y);
  936. };
  937. /**
  938. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  939. */
  940. Vector2.Transform = function (vector, transformation) {
  941. var r = Vector2.Zero();
  942. Vector2.TransformToRef(vector, transformation, r);
  943. return r;
  944. };
  945. /**
  946. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  947. */
  948. Vector2.TransformToRef = function (vector, transformation, result) {
  949. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  950. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  951. result.x = x;
  952. result.y = y;
  953. };
  954. /**
  955. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  956. */
  957. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  958. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  959. var sign = a < 0 ? -1 : 1;
  960. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  961. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  962. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  963. };
  964. /**
  965. * Returns the distance (float) between the vectors "value1" and "value2".
  966. */
  967. Vector2.Distance = function (value1, value2) {
  968. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  969. };
  970. /**
  971. * Returns the squared distance (float) between the vectors "value1" and "value2".
  972. */
  973. Vector2.DistanceSquared = function (value1, value2) {
  974. var x = value1.x - value2.x;
  975. var y = value1.y - value2.y;
  976. return (x * x) + (y * y);
  977. };
  978. /**
  979. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  980. */
  981. Vector2.Center = function (value1, value2) {
  982. var center = value1.add(value2);
  983. center.scaleInPlace(0.5);
  984. return center;
  985. };
  986. /**
  987. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  988. */
  989. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  990. var l2 = Vector2.DistanceSquared(segA, segB);
  991. if (l2 === 0.0) {
  992. return Vector2.Distance(p, segA);
  993. }
  994. var v = segB.subtract(segA);
  995. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  996. var proj = segA.add(v.multiplyByFloats(t, t));
  997. return Vector2.Distance(p, proj);
  998. };
  999. return Vector2;
  1000. }());
  1001. BABYLON.Vector2 = Vector2;
  1002. var Vector3 = (function () {
  1003. /**
  1004. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1005. * A Vector3 is the main object used in 3D geometry.
  1006. * It can represent etiher the coordinates of a point the space, either a direction.
  1007. */
  1008. function Vector3(x, y, z) {
  1009. this.x = x;
  1010. this.y = y;
  1011. this.z = z;
  1012. }
  1013. /**
  1014. * Returns a string with the Vector3 coordinates.
  1015. */
  1016. Vector3.prototype.toString = function () {
  1017. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1018. };
  1019. /**
  1020. * Returns the string "Vector3"
  1021. */
  1022. Vector3.prototype.getClassName = function () {
  1023. return "Vector3";
  1024. };
  1025. /**
  1026. * Returns the Vector hash code.
  1027. */
  1028. Vector3.prototype.getHashCode = function () {
  1029. var hash = this.x || 0;
  1030. hash = (hash * 397) ^ (this.y || 0);
  1031. hash = (hash * 397) ^ (this.z || 0);
  1032. return hash;
  1033. };
  1034. // Operators
  1035. /**
  1036. * Returns a new array with three elements : the coordinates the Vector3.
  1037. */
  1038. Vector3.prototype.asArray = function () {
  1039. var result = [];
  1040. this.toArray(result, 0);
  1041. return result;
  1042. };
  1043. /**
  1044. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1045. * Returns the Vector3.
  1046. */
  1047. Vector3.prototype.toArray = function (array, index) {
  1048. if (index === void 0) { index = 0; }
  1049. array[index] = this.x;
  1050. array[index + 1] = this.y;
  1051. array[index + 2] = this.z;
  1052. return this;
  1053. };
  1054. /**
  1055. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1056. */
  1057. Vector3.prototype.toQuaternion = function () {
  1058. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1059. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1060. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1061. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1062. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1063. var cosy = Math.cos(this.y * 0.5);
  1064. var siny = Math.sin(this.y * 0.5);
  1065. result.x = coszMinusx * siny;
  1066. result.y = -sinzMinusx * siny;
  1067. result.z = sinxPlusz * cosy;
  1068. result.w = cosxPlusz * cosy;
  1069. return result;
  1070. };
  1071. /**
  1072. * Adds the passed vector to the current Vector3.
  1073. * Returns the updated Vector3.
  1074. */
  1075. Vector3.prototype.addInPlace = function (otherVector) {
  1076. this.x += otherVector.x;
  1077. this.y += otherVector.y;
  1078. this.z += otherVector.z;
  1079. return this;
  1080. };
  1081. /**
  1082. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1083. */
  1084. Vector3.prototype.add = function (otherVector) {
  1085. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1086. };
  1087. /**
  1088. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1089. * Returns the current Vector3.
  1090. */
  1091. Vector3.prototype.addToRef = function (otherVector, result) {
  1092. result.x = this.x + otherVector.x;
  1093. result.y = this.y + otherVector.y;
  1094. result.z = this.z + otherVector.z;
  1095. return this;
  1096. };
  1097. /**
  1098. * Subtract the passed vector from the current Vector3.
  1099. * Returns the updated Vector3.
  1100. */
  1101. Vector3.prototype.subtractInPlace = function (otherVector) {
  1102. this.x -= otherVector.x;
  1103. this.y -= otherVector.y;
  1104. this.z -= otherVector.z;
  1105. return this;
  1106. };
  1107. /**
  1108. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1109. */
  1110. Vector3.prototype.subtract = function (otherVector) {
  1111. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1112. };
  1113. /**
  1114. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1115. * Returns the current Vector3.
  1116. */
  1117. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1118. result.x = this.x - otherVector.x;
  1119. result.y = this.y - otherVector.y;
  1120. result.z = this.z - otherVector.z;
  1121. return this;
  1122. };
  1123. /**
  1124. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1125. */
  1126. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1127. return new Vector3(this.x - x, this.y - y, this.z - z);
  1128. };
  1129. /**
  1130. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1131. * Returns the current Vector3.
  1132. */
  1133. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1134. result.x = this.x - x;
  1135. result.y = this.y - y;
  1136. result.z = this.z - z;
  1137. return this;
  1138. };
  1139. /**
  1140. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1141. */
  1142. Vector3.prototype.negate = function () {
  1143. return new Vector3(-this.x, -this.y, -this.z);
  1144. };
  1145. /**
  1146. * Multiplies the Vector3 coordinates by the float "scale".
  1147. * Returns the updated Vector3.
  1148. */
  1149. Vector3.prototype.scaleInPlace = function (scale) {
  1150. this.x *= scale;
  1151. this.y *= scale;
  1152. this.z *= scale;
  1153. return this;
  1154. };
  1155. /**
  1156. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1157. */
  1158. Vector3.prototype.scale = function (scale) {
  1159. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1160. };
  1161. /**
  1162. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1163. * Returns the current Vector3.
  1164. */
  1165. Vector3.prototype.scaleToRef = function (scale, result) {
  1166. result.x = this.x * scale;
  1167. result.y = this.y * scale;
  1168. result.z = this.z * scale;
  1169. return this;
  1170. };
  1171. /**
  1172. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1173. */
  1174. Vector3.prototype.equals = function (otherVector) {
  1175. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1176. };
  1177. /**
  1178. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1179. */
  1180. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1181. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1182. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  1183. };
  1184. /**
  1185. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1186. */
  1187. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1188. return this.x === x && this.y === y && this.z === z;
  1189. };
  1190. /**
  1191. * Muliplies the current Vector3 coordinates by the passed ones.
  1192. * Returns the updated Vector3.
  1193. */
  1194. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1195. this.x *= otherVector.x;
  1196. this.y *= otherVector.y;
  1197. this.z *= otherVector.z;
  1198. return this;
  1199. };
  1200. /**
  1201. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1202. */
  1203. Vector3.prototype.multiply = function (otherVector) {
  1204. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1205. };
  1206. /**
  1207. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1208. * Returns the current Vector3.
  1209. */
  1210. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1211. result.x = this.x * otherVector.x;
  1212. result.y = this.y * otherVector.y;
  1213. result.z = this.z * otherVector.z;
  1214. return this;
  1215. };
  1216. /**
  1217. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1218. */
  1219. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1220. return new Vector3(this.x * x, this.y * y, this.z * z);
  1221. };
  1222. /**
  1223. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1224. */
  1225. Vector3.prototype.divide = function (otherVector) {
  1226. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1227. };
  1228. /**
  1229. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1230. * Returns the current Vector3.
  1231. */
  1232. Vector3.prototype.divideToRef = function (otherVector, result) {
  1233. result.x = this.x / otherVector.x;
  1234. result.y = this.y / otherVector.y;
  1235. result.z = this.z / otherVector.z;
  1236. return this;
  1237. };
  1238. /**
  1239. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1240. * Returns the updated Vector3.
  1241. */
  1242. Vector3.prototype.MinimizeInPlace = function (other) {
  1243. if (other.x < this.x)
  1244. this.x = other.x;
  1245. if (other.y < this.y)
  1246. this.y = other.y;
  1247. if (other.z < this.z)
  1248. this.z = other.z;
  1249. return this;
  1250. };
  1251. /**
  1252. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1253. * Returns the updated Vector3.
  1254. */
  1255. Vector3.prototype.MaximizeInPlace = function (other) {
  1256. if (other.x > this.x)
  1257. this.x = other.x;
  1258. if (other.y > this.y)
  1259. this.y = other.y;
  1260. if (other.z > this.z)
  1261. this.z = other.z;
  1262. return this;
  1263. };
  1264. // Properties
  1265. /**
  1266. * Returns the length of the Vector3 (float).
  1267. */
  1268. Vector3.prototype.length = function () {
  1269. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1270. };
  1271. /**
  1272. * Returns the squared length of the Vector3 (float).
  1273. */
  1274. Vector3.prototype.lengthSquared = function () {
  1275. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1276. };
  1277. // Methods
  1278. /**
  1279. * Normalize the current Vector3.
  1280. * Returns the updated Vector3.
  1281. */
  1282. Vector3.prototype.normalize = function () {
  1283. var len = this.length();
  1284. if (len === 0 || len === 1.0)
  1285. return this;
  1286. var num = 1.0 / len;
  1287. this.x *= num;
  1288. this.y *= num;
  1289. this.z *= num;
  1290. return this;
  1291. };
  1292. /**
  1293. * Returns a new Vector3 copied from the current Vector3.
  1294. */
  1295. Vector3.prototype.clone = function () {
  1296. return new Vector3(this.x, this.y, this.z);
  1297. };
  1298. /**
  1299. * Copies the passed vector coordinates to the current Vector3 ones.
  1300. * Returns the updated Vector3.
  1301. */
  1302. Vector3.prototype.copyFrom = function (source) {
  1303. this.x = source.x;
  1304. this.y = source.y;
  1305. this.z = source.z;
  1306. return this;
  1307. };
  1308. /**
  1309. * Copies the passed floats to the current Vector3 coordinates.
  1310. * Returns the updated Vector3.
  1311. */
  1312. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1313. this.x = x;
  1314. this.y = y;
  1315. this.z = z;
  1316. return this;
  1317. };
  1318. /**
  1319. * Copies the passed floats to the current Vector3 coordinates.
  1320. * Returns the updated Vector3.
  1321. */
  1322. Vector3.prototype.set = function (x, y, z) {
  1323. return this.copyFromFloats(x, y, z);
  1324. };
  1325. // Statics
  1326. /**
  1327. *
  1328. */
  1329. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1330. var d0 = Vector3.Dot(vector0, axis) - size;
  1331. var d1 = Vector3.Dot(vector1, axis) - size;
  1332. var s = d0 / (d0 - d1);
  1333. return s;
  1334. };
  1335. /**
  1336. * Returns a new Vector3 set from the index "offset" of the passed array.
  1337. */
  1338. Vector3.FromArray = function (array, offset) {
  1339. if (!offset) {
  1340. offset = 0;
  1341. }
  1342. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1343. };
  1344. /**
  1345. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1346. * This function is deprecated. Use FromArray instead.
  1347. */
  1348. Vector3.FromFloatArray = function (array, offset) {
  1349. return Vector3.FromArray(array, offset);
  1350. };
  1351. /**
  1352. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1353. */
  1354. Vector3.FromArrayToRef = function (array, offset, result) {
  1355. result.x = array[offset];
  1356. result.y = array[offset + 1];
  1357. result.z = array[offset + 2];
  1358. };
  1359. /**
  1360. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1361. * This function is deprecated. Use FromArrayToRef instead.
  1362. */
  1363. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1364. return Vector3.FromArrayToRef(array, offset, result);
  1365. };
  1366. /**
  1367. * Sets the passed vector "result" with the passed floats.
  1368. */
  1369. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1370. result.x = x;
  1371. result.y = y;
  1372. result.z = z;
  1373. };
  1374. /**
  1375. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1376. */
  1377. Vector3.Zero = function () {
  1378. return new Vector3(0.0, 0.0, 0.0);
  1379. };
  1380. /**
  1381. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1382. */
  1383. Vector3.Up = function () {
  1384. return new Vector3(0.0, 1.0, 0.0);
  1385. };
  1386. /**
  1387. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1388. */
  1389. Vector3.Forward = function () {
  1390. return new Vector3(0.0, 0.0, 1.0);
  1391. };
  1392. /**
  1393. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1394. */
  1395. Vector3.Right = function () {
  1396. return new Vector3(1.0, 0.0, 0.0);
  1397. };
  1398. /**
  1399. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1400. */
  1401. Vector3.Left = function () {
  1402. return new Vector3(-1.0, 0.0, 0.0);
  1403. };
  1404. /**
  1405. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1406. * This method computes tranformed coordinates only, not transformed direction vectors.
  1407. */
  1408. Vector3.TransformCoordinates = function (vector, transformation) {
  1409. var result = Vector3.Zero();
  1410. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1411. return result;
  1412. };
  1413. /**
  1414. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1415. * This method computes tranformed coordinates only, not transformed direction vectors.
  1416. */
  1417. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1418. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1419. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1420. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1421. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1422. result.x = x / w;
  1423. result.y = y / w;
  1424. result.z = z / w;
  1425. };
  1426. /**
  1427. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1428. * This method computes tranformed coordinates only, not transformed direction vectors.
  1429. */
  1430. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1431. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1432. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1433. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1434. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1435. result.x = rx / rw;
  1436. result.y = ry / rw;
  1437. result.z = rz / rw;
  1438. };
  1439. /**
  1440. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1441. * This methods computes transformed normalized direction vectors only.
  1442. */
  1443. Vector3.TransformNormal = function (vector, transformation) {
  1444. var result = Vector3.Zero();
  1445. Vector3.TransformNormalToRef(vector, transformation, result);
  1446. return result;
  1447. };
  1448. /**
  1449. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1450. * This methods computes transformed normalized direction vectors only.
  1451. */
  1452. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1453. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1454. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1455. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1456. result.x = x;
  1457. result.y = y;
  1458. result.z = z;
  1459. };
  1460. /**
  1461. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1462. * This methods computes transformed normalized direction vectors only.
  1463. */
  1464. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1465. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1466. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1467. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1468. };
  1469. /**
  1470. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1471. */
  1472. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1473. var squared = amount * amount;
  1474. var cubed = amount * squared;
  1475. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1476. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1477. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1478. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1479. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1480. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1481. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1482. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1483. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1484. return new Vector3(x, y, z);
  1485. };
  1486. /**
  1487. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max".
  1488. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1489. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1490. */
  1491. Vector3.Clamp = function (value, min, max) {
  1492. var x = value.x;
  1493. x = (x > max.x) ? max.x : x;
  1494. x = (x < min.x) ? min.x : x;
  1495. var y = value.y;
  1496. y = (y > max.y) ? max.y : y;
  1497. y = (y < min.y) ? min.y : y;
  1498. var z = value.z;
  1499. z = (z > max.z) ? max.z : z;
  1500. z = (z < min.z) ? min.z : z;
  1501. return new Vector3(x, y, z);
  1502. };
  1503. /**
  1504. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1505. */
  1506. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1507. var squared = amount * amount;
  1508. var cubed = amount * squared;
  1509. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1510. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1511. var part3 = (cubed - (2.0 * squared)) + amount;
  1512. var part4 = cubed - squared;
  1513. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1514. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1515. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1516. return new Vector3(x, y, z);
  1517. };
  1518. /**
  1519. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1520. */
  1521. Vector3.Lerp = function (start, end, amount) {
  1522. var result = new Vector3(0, 0, 0);
  1523. Vector3.LerpToRef(start, end, amount, result);
  1524. return result;
  1525. };
  1526. /**
  1527. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1528. */
  1529. Vector3.LerpToRef = function (start, end, amount, result) {
  1530. result.x = start.x + ((end.x - start.x) * amount);
  1531. result.y = start.y + ((end.y - start.y) * amount);
  1532. result.z = start.z + ((end.z - start.z) * amount);
  1533. };
  1534. /**
  1535. * Returns the dot product (float) between the vectors "left" and "right".
  1536. */
  1537. Vector3.Dot = function (left, right) {
  1538. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1539. };
  1540. /**
  1541. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1542. * The cross product is then orthogonal to both "left" and "right".
  1543. */
  1544. Vector3.Cross = function (left, right) {
  1545. var result = Vector3.Zero();
  1546. Vector3.CrossToRef(left, right, result);
  1547. return result;
  1548. };
  1549. /**
  1550. * Sets the passed vector "result" with the cross product of "left" and "right".
  1551. * The cross product is then orthogonal to both "left" and "right".
  1552. */
  1553. Vector3.CrossToRef = function (left, right, result) {
  1554. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1555. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1556. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1557. result.copyFrom(MathTmp.Vector3[0]);
  1558. };
  1559. /**
  1560. * Returns a new Vector3 as the normalization of the passed vector.
  1561. */
  1562. Vector3.Normalize = function (vector) {
  1563. var result = Vector3.Zero();
  1564. Vector3.NormalizeToRef(vector, result);
  1565. return result;
  1566. };
  1567. /**
  1568. * Sets the passed vector "result" with the normalization of the passed first vector.
  1569. */
  1570. Vector3.NormalizeToRef = function (vector, result) {
  1571. result.copyFrom(vector);
  1572. result.normalize();
  1573. };
  1574. Vector3.Project = function (vector, world, transform, viewport) {
  1575. var cw = viewport.width;
  1576. var ch = viewport.height;
  1577. var cx = viewport.x;
  1578. var cy = viewport.y;
  1579. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1580. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  1581. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1582. world.multiplyToRef(transform, matrix);
  1583. matrix.multiplyToRef(viewportMatrix, matrix);
  1584. return Vector3.TransformCoordinates(vector, matrix);
  1585. };
  1586. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1587. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1588. world.multiplyToRef(transform, matrix);
  1589. matrix.invert();
  1590. source.x = source.x / viewportWidth * 2 - 1;
  1591. source.y = -(source.y / viewportHeight * 2 - 1);
  1592. var vector = Vector3.TransformCoordinates(source, matrix);
  1593. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1594. if (MathTools.WithinEpsilon(num, 1.0)) {
  1595. vector = vector.scale(1.0 / num);
  1596. }
  1597. return vector;
  1598. };
  1599. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1600. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1601. world.multiplyToRef(view, matrix);
  1602. matrix.multiplyToRef(projection, matrix);
  1603. matrix.invert();
  1604. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1605. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1606. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1607. if (MathTools.WithinEpsilon(num, 1.0)) {
  1608. vector = vector.scale(1.0 / num);
  1609. }
  1610. return vector;
  1611. };
  1612. Vector3.Minimize = function (left, right) {
  1613. var min = left.clone();
  1614. min.MinimizeInPlace(right);
  1615. return min;
  1616. };
  1617. Vector3.Maximize = function (left, right) {
  1618. var max = left.clone();
  1619. max.MaximizeInPlace(right);
  1620. return max;
  1621. };
  1622. /**
  1623. * Returns the distance (float) between the vectors "value1" and "value2".
  1624. */
  1625. Vector3.Distance = function (value1, value2) {
  1626. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1627. };
  1628. /**
  1629. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1630. */
  1631. Vector3.DistanceSquared = function (value1, value2) {
  1632. var x = value1.x - value2.x;
  1633. var y = value1.y - value2.y;
  1634. var z = value1.z - value2.z;
  1635. return (x * x) + (y * y) + (z * z);
  1636. };
  1637. /**
  1638. * Returns a new Vector3 located at the center between "value1" and "value2".
  1639. */
  1640. Vector3.Center = function (value1, value2) {
  1641. var center = value1.add(value2);
  1642. center.scaleInPlace(0.5);
  1643. return center;
  1644. };
  1645. /**
  1646. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1647. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1648. * to something in order to rotate it from its local system to the given target system.
  1649. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1650. * Returns a new Vector3.
  1651. */
  1652. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1653. var rotation = Vector3.Zero();
  1654. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1655. return rotation;
  1656. };
  1657. /**
  1658. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1659. */
  1660. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1661. var quat = MathTmp.Quaternion[0];
  1662. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1663. quat.toEulerAnglesToRef(ref);
  1664. };
  1665. return Vector3;
  1666. }());
  1667. BABYLON.Vector3 = Vector3;
  1668. //Vector4 class created for EulerAngle class conversion to Quaternion
  1669. var Vector4 = (function () {
  1670. /**
  1671. * Creates a Vector4 object from the passed floats.
  1672. */
  1673. function Vector4(x, y, z, w) {
  1674. this.x = x;
  1675. this.y = y;
  1676. this.z = z;
  1677. this.w = w;
  1678. }
  1679. /**
  1680. * Returns the string with the Vector4 coordinates.
  1681. */
  1682. Vector4.prototype.toString = function () {
  1683. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1684. };
  1685. /**
  1686. * Returns the string "Vector4".
  1687. */
  1688. Vector4.prototype.getClassName = function () {
  1689. return "Vector4";
  1690. };
  1691. /**
  1692. * Returns the Vector4 hash code.
  1693. */
  1694. Vector4.prototype.getHashCode = function () {
  1695. var hash = this.x || 0;
  1696. hash = (hash * 397) ^ (this.y || 0);
  1697. hash = (hash * 397) ^ (this.z || 0);
  1698. hash = (hash * 397) ^ (this.w || 0);
  1699. return hash;
  1700. };
  1701. // Operators
  1702. /**
  1703. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1704. */
  1705. Vector4.prototype.asArray = function () {
  1706. var result = [];
  1707. this.toArray(result, 0);
  1708. return result;
  1709. };
  1710. /**
  1711. * Populates the passed array from the passed index with the Vector4 coordinates.
  1712. * Returns the Vector4.
  1713. */
  1714. Vector4.prototype.toArray = function (array, index) {
  1715. if (index === undefined) {
  1716. index = 0;
  1717. }
  1718. array[index] = this.x;
  1719. array[index + 1] = this.y;
  1720. array[index + 2] = this.z;
  1721. array[index + 3] = this.w;
  1722. return this;
  1723. };
  1724. /**
  1725. * Adds the passed vector to the current Vector4.
  1726. * Returns the updated Vector4.
  1727. */
  1728. Vector4.prototype.addInPlace = function (otherVector) {
  1729. this.x += otherVector.x;
  1730. this.y += otherVector.y;
  1731. this.z += otherVector.z;
  1732. this.w += otherVector.w;
  1733. return this;
  1734. };
  1735. /**
  1736. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1737. */
  1738. Vector4.prototype.add = function (otherVector) {
  1739. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1740. };
  1741. /**
  1742. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1743. * Returns the current Vector4.
  1744. */
  1745. Vector4.prototype.addToRef = function (otherVector, result) {
  1746. result.x = this.x + otherVector.x;
  1747. result.y = this.y + otherVector.y;
  1748. result.z = this.z + otherVector.z;
  1749. result.w = this.w + otherVector.w;
  1750. return this;
  1751. };
  1752. /**
  1753. * Subtract in place the passed vector from the current Vector4.
  1754. * Returns the updated Vector4.
  1755. */
  1756. Vector4.prototype.subtractInPlace = function (otherVector) {
  1757. this.x -= otherVector.x;
  1758. this.y -= otherVector.y;
  1759. this.z -= otherVector.z;
  1760. this.w -= otherVector.w;
  1761. return this;
  1762. };
  1763. /**
  1764. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1765. */
  1766. Vector4.prototype.subtract = function (otherVector) {
  1767. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1768. };
  1769. /**
  1770. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1771. * Returns the current Vector4.
  1772. */
  1773. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1774. result.x = this.x - otherVector.x;
  1775. result.y = this.y - otherVector.y;
  1776. result.z = this.z - otherVector.z;
  1777. result.w = this.w - otherVector.w;
  1778. return this;
  1779. };
  1780. /**
  1781. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1782. */
  1783. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1784. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1785. };
  1786. /**
  1787. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1788. * Returns the current Vector4.
  1789. */
  1790. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1791. result.x = this.x - x;
  1792. result.y = this.y - y;
  1793. result.z = this.z - z;
  1794. result.w = this.w - w;
  1795. return this;
  1796. };
  1797. /**
  1798. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1799. */
  1800. Vector4.prototype.negate = function () {
  1801. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1802. };
  1803. /**
  1804. * Multiplies the current Vector4 coordinates by scale (float).
  1805. * Returns the updated Vector4.
  1806. */
  1807. Vector4.prototype.scaleInPlace = function (scale) {
  1808. this.x *= scale;
  1809. this.y *= scale;
  1810. this.z *= scale;
  1811. this.w *= scale;
  1812. return this;
  1813. };
  1814. /**
  1815. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1816. */
  1817. Vector4.prototype.scale = function (scale) {
  1818. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1819. };
  1820. /**
  1821. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1822. * Returns the current Vector4.
  1823. */
  1824. Vector4.prototype.scaleToRef = function (scale, result) {
  1825. result.x = this.x * scale;
  1826. result.y = this.y * scale;
  1827. result.z = this.z * scale;
  1828. result.w = this.w * scale;
  1829. return this;
  1830. };
  1831. /**
  1832. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1833. */
  1834. Vector4.prototype.equals = function (otherVector) {
  1835. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1836. };
  1837. /**
  1838. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1839. */
  1840. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1841. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1842. return otherVector
  1843. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1844. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1845. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1846. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1847. };
  1848. /**
  1849. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1850. */
  1851. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1852. return this.x === x && this.y === y && this.z === z && this.w === w;
  1853. };
  1854. /**
  1855. * Multiplies in place the current Vector4 by the passed one.
  1856. * Returns the updated Vector4.
  1857. */
  1858. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1859. this.x *= otherVector.x;
  1860. this.y *= otherVector.y;
  1861. this.z *= otherVector.z;
  1862. this.w *= otherVector.w;
  1863. return this;
  1864. };
  1865. /**
  1866. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1867. */
  1868. Vector4.prototype.multiply = function (otherVector) {
  1869. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1870. };
  1871. /**
  1872. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1873. * Returns the current Vector4.
  1874. */
  1875. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1876. result.x = this.x * otherVector.x;
  1877. result.y = this.y * otherVector.y;
  1878. result.z = this.z * otherVector.z;
  1879. result.w = this.w * otherVector.w;
  1880. return this;
  1881. };
  1882. /**
  1883. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1884. */
  1885. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1886. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1887. };
  1888. /**
  1889. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1890. */
  1891. Vector4.prototype.divide = function (otherVector) {
  1892. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1893. };
  1894. /**
  1895. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1896. * Returns the current Vector4.
  1897. */
  1898. Vector4.prototype.divideToRef = function (otherVector, result) {
  1899. result.x = this.x / otherVector.x;
  1900. result.y = this.y / otherVector.y;
  1901. result.z = this.z / otherVector.z;
  1902. result.w = this.w / otherVector.w;
  1903. return this;
  1904. };
  1905. /**
  1906. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1907. */
  1908. Vector4.prototype.MinimizeInPlace = function (other) {
  1909. if (other.x < this.x)
  1910. this.x = other.x;
  1911. if (other.y < this.y)
  1912. this.y = other.y;
  1913. if (other.z < this.z)
  1914. this.z = other.z;
  1915. if (other.w < this.w)
  1916. this.w = other.w;
  1917. return this;
  1918. };
  1919. /**
  1920. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1921. */
  1922. Vector4.prototype.MaximizeInPlace = function (other) {
  1923. if (other.x > this.x)
  1924. this.x = other.x;
  1925. if (other.y > this.y)
  1926. this.y = other.y;
  1927. if (other.z > this.z)
  1928. this.z = other.z;
  1929. if (other.w > this.w)
  1930. this.w = other.w;
  1931. return this;
  1932. };
  1933. // Properties
  1934. /**
  1935. * Returns the Vector4 length (float).
  1936. */
  1937. Vector4.prototype.length = function () {
  1938. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1939. };
  1940. /**
  1941. * Returns the Vector4 squared length (float).
  1942. */
  1943. Vector4.prototype.lengthSquared = function () {
  1944. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1945. };
  1946. // Methods
  1947. /**
  1948. * Normalizes in place the Vector4.
  1949. * Returns the updated Vector4.
  1950. */
  1951. Vector4.prototype.normalize = function () {
  1952. var len = this.length();
  1953. if (len === 0)
  1954. return this;
  1955. var num = 1.0 / len;
  1956. this.x *= num;
  1957. this.y *= num;
  1958. this.z *= num;
  1959. this.w *= num;
  1960. return this;
  1961. };
  1962. /**
  1963. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1964. */
  1965. Vector4.prototype.toVector3 = function () {
  1966. return new Vector3(this.x, this.y, this.z);
  1967. };
  1968. /**
  1969. * Returns a new Vector4 copied from the current one.
  1970. */
  1971. Vector4.prototype.clone = function () {
  1972. return new Vector4(this.x, this.y, this.z, this.w);
  1973. };
  1974. /**
  1975. * Updates the current Vector4 with the passed one coordinates.
  1976. * Returns the updated Vector4.
  1977. */
  1978. Vector4.prototype.copyFrom = function (source) {
  1979. this.x = source.x;
  1980. this.y = source.y;
  1981. this.z = source.z;
  1982. this.w = source.w;
  1983. return this;
  1984. };
  1985. /**
  1986. * Updates the current Vector4 coordinates with the passed floats.
  1987. * Returns the updated Vector4.
  1988. */
  1989. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1990. this.x = x;
  1991. this.y = y;
  1992. this.z = z;
  1993. this.w = w;
  1994. return this;
  1995. };
  1996. /**
  1997. * Updates the current Vector4 coordinates with the passed floats.
  1998. * Returns the updated Vector4.
  1999. */
  2000. Vector4.prototype.set = function (x, y, z, w) {
  2001. return this.copyFromFloats(x, y, z, w);
  2002. };
  2003. // Statics
  2004. /**
  2005. * Returns a new Vector4 set from the starting index of the passed array.
  2006. */
  2007. Vector4.FromArray = function (array, offset) {
  2008. if (!offset) {
  2009. offset = 0;
  2010. }
  2011. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2012. };
  2013. /**
  2014. * Updates the passed vector "result" from the starting index of the passed array.
  2015. */
  2016. Vector4.FromArrayToRef = function (array, offset, result) {
  2017. result.x = array[offset];
  2018. result.y = array[offset + 1];
  2019. result.z = array[offset + 2];
  2020. result.w = array[offset + 3];
  2021. };
  2022. /**
  2023. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2024. */
  2025. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2026. Vector4.FromArrayToRef(array, offset, result);
  2027. };
  2028. /**
  2029. * Updates the passed vector "result" coordinates from the passed floats.
  2030. */
  2031. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2032. result.x = x;
  2033. result.y = y;
  2034. result.z = z;
  2035. result.w = w;
  2036. };
  2037. /**
  2038. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2039. */
  2040. Vector4.Zero = function () {
  2041. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2042. };
  2043. /**
  2044. * Returns a new normalized Vector4 from the passed one.
  2045. */
  2046. Vector4.Normalize = function (vector) {
  2047. var result = Vector4.Zero();
  2048. Vector4.NormalizeToRef(vector, result);
  2049. return result;
  2050. };
  2051. /**
  2052. * Updates the passed vector "result" from the normalization of the passed one.
  2053. */
  2054. Vector4.NormalizeToRef = function (vector, result) {
  2055. result.copyFrom(vector);
  2056. result.normalize();
  2057. };
  2058. Vector4.Minimize = function (left, right) {
  2059. var min = left.clone();
  2060. min.MinimizeInPlace(right);
  2061. return min;
  2062. };
  2063. Vector4.Maximize = function (left, right) {
  2064. var max = left.clone();
  2065. max.MaximizeInPlace(right);
  2066. return max;
  2067. };
  2068. /**
  2069. * Returns the distance (float) between the vectors "value1" and "value2".
  2070. */
  2071. Vector4.Distance = function (value1, value2) {
  2072. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2073. };
  2074. /**
  2075. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2076. */
  2077. Vector4.DistanceSquared = function (value1, value2) {
  2078. var x = value1.x - value2.x;
  2079. var y = value1.y - value2.y;
  2080. var z = value1.z - value2.z;
  2081. var w = value1.w - value2.w;
  2082. return (x * x) + (y * y) + (z * z) + (w * w);
  2083. };
  2084. /**
  2085. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2086. */
  2087. Vector4.Center = function (value1, value2) {
  2088. var center = value1.add(value2);
  2089. center.scaleInPlace(0.5);
  2090. return center;
  2091. };
  2092. /**
  2093. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2094. * This methods computes transformed normalized direction vectors only.
  2095. */
  2096. Vector4.TransformNormal = function (vector, transformation) {
  2097. var result = Vector4.Zero();
  2098. Vector4.TransformNormalToRef(vector, transformation, result);
  2099. return result;
  2100. };
  2101. /**
  2102. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2103. * This methods computes transformed normalized direction vectors only.
  2104. */
  2105. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2106. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2107. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2108. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2109. result.x = x;
  2110. result.y = y;
  2111. result.z = z;
  2112. result.w = vector.w;
  2113. };
  2114. /**
  2115. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2116. * This methods computes transformed normalized direction vectors only.
  2117. */
  2118. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2119. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2120. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2121. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2122. result.w = w;
  2123. };
  2124. return Vector4;
  2125. }());
  2126. BABYLON.Vector4 = Vector4;
  2127. var Size = (function () {
  2128. /**
  2129. * Creates a Size object from the passed width and height (floats).
  2130. */
  2131. function Size(width, height) {
  2132. this.width = width;
  2133. this.height = height;
  2134. }
  2135. // Returns a string with the Size width and height.
  2136. Size.prototype.toString = function () {
  2137. return "{W: " + this.width + ", H: " + this.height + "}";
  2138. };
  2139. /**
  2140. * Returns the string "Size"
  2141. */
  2142. Size.prototype.getClassName = function () {
  2143. return "Size";
  2144. };
  2145. /**
  2146. * Returns the Size hash code.
  2147. */
  2148. Size.prototype.getHashCode = function () {
  2149. var hash = this.width || 0;
  2150. hash = (hash * 397) ^ (this.height || 0);
  2151. return hash;
  2152. };
  2153. /**
  2154. * Updates the current size from the passed one.
  2155. * Returns the updated Size.
  2156. */
  2157. Size.prototype.copyFrom = function (src) {
  2158. this.width = src.width;
  2159. this.height = src.height;
  2160. };
  2161. /**
  2162. * Updates in place the current Size from the passed floats.
  2163. * Returns the updated Size.
  2164. */
  2165. Size.prototype.copyFromFloats = function (width, height) {
  2166. this.width = width;
  2167. this.height = height;
  2168. return this;
  2169. };
  2170. /**
  2171. * Updates in place the current Size from the passed floats.
  2172. * Returns the updated Size.
  2173. */
  2174. Size.prototype.set = function (width, height) {
  2175. return this.copyFromFloats(width, height);
  2176. };
  2177. /**
  2178. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2179. */
  2180. Size.prototype.multiplyByFloats = function (w, h) {
  2181. return new Size(this.width * w, this.height * h);
  2182. };
  2183. /**
  2184. * Returns a new Size copied from the passed one.
  2185. */
  2186. Size.prototype.clone = function () {
  2187. return new Size(this.width, this.height);
  2188. };
  2189. /**
  2190. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2191. */
  2192. Size.prototype.equals = function (other) {
  2193. if (!other) {
  2194. return false;
  2195. }
  2196. return (this.width === other.width) && (this.height === other.height);
  2197. };
  2198. Object.defineProperty(Size.prototype, "surface", {
  2199. /**
  2200. * Returns the surface of the Size : width * height (float).
  2201. */
  2202. get: function () {
  2203. return this.width * this.height;
  2204. },
  2205. enumerable: true,
  2206. configurable: true
  2207. });
  2208. /**
  2209. * Returns a new Size set to (0.0, 0.0)
  2210. */
  2211. Size.Zero = function () {
  2212. return new Size(0.0, 0.0);
  2213. };
  2214. /**
  2215. * Returns a new Size set as the addition result of the current Size and the passed one.
  2216. */
  2217. Size.prototype.add = function (otherSize) {
  2218. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2219. return r;
  2220. };
  2221. /**
  2222. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2223. */
  2224. Size.prototype.subtract = function (otherSize) {
  2225. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2226. return r;
  2227. };
  2228. /**
  2229. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2230. */
  2231. Size.Lerp = function (start, end, amount) {
  2232. var w = start.width + ((end.width - start.width) * amount);
  2233. var h = start.height + ((end.height - start.height) * amount);
  2234. return new Size(w, h);
  2235. };
  2236. return Size;
  2237. }());
  2238. BABYLON.Size = Size;
  2239. var Quaternion = (function () {
  2240. /**
  2241. * Creates a new Quaternion from the passed floats.
  2242. */
  2243. function Quaternion(x, y, z, w) {
  2244. if (x === void 0) { x = 0.0; }
  2245. if (y === void 0) { y = 0.0; }
  2246. if (z === void 0) { z = 0.0; }
  2247. if (w === void 0) { w = 1.0; }
  2248. this.x = x;
  2249. this.y = y;
  2250. this.z = z;
  2251. this.w = w;
  2252. }
  2253. /**
  2254. * Returns a string with the Quaternion coordinates.
  2255. */
  2256. Quaternion.prototype.toString = function () {
  2257. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2258. };
  2259. /**
  2260. * Returns the string "Quaternion".
  2261. */
  2262. Quaternion.prototype.getClassName = function () {
  2263. return "Quaternion";
  2264. };
  2265. /**
  2266. * Returns the Quaternion hash code.
  2267. */
  2268. Quaternion.prototype.getHashCode = function () {
  2269. var hash = this.x || 0;
  2270. hash = (hash * 397) ^ (this.y || 0);
  2271. hash = (hash * 397) ^ (this.z || 0);
  2272. hash = (hash * 397) ^ (this.w || 0);
  2273. return hash;
  2274. };
  2275. /**
  2276. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2277. */
  2278. Quaternion.prototype.asArray = function () {
  2279. return [this.x, this.y, this.z, this.w];
  2280. };
  2281. /**
  2282. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2283. */
  2284. Quaternion.prototype.equals = function (otherQuaternion) {
  2285. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2286. };
  2287. /**
  2288. * Returns a new Quaternion copied from the current one.
  2289. */
  2290. Quaternion.prototype.clone = function () {
  2291. return new Quaternion(this.x, this.y, this.z, this.w);
  2292. };
  2293. /**
  2294. * Updates the current Quaternion from the passed one coordinates.
  2295. * Returns the updated Quaterion.
  2296. */
  2297. Quaternion.prototype.copyFrom = function (other) {
  2298. this.x = other.x;
  2299. this.y = other.y;
  2300. this.z = other.z;
  2301. this.w = other.w;
  2302. return this;
  2303. };
  2304. /**
  2305. * Updates the current Quaternion from the passed float coordinates.
  2306. * Returns the updated Quaterion.
  2307. */
  2308. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2309. this.x = x;
  2310. this.y = y;
  2311. this.z = z;
  2312. this.w = w;
  2313. return this;
  2314. };
  2315. /**
  2316. * Updates the current Quaternion from the passed float coordinates.
  2317. * Returns the updated Quaterion.
  2318. */
  2319. Quaternion.prototype.set = function (x, y, z, w) {
  2320. return this.copyFromFloats(x, y, z, w);
  2321. };
  2322. /**
  2323. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2324. */
  2325. Quaternion.prototype.add = function (other) {
  2326. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2327. };
  2328. /**
  2329. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2330. */
  2331. Quaternion.prototype.subtract = function (other) {
  2332. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2333. };
  2334. /**
  2335. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2336. */
  2337. Quaternion.prototype.scale = function (value) {
  2338. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2339. };
  2340. /**
  2341. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2342. */
  2343. Quaternion.prototype.multiply = function (q1) {
  2344. var result = new Quaternion(0, 0, 0, 1.0);
  2345. this.multiplyToRef(q1, result);
  2346. return result;
  2347. };
  2348. /**
  2349. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2350. * Returns the current Quaternion.
  2351. */
  2352. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2353. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2354. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2355. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2356. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2357. result.copyFromFloats(x, y, z, w);
  2358. return this;
  2359. };
  2360. /**
  2361. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2362. * Returns the updated Quaternion.
  2363. */
  2364. Quaternion.prototype.multiplyInPlace = function (q1) {
  2365. this.multiplyToRef(q1, this);
  2366. return this;
  2367. };
  2368. /**
  2369. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2370. * Returns the current Quaternion.
  2371. */
  2372. Quaternion.prototype.conjugateToRef = function (ref) {
  2373. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2374. return this;
  2375. };
  2376. /**
  2377. * Conjugates in place the current Quaternion.
  2378. * Returns the updated Quaternion.
  2379. */
  2380. Quaternion.prototype.conjugateInPlace = function () {
  2381. this.x *= -1;
  2382. this.y *= -1;
  2383. this.z *= -1;
  2384. return this;
  2385. };
  2386. /**
  2387. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2388. */
  2389. Quaternion.prototype.conjugate = function () {
  2390. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2391. return result;
  2392. };
  2393. /**
  2394. * Returns the Quaternion length (float).
  2395. */
  2396. Quaternion.prototype.length = function () {
  2397. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2398. };
  2399. /**
  2400. * Normalize in place the current Quaternion.
  2401. * Returns the updated Quaternion.
  2402. */
  2403. Quaternion.prototype.normalize = function () {
  2404. var length = 1.0 / this.length();
  2405. this.x *= length;
  2406. this.y *= length;
  2407. this.z *= length;
  2408. this.w *= length;
  2409. return this;
  2410. };
  2411. /**
  2412. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2413. */
  2414. Quaternion.prototype.toEulerAngles = function (order) {
  2415. if (order === void 0) { order = "YZX"; }
  2416. var result = Vector3.Zero();
  2417. this.toEulerAnglesToRef(result, order);
  2418. return result;
  2419. };
  2420. /**
  2421. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2422. * Returns the current Quaternion.
  2423. */
  2424. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2425. if (order === void 0) { order = "YZX"; }
  2426. var qz = this.z;
  2427. var qx = this.x;
  2428. var qy = this.y;
  2429. var qw = this.w;
  2430. var sqw = qw * qw;
  2431. var sqz = qz * qz;
  2432. var sqx = qx * qx;
  2433. var sqy = qy * qy;
  2434. var zAxisY = qy * qz - qx * qw;
  2435. var limit = .4999999;
  2436. if (zAxisY < -limit) {
  2437. result.y = 2 * Math.atan2(qy, qw);
  2438. result.x = Math.PI / 2;
  2439. result.z = 0;
  2440. }
  2441. else if (zAxisY > limit) {
  2442. result.y = 2 * Math.atan2(qy, qw);
  2443. result.x = -Math.PI / 2;
  2444. result.z = 0;
  2445. }
  2446. else {
  2447. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2448. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2449. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2450. }
  2451. return this;
  2452. };
  2453. /**
  2454. * Updates the passed rotation matrix with the current Quaternion values.
  2455. * Returns the current Quaternion.
  2456. */
  2457. Quaternion.prototype.toRotationMatrix = function (result) {
  2458. var xx = this.x * this.x;
  2459. var yy = this.y * this.y;
  2460. var zz = this.z * this.z;
  2461. var xy = this.x * this.y;
  2462. var zw = this.z * this.w;
  2463. var zx = this.z * this.x;
  2464. var yw = this.y * this.w;
  2465. var yz = this.y * this.z;
  2466. var xw = this.x * this.w;
  2467. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2468. result.m[1] = 2.0 * (xy + zw);
  2469. result.m[2] = 2.0 * (zx - yw);
  2470. result.m[3] = 0;
  2471. result.m[4] = 2.0 * (xy - zw);
  2472. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2473. result.m[6] = 2.0 * (yz + xw);
  2474. result.m[7] = 0;
  2475. result.m[8] = 2.0 * (zx + yw);
  2476. result.m[9] = 2.0 * (yz - xw);
  2477. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2478. result.m[11] = 0;
  2479. result.m[12] = 0;
  2480. result.m[13] = 0;
  2481. result.m[14] = 0;
  2482. result.m[15] = 1.0;
  2483. result._markAsUpdated();
  2484. return this;
  2485. };
  2486. /**
  2487. * Updates the current Quaternion from the passed rotation matrix values.
  2488. * Returns the updated Quaternion.
  2489. */
  2490. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2491. Quaternion.FromRotationMatrixToRef(matrix, this);
  2492. return this;
  2493. };
  2494. // Statics
  2495. /**
  2496. * Returns a new Quaternion set from the passed rotation matrix values.
  2497. */
  2498. Quaternion.FromRotationMatrix = function (matrix) {
  2499. var result = new Quaternion();
  2500. Quaternion.FromRotationMatrixToRef(matrix, result);
  2501. return result;
  2502. };
  2503. /**
  2504. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2505. */
  2506. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2507. var data = matrix.m;
  2508. var m11 = data[0], m12 = data[4], m13 = data[8];
  2509. var m21 = data[1], m22 = data[5], m23 = data[9];
  2510. var m31 = data[2], m32 = data[6], m33 = data[10];
  2511. var trace = m11 + m22 + m33;
  2512. var s;
  2513. if (trace > 0) {
  2514. s = 0.5 / Math.sqrt(trace + 1.0);
  2515. result.w = 0.25 / s;
  2516. result.x = (m32 - m23) * s;
  2517. result.y = (m13 - m31) * s;
  2518. result.z = (m21 - m12) * s;
  2519. }
  2520. else if (m11 > m22 && m11 > m33) {
  2521. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2522. result.w = (m32 - m23) / s;
  2523. result.x = 0.25 * s;
  2524. result.y = (m12 + m21) / s;
  2525. result.z = (m13 + m31) / s;
  2526. }
  2527. else if (m22 > m33) {
  2528. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2529. result.w = (m13 - m31) / s;
  2530. result.x = (m12 + m21) / s;
  2531. result.y = 0.25 * s;
  2532. result.z = (m23 + m32) / s;
  2533. }
  2534. else {
  2535. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2536. result.w = (m21 - m12) / s;
  2537. result.x = (m13 + m31) / s;
  2538. result.y = (m23 + m32) / s;
  2539. result.z = 0.25 * s;
  2540. }
  2541. };
  2542. /**
  2543. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2544. */
  2545. Quaternion.Zero = function () {
  2546. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2547. };
  2548. /**
  2549. * Returns a new Quaternion as the inverted current Quaternion.
  2550. */
  2551. Quaternion.Inverse = function (q) {
  2552. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2553. };
  2554. /**
  2555. * Returns the identity Quaternion.
  2556. */
  2557. Quaternion.Identity = function () {
  2558. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2559. };
  2560. Quaternion.IsIdentity = function (quaternion) {
  2561. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2562. };
  2563. /**
  2564. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2565. */
  2566. Quaternion.RotationAxis = function (axis, angle) {
  2567. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2568. };
  2569. /**
  2570. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2571. */
  2572. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2573. var sin = Math.sin(angle / 2);
  2574. axis.normalize();
  2575. result.w = Math.cos(angle / 2);
  2576. result.x = axis.x * sin;
  2577. result.y = axis.y * sin;
  2578. result.z = axis.z * sin;
  2579. return result;
  2580. };
  2581. /**
  2582. * Retuns a new Quaternion set from the starting index of the passed array.
  2583. */
  2584. Quaternion.FromArray = function (array, offset) {
  2585. if (!offset) {
  2586. offset = 0;
  2587. }
  2588. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2589. };
  2590. /**
  2591. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2592. */
  2593. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2594. var q = new Quaternion();
  2595. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2596. return q;
  2597. };
  2598. /**
  2599. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2600. */
  2601. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2602. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2603. var halfRoll = roll * 0.5;
  2604. var halfPitch = pitch * 0.5;
  2605. var halfYaw = yaw * 0.5;
  2606. var sinRoll = Math.sin(halfRoll);
  2607. var cosRoll = Math.cos(halfRoll);
  2608. var sinPitch = Math.sin(halfPitch);
  2609. var cosPitch = Math.cos(halfPitch);
  2610. var sinYaw = Math.sin(halfYaw);
  2611. var cosYaw = Math.cos(halfYaw);
  2612. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2613. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2614. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2615. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2616. };
  2617. /**
  2618. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2619. */
  2620. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2621. var result = new Quaternion();
  2622. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2623. return result;
  2624. };
  2625. /**
  2626. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2627. */
  2628. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2629. // Produces a quaternion from Euler angles in the z-x-z orientation
  2630. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2631. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2632. var halfBeta = beta * 0.5;
  2633. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2634. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2635. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2636. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2637. };
  2638. /**
  2639. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2640. * cf to Vector3.RotationFromAxis() documentation.
  2641. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2642. */
  2643. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2644. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2645. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2646. return quat;
  2647. };
  2648. /**
  2649. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2650. * cf to Vector3.RotationFromAxis() documentation.
  2651. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2652. */
  2653. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2654. var rotMat = MathTmp.Matrix[0];
  2655. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2656. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2657. };
  2658. Quaternion.Slerp = function (left, right, amount) {
  2659. var result = Quaternion.Identity();
  2660. Quaternion.SlerpToRef(left, right, amount, result);
  2661. return result;
  2662. };
  2663. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2664. var num2;
  2665. var num3;
  2666. var num = amount;
  2667. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2668. var flag = false;
  2669. if (num4 < 0) {
  2670. flag = true;
  2671. num4 = -num4;
  2672. }
  2673. if (num4 > 0.999999) {
  2674. num3 = 1 - num;
  2675. num2 = flag ? -num : num;
  2676. }
  2677. else {
  2678. var num5 = Math.acos(num4);
  2679. var num6 = (1.0 / Math.sin(num5));
  2680. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2681. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2682. }
  2683. result.x = (num3 * left.x) + (num2 * right.x);
  2684. result.y = (num3 * left.y) + (num2 * right.y);
  2685. result.z = (num3 * left.z) + (num2 * right.z);
  2686. result.w = (num3 * left.w) + (num2 * right.w);
  2687. };
  2688. /**
  2689. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2690. */
  2691. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2692. var squared = amount * amount;
  2693. var cubed = amount * squared;
  2694. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2695. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2696. var part3 = (cubed - (2.0 * squared)) + amount;
  2697. var part4 = cubed - squared;
  2698. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2699. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2700. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2701. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2702. return new Quaternion(x, y, z, w);
  2703. };
  2704. return Quaternion;
  2705. }());
  2706. BABYLON.Quaternion = Quaternion;
  2707. var Matrix = (function () {
  2708. function Matrix() {
  2709. this.m = new Float32Array(16);
  2710. this._markAsUpdated();
  2711. }
  2712. Matrix.prototype._markAsUpdated = function () {
  2713. this.updateFlag = Matrix._updateFlagSeed++;
  2714. };
  2715. // Properties
  2716. /**
  2717. * Boolean : True is the matrix is the identity matrix
  2718. */
  2719. Matrix.prototype.isIdentity = function () {
  2720. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  2721. return false;
  2722. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2723. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2724. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2725. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  2726. return false;
  2727. return true;
  2728. };
  2729. /**
  2730. * Returns the matrix determinant (float).
  2731. */
  2732. Matrix.prototype.determinant = function () {
  2733. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2734. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2735. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2736. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2737. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2738. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2739. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2740. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2741. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2742. };
  2743. // Methods
  2744. /**
  2745. * Returns the matrix underlying array.
  2746. */
  2747. Matrix.prototype.toArray = function () {
  2748. return this.m;
  2749. };
  2750. /**
  2751. * Returns the matrix underlying array.
  2752. */
  2753. Matrix.prototype.asArray = function () {
  2754. return this.toArray();
  2755. };
  2756. /**
  2757. * Inverts in place the Matrix.
  2758. * Returns the Matrix inverted.
  2759. */
  2760. Matrix.prototype.invert = function () {
  2761. this.invertToRef(this);
  2762. return this;
  2763. };
  2764. /**
  2765. * Sets all the matrix elements to zero.
  2766. * Returns the Matrix.
  2767. */
  2768. Matrix.prototype.reset = function () {
  2769. for (var index = 0; index < 16; index++) {
  2770. this.m[index] = 0.0;
  2771. }
  2772. this._markAsUpdated();
  2773. return this;
  2774. };
  2775. /**
  2776. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2777. */
  2778. Matrix.prototype.add = function (other) {
  2779. var result = new Matrix();
  2780. this.addToRef(other, result);
  2781. return result;
  2782. };
  2783. /**
  2784. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2785. * Returns the Matrix.
  2786. */
  2787. Matrix.prototype.addToRef = function (other, result) {
  2788. for (var index = 0; index < 16; index++) {
  2789. result.m[index] = this.m[index] + other.m[index];
  2790. }
  2791. result._markAsUpdated();
  2792. return this;
  2793. };
  2794. /**
  2795. * Adds in place the passed matrix to the current Matrix.
  2796. * Returns the updated Matrix.
  2797. */
  2798. Matrix.prototype.addToSelf = function (other) {
  2799. for (var index = 0; index < 16; index++) {
  2800. this.m[index] += other.m[index];
  2801. }
  2802. this._markAsUpdated();
  2803. return this;
  2804. };
  2805. /**
  2806. * Sets the passed matrix with the current inverted Matrix.
  2807. * Returns the unmodified current Matrix.
  2808. */
  2809. Matrix.prototype.invertToRef = function (other) {
  2810. var l1 = this.m[0];
  2811. var l2 = this.m[1];
  2812. var l3 = this.m[2];
  2813. var l4 = this.m[3];
  2814. var l5 = this.m[4];
  2815. var l6 = this.m[5];
  2816. var l7 = this.m[6];
  2817. var l8 = this.m[7];
  2818. var l9 = this.m[8];
  2819. var l10 = this.m[9];
  2820. var l11 = this.m[10];
  2821. var l12 = this.m[11];
  2822. var l13 = this.m[12];
  2823. var l14 = this.m[13];
  2824. var l15 = this.m[14];
  2825. var l16 = this.m[15];
  2826. var l17 = (l11 * l16) - (l12 * l15);
  2827. var l18 = (l10 * l16) - (l12 * l14);
  2828. var l19 = (l10 * l15) - (l11 * l14);
  2829. var l20 = (l9 * l16) - (l12 * l13);
  2830. var l21 = (l9 * l15) - (l11 * l13);
  2831. var l22 = (l9 * l14) - (l10 * l13);
  2832. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2833. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2834. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2835. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2836. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2837. var l28 = (l7 * l16) - (l8 * l15);
  2838. var l29 = (l6 * l16) - (l8 * l14);
  2839. var l30 = (l6 * l15) - (l7 * l14);
  2840. var l31 = (l5 * l16) - (l8 * l13);
  2841. var l32 = (l5 * l15) - (l7 * l13);
  2842. var l33 = (l5 * l14) - (l6 * l13);
  2843. var l34 = (l7 * l12) - (l8 * l11);
  2844. var l35 = (l6 * l12) - (l8 * l10);
  2845. var l36 = (l6 * l11) - (l7 * l10);
  2846. var l37 = (l5 * l12) - (l8 * l9);
  2847. var l38 = (l5 * l11) - (l7 * l9);
  2848. var l39 = (l5 * l10) - (l6 * l9);
  2849. other.m[0] = l23 * l27;
  2850. other.m[4] = l24 * l27;
  2851. other.m[8] = l25 * l27;
  2852. other.m[12] = l26 * l27;
  2853. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2854. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2855. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2856. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2857. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2858. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2859. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2860. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2861. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2862. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2863. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2864. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2865. other._markAsUpdated();
  2866. return this;
  2867. };
  2868. /**
  2869. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2870. * Returns the updated Matrix.
  2871. */
  2872. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2873. this.m[12] = x;
  2874. this.m[13] = y;
  2875. this.m[14] = z;
  2876. this._markAsUpdated();
  2877. return this;
  2878. };
  2879. /**
  2880. * Inserts the translation vector in the current Matrix.
  2881. * Returns the updated Matrix.
  2882. */
  2883. Matrix.prototype.setTranslation = function (vector3) {
  2884. this.m[12] = vector3.x;
  2885. this.m[13] = vector3.y;
  2886. this.m[14] = vector3.z;
  2887. this._markAsUpdated();
  2888. return this;
  2889. };
  2890. /**
  2891. * Returns a new Vector3 as the extracted translation from the Matrix.
  2892. */
  2893. Matrix.prototype.getTranslation = function () {
  2894. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2895. };
  2896. /**
  2897. * Fill a Vector3 with the extracted translation from the Matrix.
  2898. */
  2899. Matrix.prototype.getTranslationToRef = function (result) {
  2900. result.x = this.m[12];
  2901. result.y = this.m[13];
  2902. result.z = this.m[14];
  2903. return this;
  2904. };
  2905. /**
  2906. * Remove rotation and scaling part from the Matrix.
  2907. * Returns the updated Matrix.
  2908. */
  2909. Matrix.prototype.removeRotationAndScaling = function () {
  2910. this.setRowFromFloats(0, 1, 0, 0, 0);
  2911. this.setRowFromFloats(1, 0, 1, 0, 0);
  2912. this.setRowFromFloats(2, 0, 0, 1, 0);
  2913. return this;
  2914. };
  2915. /**
  2916. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2917. */
  2918. Matrix.prototype.multiply = function (other) {
  2919. var result = new Matrix();
  2920. this.multiplyToRef(other, result);
  2921. return result;
  2922. };
  2923. /**
  2924. * Updates the current Matrix from the passed one values.
  2925. * Returns the updated Matrix.
  2926. */
  2927. Matrix.prototype.copyFrom = function (other) {
  2928. for (var index = 0; index < 16; index++) {
  2929. this.m[index] = other.m[index];
  2930. }
  2931. this._markAsUpdated();
  2932. return this;
  2933. };
  2934. /**
  2935. * Populates the passed array from the starting index with the Matrix values.
  2936. * Returns the Matrix.
  2937. */
  2938. Matrix.prototype.copyToArray = function (array, offset) {
  2939. if (offset === void 0) { offset = 0; }
  2940. for (var index = 0; index < 16; index++) {
  2941. array[offset + index] = this.m[index];
  2942. }
  2943. return this;
  2944. };
  2945. /**
  2946. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2947. */
  2948. Matrix.prototype.multiplyToRef = function (other, result) {
  2949. this.multiplyToArray(other, result.m, 0);
  2950. result._markAsUpdated();
  2951. return this;
  2952. };
  2953. /**
  2954. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2955. */
  2956. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2957. var tm0 = this.m[0];
  2958. var tm1 = this.m[1];
  2959. var tm2 = this.m[2];
  2960. var tm3 = this.m[3];
  2961. var tm4 = this.m[4];
  2962. var tm5 = this.m[5];
  2963. var tm6 = this.m[6];
  2964. var tm7 = this.m[7];
  2965. var tm8 = this.m[8];
  2966. var tm9 = this.m[9];
  2967. var tm10 = this.m[10];
  2968. var tm11 = this.m[11];
  2969. var tm12 = this.m[12];
  2970. var tm13 = this.m[13];
  2971. var tm14 = this.m[14];
  2972. var tm15 = this.m[15];
  2973. var om0 = other.m[0];
  2974. var om1 = other.m[1];
  2975. var om2 = other.m[2];
  2976. var om3 = other.m[3];
  2977. var om4 = other.m[4];
  2978. var om5 = other.m[5];
  2979. var om6 = other.m[6];
  2980. var om7 = other.m[7];
  2981. var om8 = other.m[8];
  2982. var om9 = other.m[9];
  2983. var om10 = other.m[10];
  2984. var om11 = other.m[11];
  2985. var om12 = other.m[12];
  2986. var om13 = other.m[13];
  2987. var om14 = other.m[14];
  2988. var om15 = other.m[15];
  2989. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2990. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2991. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  2992. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  2993. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  2994. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  2995. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  2996. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  2997. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  2998. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  2999. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3000. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3001. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3002. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3003. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3004. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3005. return this;
  3006. };
  3007. /**
  3008. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3009. */
  3010. Matrix.prototype.equals = function (value) {
  3011. return value &&
  3012. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3013. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3014. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3015. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3016. };
  3017. /**
  3018. * Returns a new Matrix from the current Matrix.
  3019. */
  3020. Matrix.prototype.clone = function () {
  3021. 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]);
  3022. };
  3023. /**
  3024. * Returns the string "Matrix"
  3025. */
  3026. Matrix.prototype.getClassName = function () {
  3027. return "Matrix";
  3028. };
  3029. /**
  3030. * Returns the Matrix hash code.
  3031. */
  3032. Matrix.prototype.getHashCode = function () {
  3033. var hash = this.m[0] || 0;
  3034. for (var i = 1; i < 16; i++) {
  3035. hash = (hash * 397) ^ (this.m[i] || 0);
  3036. }
  3037. return hash;
  3038. };
  3039. /**
  3040. * Decomposes the current Matrix into :
  3041. * - a scale vector3 passed as a reference to update,
  3042. * - a rotation quaternion passed as a reference to update,
  3043. * - a translation vector3 passed as a reference to update.
  3044. * Returns the boolean `true`.
  3045. */
  3046. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3047. translation.x = this.m[12];
  3048. translation.y = this.m[13];
  3049. translation.z = this.m[14];
  3050. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  3051. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  3052. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  3053. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3054. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3055. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3056. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3057. rotation.x = 0;
  3058. rotation.y = 0;
  3059. rotation.z = 0;
  3060. rotation.w = 1;
  3061. return false;
  3062. }
  3063. Matrix.FromValuesToRef(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, MathTmp.Matrix[0]);
  3064. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3065. return true;
  3066. };
  3067. /**
  3068. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3069. */
  3070. Matrix.prototype.getRotationMatrix = function () {
  3071. var result = Matrix.Identity();
  3072. this.getRotationMatrixToRef(result);
  3073. return result;
  3074. };
  3075. /**
  3076. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3077. * Returns the current Matrix.
  3078. */
  3079. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3080. var m = this.m;
  3081. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3082. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3083. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3084. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3085. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3086. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3087. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  3088. return this;
  3089. };
  3090. // Statics
  3091. /**
  3092. * Returns a new Matrix set from the starting index of the passed array.
  3093. */
  3094. Matrix.FromArray = function (array, offset) {
  3095. var result = new Matrix();
  3096. if (!offset) {
  3097. offset = 0;
  3098. }
  3099. Matrix.FromArrayToRef(array, offset, result);
  3100. return result;
  3101. };
  3102. /**
  3103. * Sets the passed "result" matrix from the starting index of the passed array.
  3104. */
  3105. Matrix.FromArrayToRef = function (array, offset, result) {
  3106. for (var index = 0; index < 16; index++) {
  3107. result.m[index] = array[index + offset];
  3108. }
  3109. result._markAsUpdated();
  3110. };
  3111. /**
  3112. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3113. */
  3114. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3115. for (var index = 0; index < 16; index++) {
  3116. result.m[index] = array[index + offset] * scale;
  3117. }
  3118. result._markAsUpdated();
  3119. };
  3120. /**
  3121. * Sets the passed matrix "result" with the 16 passed floats.
  3122. */
  3123. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3124. result.m[0] = initialM11;
  3125. result.m[1] = initialM12;
  3126. result.m[2] = initialM13;
  3127. result.m[3] = initialM14;
  3128. result.m[4] = initialM21;
  3129. result.m[5] = initialM22;
  3130. result.m[6] = initialM23;
  3131. result.m[7] = initialM24;
  3132. result.m[8] = initialM31;
  3133. result.m[9] = initialM32;
  3134. result.m[10] = initialM33;
  3135. result.m[11] = initialM34;
  3136. result.m[12] = initialM41;
  3137. result.m[13] = initialM42;
  3138. result.m[14] = initialM43;
  3139. result.m[15] = initialM44;
  3140. result._markAsUpdated();
  3141. };
  3142. /**
  3143. * Returns the index-th row of the current matrix as a new Vector4.
  3144. */
  3145. Matrix.prototype.getRow = function (index) {
  3146. if (index < 0 || index > 3) {
  3147. return null;
  3148. }
  3149. var i = index * 4;
  3150. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3151. };
  3152. /**
  3153. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3154. * Returns the updated Matrix.
  3155. */
  3156. Matrix.prototype.setRow = function (index, row) {
  3157. if (index < 0 || index > 3) {
  3158. return this;
  3159. }
  3160. var i = index * 4;
  3161. this.m[i + 0] = row.x;
  3162. this.m[i + 1] = row.y;
  3163. this.m[i + 2] = row.z;
  3164. this.m[i + 3] = row.w;
  3165. this._markAsUpdated();
  3166. return this;
  3167. };
  3168. /**
  3169. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3170. * Returns the updated Matrix.
  3171. */
  3172. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3173. if (index < 0 || index > 3) {
  3174. return this;
  3175. }
  3176. var i = index * 4;
  3177. this.m[i + 0] = x;
  3178. this.m[i + 1] = y;
  3179. this.m[i + 2] = z;
  3180. this.m[i + 3] = w;
  3181. this._markAsUpdated();
  3182. return this;
  3183. };
  3184. /**
  3185. * Returns a new Matrix set from the 16 passed floats.
  3186. */
  3187. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3188. var result = new Matrix();
  3189. result.m[0] = initialM11;
  3190. result.m[1] = initialM12;
  3191. result.m[2] = initialM13;
  3192. result.m[3] = initialM14;
  3193. result.m[4] = initialM21;
  3194. result.m[5] = initialM22;
  3195. result.m[6] = initialM23;
  3196. result.m[7] = initialM24;
  3197. result.m[8] = initialM31;
  3198. result.m[9] = initialM32;
  3199. result.m[10] = initialM33;
  3200. result.m[11] = initialM34;
  3201. result.m[12] = initialM41;
  3202. result.m[13] = initialM42;
  3203. result.m[14] = initialM43;
  3204. result.m[15] = initialM44;
  3205. return result;
  3206. };
  3207. /**
  3208. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3209. */
  3210. Matrix.Compose = function (scale, rotation, translation) {
  3211. var result = Matrix.Identity();
  3212. Matrix.ComposeToRef(scale, rotation, translation, result);
  3213. return result;
  3214. };
  3215. /**
  3216. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3217. */
  3218. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3219. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3220. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3221. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3222. result.setTranslation(translation);
  3223. };
  3224. /**
  3225. * Returns a new indentity Matrix.
  3226. */
  3227. Matrix.Identity = function () {
  3228. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  3229. };
  3230. /**
  3231. * Sets the passed "result" as an identity matrix.
  3232. */
  3233. Matrix.IdentityToRef = function (result) {
  3234. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  3235. };
  3236. /**
  3237. * Returns a new zero Matrix.
  3238. */
  3239. Matrix.Zero = function () {
  3240. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  3241. };
  3242. /**
  3243. * Returns a new rotation matrix for "angle" radians around the X axis.
  3244. */
  3245. Matrix.RotationX = function (angle) {
  3246. var result = new Matrix();
  3247. Matrix.RotationXToRef(angle, result);
  3248. return result;
  3249. };
  3250. /**
  3251. * Returns a new Matrix as the passed inverted one.
  3252. */
  3253. Matrix.Invert = function (source) {
  3254. var result = new Matrix();
  3255. source.invertToRef(result);
  3256. return result;
  3257. };
  3258. /**
  3259. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3260. */
  3261. Matrix.RotationXToRef = function (angle, result) {
  3262. var s = Math.sin(angle);
  3263. var c = Math.cos(angle);
  3264. result.m[0] = 1.0;
  3265. result.m[15] = 1.0;
  3266. result.m[5] = c;
  3267. result.m[10] = c;
  3268. result.m[9] = -s;
  3269. result.m[6] = s;
  3270. result.m[1] = 0.0;
  3271. result.m[2] = 0.0;
  3272. result.m[3] = 0.0;
  3273. result.m[4] = 0.0;
  3274. result.m[7] = 0.0;
  3275. result.m[8] = 0.0;
  3276. result.m[11] = 0.0;
  3277. result.m[12] = 0.0;
  3278. result.m[13] = 0.0;
  3279. result.m[14] = 0.0;
  3280. result._markAsUpdated();
  3281. };
  3282. /**
  3283. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3284. */
  3285. Matrix.RotationY = function (angle) {
  3286. var result = new Matrix();
  3287. Matrix.RotationYToRef(angle, result);
  3288. return result;
  3289. };
  3290. /**
  3291. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3292. */
  3293. Matrix.RotationYToRef = function (angle, result) {
  3294. var s = Math.sin(angle);
  3295. var c = Math.cos(angle);
  3296. result.m[5] = 1.0;
  3297. result.m[15] = 1.0;
  3298. result.m[0] = c;
  3299. result.m[2] = -s;
  3300. result.m[8] = s;
  3301. result.m[10] = c;
  3302. result.m[1] = 0.0;
  3303. result.m[3] = 0.0;
  3304. result.m[4] = 0.0;
  3305. result.m[6] = 0.0;
  3306. result.m[7] = 0.0;
  3307. result.m[9] = 0.0;
  3308. result.m[11] = 0.0;
  3309. result.m[12] = 0.0;
  3310. result.m[13] = 0.0;
  3311. result.m[14] = 0.0;
  3312. result._markAsUpdated();
  3313. };
  3314. /**
  3315. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3316. */
  3317. Matrix.RotationZ = function (angle) {
  3318. var result = new Matrix();
  3319. Matrix.RotationZToRef(angle, result);
  3320. return result;
  3321. };
  3322. /**
  3323. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3324. */
  3325. Matrix.RotationZToRef = function (angle, result) {
  3326. var s = Math.sin(angle);
  3327. var c = Math.cos(angle);
  3328. result.m[10] = 1.0;
  3329. result.m[15] = 1.0;
  3330. result.m[0] = c;
  3331. result.m[1] = s;
  3332. result.m[4] = -s;
  3333. result.m[5] = c;
  3334. result.m[2] = 0.0;
  3335. result.m[3] = 0.0;
  3336. result.m[6] = 0.0;
  3337. result.m[7] = 0.0;
  3338. result.m[8] = 0.0;
  3339. result.m[9] = 0.0;
  3340. result.m[11] = 0.0;
  3341. result.m[12] = 0.0;
  3342. result.m[13] = 0.0;
  3343. result.m[14] = 0.0;
  3344. result._markAsUpdated();
  3345. };
  3346. /**
  3347. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3348. */
  3349. Matrix.RotationAxis = function (axis, angle) {
  3350. var result = Matrix.Zero();
  3351. Matrix.RotationAxisToRef(axis, angle, result);
  3352. return result;
  3353. };
  3354. /**
  3355. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3356. */
  3357. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3358. var s = Math.sin(-angle);
  3359. var c = Math.cos(-angle);
  3360. var c1 = 1 - c;
  3361. axis.normalize();
  3362. result.m[0] = (axis.x * axis.x) * c1 + c;
  3363. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3364. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3365. result.m[3] = 0.0;
  3366. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3367. result.m[5] = (axis.y * axis.y) * c1 + c;
  3368. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3369. result.m[7] = 0.0;
  3370. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3371. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3372. result.m[10] = (axis.z * axis.z) * c1 + c;
  3373. result.m[11] = 0.0;
  3374. result.m[15] = 1.0;
  3375. result._markAsUpdated();
  3376. };
  3377. /**
  3378. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3379. */
  3380. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3381. var result = new Matrix();
  3382. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3383. return result;
  3384. };
  3385. /**
  3386. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3387. */
  3388. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3389. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3390. this._tempQuaternion.toRotationMatrix(result);
  3391. };
  3392. /**
  3393. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3394. */
  3395. Matrix.Scaling = function (x, y, z) {
  3396. var result = Matrix.Zero();
  3397. Matrix.ScalingToRef(x, y, z, result);
  3398. return result;
  3399. };
  3400. /**
  3401. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3402. */
  3403. Matrix.ScalingToRef = function (x, y, z, result) {
  3404. result.m[0] = x;
  3405. result.m[1] = 0.0;
  3406. result.m[2] = 0.0;
  3407. result.m[3] = 0.0;
  3408. result.m[4] = 0.0;
  3409. result.m[5] = y;
  3410. result.m[6] = 0.0;
  3411. result.m[7] = 0.0;
  3412. result.m[8] = 0.0;
  3413. result.m[9] = 0.0;
  3414. result.m[10] = z;
  3415. result.m[11] = 0.0;
  3416. result.m[12] = 0.0;
  3417. result.m[13] = 0.0;
  3418. result.m[14] = 0.0;
  3419. result.m[15] = 1.0;
  3420. result._markAsUpdated();
  3421. };
  3422. /**
  3423. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3424. */
  3425. Matrix.Translation = function (x, y, z) {
  3426. var result = Matrix.Identity();
  3427. Matrix.TranslationToRef(x, y, z, result);
  3428. return result;
  3429. };
  3430. /**
  3431. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3432. */
  3433. Matrix.TranslationToRef = function (x, y, z, result) {
  3434. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  3435. };
  3436. /**
  3437. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3438. */
  3439. Matrix.Lerp = function (startValue, endValue, gradient) {
  3440. var result = Matrix.Zero();
  3441. for (var index = 0; index < 16; index++) {
  3442. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3443. }
  3444. result._markAsUpdated();
  3445. return result;
  3446. };
  3447. /**
  3448. * Returns a new Matrix whose values are computed by :
  3449. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3450. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3451. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3452. */
  3453. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3454. var startScale = new Vector3(0, 0, 0);
  3455. var startRotation = new Quaternion();
  3456. var startTranslation = new Vector3(0, 0, 0);
  3457. startValue.decompose(startScale, startRotation, startTranslation);
  3458. var endScale = new Vector3(0, 0, 0);
  3459. var endRotation = new Quaternion();
  3460. var endTranslation = new Vector3(0, 0, 0);
  3461. endValue.decompose(endScale, endRotation, endTranslation);
  3462. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3463. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3464. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3465. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3466. };
  3467. /**
  3468. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3469. * This methods works for a Left-Handed system.
  3470. */
  3471. Matrix.LookAtLH = function (eye, target, up) {
  3472. var result = Matrix.Zero();
  3473. Matrix.LookAtLHToRef(eye, target, up, result);
  3474. return result;
  3475. };
  3476. /**
  3477. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3478. * This methods works for a Left-Handed system.
  3479. */
  3480. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3481. // Z axis
  3482. target.subtractToRef(eye, this._zAxis);
  3483. this._zAxis.normalize();
  3484. // X axis
  3485. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3486. if (this._xAxis.lengthSquared() === 0) {
  3487. this._xAxis.x = 1.0;
  3488. }
  3489. else {
  3490. this._xAxis.normalize();
  3491. }
  3492. // Y axis
  3493. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3494. this._yAxis.normalize();
  3495. // Eye angles
  3496. var ex = -Vector3.Dot(this._xAxis, eye);
  3497. var ey = -Vector3.Dot(this._yAxis, eye);
  3498. var ez = -Vector3.Dot(this._zAxis, eye);
  3499. 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);
  3500. };
  3501. /**
  3502. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3503. * This methods works for a Right-Handed system.
  3504. */
  3505. Matrix.LookAtRH = function (eye, target, up) {
  3506. var result = Matrix.Zero();
  3507. Matrix.LookAtRHToRef(eye, target, up, result);
  3508. return result;
  3509. };
  3510. /**
  3511. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3512. * This methods works for a Left-Handed system.
  3513. */
  3514. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3515. // Z axis
  3516. eye.subtractToRef(target, this._zAxis);
  3517. this._zAxis.normalize();
  3518. // X axis
  3519. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3520. if (this._xAxis.lengthSquared() === 0) {
  3521. this._xAxis.x = 1.0;
  3522. }
  3523. else {
  3524. this._xAxis.normalize();
  3525. }
  3526. // Y axis
  3527. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3528. this._yAxis.normalize();
  3529. // Eye angles
  3530. var ex = -Vector3.Dot(this._xAxis, eye);
  3531. var ey = -Vector3.Dot(this._yAxis, eye);
  3532. var ez = -Vector3.Dot(this._zAxis, eye);
  3533. 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);
  3534. };
  3535. /**
  3536. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3537. */
  3538. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3539. var matrix = Matrix.Zero();
  3540. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3541. return matrix;
  3542. };
  3543. /**
  3544. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3545. */
  3546. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3547. var n = znear;
  3548. var f = zfar;
  3549. var a = 2.0 / width;
  3550. var b = 2.0 / height;
  3551. var c = 2.0 / (f - n);
  3552. var d = -(f + n) / (f - n);
  3553. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  3554. };
  3555. /**
  3556. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3557. */
  3558. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3559. var matrix = Matrix.Zero();
  3560. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3561. return matrix;
  3562. };
  3563. /**
  3564. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3565. */
  3566. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3567. var n = znear;
  3568. var f = zfar;
  3569. var a = 2.0 / (right - left);
  3570. var b = 2.0 / (top - bottom);
  3571. var c = 2.0 / (f - n);
  3572. var d = -(f + n) / (f - n);
  3573. var i0 = (left + right) / (left - right);
  3574. var i1 = (top + bottom) / (bottom - top);
  3575. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  3576. };
  3577. /**
  3578. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3579. */
  3580. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3581. var matrix = Matrix.Zero();
  3582. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3583. return matrix;
  3584. };
  3585. /**
  3586. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3587. */
  3588. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3589. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3590. result.m[10] *= -1.0;
  3591. };
  3592. /**
  3593. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3594. */
  3595. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3596. var matrix = Matrix.Zero();
  3597. var n = znear;
  3598. var f = zfar;
  3599. var a = 2.0 * n / width;
  3600. var b = 2.0 * n / height;
  3601. var c = (f + n) / (f - n);
  3602. var d = -2.0 * f * n / (f - n);
  3603. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  3604. return matrix;
  3605. };
  3606. /**
  3607. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3608. */
  3609. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3610. var matrix = Matrix.Zero();
  3611. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3612. return matrix;
  3613. };
  3614. /**
  3615. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3616. */
  3617. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3618. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3619. var n = znear;
  3620. var f = zfar;
  3621. var t = 1.0 / (Math.tan(fov * 0.5));
  3622. var a = isVerticalFovFixed ? (t / aspect) : t;
  3623. var b = isVerticalFovFixed ? t : (t * aspect);
  3624. var c = (f + n) / (f - n);
  3625. var d = -2.0 * f * n / (f - n);
  3626. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  3627. };
  3628. /**
  3629. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3630. */
  3631. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3632. var matrix = Matrix.Zero();
  3633. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3634. return matrix;
  3635. };
  3636. /**
  3637. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3638. */
  3639. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3640. //alternatively this could be expressed as:
  3641. // m = PerspectiveFovLHToRef
  3642. // m[10] *= -1.0;
  3643. // m[11] *= -1.0;
  3644. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3645. var n = znear;
  3646. var f = zfar;
  3647. var t = 1.0 / (Math.tan(fov * 0.5));
  3648. var a = isVerticalFovFixed ? (t / aspect) : t;
  3649. var b = isVerticalFovFixed ? t : (t * aspect);
  3650. var c = -(f + n) / (f - n);
  3651. var d = -2 * f * n / (f - n);
  3652. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3653. };
  3654. /**
  3655. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3656. */
  3657. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3658. if (rightHanded === void 0) { rightHanded = false; }
  3659. var rightHandedFactor = rightHanded ? -1 : 1;
  3660. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3661. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3662. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3663. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3664. var xScale = 2.0 / (leftTan + rightTan);
  3665. var yScale = 2.0 / (upTan + downTan);
  3666. result.m[0] = xScale;
  3667. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3668. result.m[5] = yScale;
  3669. result.m[6] = result.m[7] = 0.0;
  3670. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3671. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3672. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3673. result.m[10] = -zfar / (znear - zfar);
  3674. result.m[11] = 1.0 * rightHandedFactor;
  3675. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3676. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3677. // result.m[14] = (znear * zfar) / (znear - zfar);
  3678. result._markAsUpdated();
  3679. };
  3680. /**
  3681. * Returns the final transformation matrix : world * view * projection * viewport
  3682. */
  3683. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3684. var cw = viewport.width;
  3685. var ch = viewport.height;
  3686. var cx = viewport.x;
  3687. var cy = viewport.y;
  3688. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  3689. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3690. };
  3691. /**
  3692. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3693. */
  3694. Matrix.GetAsMatrix2x2 = function (matrix) {
  3695. return new Float32Array([
  3696. matrix.m[0], matrix.m[1],
  3697. matrix.m[4], matrix.m[5]
  3698. ]);
  3699. };
  3700. /**
  3701. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3702. */
  3703. Matrix.GetAsMatrix3x3 = function (matrix) {
  3704. return new Float32Array([
  3705. matrix.m[0], matrix.m[1], matrix.m[2],
  3706. matrix.m[4], matrix.m[5], matrix.m[6],
  3707. matrix.m[8], matrix.m[9], matrix.m[10]
  3708. ]);
  3709. };
  3710. /**
  3711. * Compute the transpose of the passed Matrix.
  3712. * Returns a new Matrix.
  3713. */
  3714. Matrix.Transpose = function (matrix) {
  3715. var result = new Matrix();
  3716. result.m[0] = matrix.m[0];
  3717. result.m[1] = matrix.m[4];
  3718. result.m[2] = matrix.m[8];
  3719. result.m[3] = matrix.m[12];
  3720. result.m[4] = matrix.m[1];
  3721. result.m[5] = matrix.m[5];
  3722. result.m[6] = matrix.m[9];
  3723. result.m[7] = matrix.m[13];
  3724. result.m[8] = matrix.m[2];
  3725. result.m[9] = matrix.m[6];
  3726. result.m[10] = matrix.m[10];
  3727. result.m[11] = matrix.m[14];
  3728. result.m[12] = matrix.m[3];
  3729. result.m[13] = matrix.m[7];
  3730. result.m[14] = matrix.m[11];
  3731. result.m[15] = matrix.m[15];
  3732. return result;
  3733. };
  3734. /**
  3735. * Returns a new Matrix as the reflection matrix across the passed plane.
  3736. */
  3737. Matrix.Reflection = function (plane) {
  3738. var matrix = new Matrix();
  3739. Matrix.ReflectionToRef(plane, matrix);
  3740. return matrix;
  3741. };
  3742. /**
  3743. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3744. */
  3745. Matrix.ReflectionToRef = function (plane, result) {
  3746. plane.normalize();
  3747. var x = plane.normal.x;
  3748. var y = plane.normal.y;
  3749. var z = plane.normal.z;
  3750. var temp = -2 * x;
  3751. var temp2 = -2 * y;
  3752. var temp3 = -2 * z;
  3753. result.m[0] = (temp * x) + 1;
  3754. result.m[1] = temp2 * x;
  3755. result.m[2] = temp3 * x;
  3756. result.m[3] = 0.0;
  3757. result.m[4] = temp * y;
  3758. result.m[5] = (temp2 * y) + 1;
  3759. result.m[6] = temp3 * y;
  3760. result.m[7] = 0.0;
  3761. result.m[8] = temp * z;
  3762. result.m[9] = temp2 * z;
  3763. result.m[10] = (temp3 * z) + 1;
  3764. result.m[11] = 0.0;
  3765. result.m[12] = temp * plane.d;
  3766. result.m[13] = temp2 * plane.d;
  3767. result.m[14] = temp3 * plane.d;
  3768. result.m[15] = 1.0;
  3769. result._markAsUpdated();
  3770. };
  3771. /**
  3772. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3773. */
  3774. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3775. result.m[0] = xaxis.x;
  3776. result.m[1] = xaxis.y;
  3777. result.m[2] = xaxis.z;
  3778. result.m[3] = 0.0;
  3779. result.m[4] = yaxis.x;
  3780. result.m[5] = yaxis.y;
  3781. result.m[6] = yaxis.z;
  3782. result.m[7] = 0.0;
  3783. result.m[8] = zaxis.x;
  3784. result.m[9] = zaxis.y;
  3785. result.m[10] = zaxis.z;
  3786. result.m[11] = 0.0;
  3787. result.m[12] = 0.0;
  3788. result.m[13] = 0.0;
  3789. result.m[14] = 0.0;
  3790. result.m[15] = 1.0;
  3791. result._markAsUpdated();
  3792. };
  3793. /**
  3794. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3795. */
  3796. Matrix.FromQuaternionToRef = function (quat, result) {
  3797. var xx = quat.x * quat.x;
  3798. var yy = quat.y * quat.y;
  3799. var zz = quat.z * quat.z;
  3800. var xy = quat.x * quat.y;
  3801. var zw = quat.z * quat.w;
  3802. var zx = quat.z * quat.x;
  3803. var yw = quat.y * quat.w;
  3804. var yz = quat.y * quat.z;
  3805. var xw = quat.x * quat.w;
  3806. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3807. result.m[1] = 2.0 * (xy + zw);
  3808. result.m[2] = 2.0 * (zx - yw);
  3809. result.m[3] = 0.0;
  3810. result.m[4] = 2.0 * (xy - zw);
  3811. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3812. result.m[6] = 2.0 * (yz + xw);
  3813. result.m[7] = 0.0;
  3814. result.m[8] = 2.0 * (zx + yw);
  3815. result.m[9] = 2.0 * (yz - xw);
  3816. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3817. result.m[11] = 0.0;
  3818. result.m[12] = 0.0;
  3819. result.m[13] = 0.0;
  3820. result.m[14] = 0.0;
  3821. result.m[15] = 1.0;
  3822. result._markAsUpdated();
  3823. };
  3824. return Matrix;
  3825. }());
  3826. Matrix._tempQuaternion = new Quaternion();
  3827. Matrix._xAxis = Vector3.Zero();
  3828. Matrix._yAxis = Vector3.Zero();
  3829. Matrix._zAxis = Vector3.Zero();
  3830. Matrix._updateFlagSeed = 0;
  3831. BABYLON.Matrix = Matrix;
  3832. var Plane = (function () {
  3833. /**
  3834. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3835. */
  3836. function Plane(a, b, c, d) {
  3837. this.normal = new Vector3(a, b, c);
  3838. this.d = d;
  3839. }
  3840. /**
  3841. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3842. */
  3843. Plane.prototype.asArray = function () {
  3844. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3845. };
  3846. // Methods
  3847. /**
  3848. * Returns a new plane copied from the current Plane.
  3849. */
  3850. Plane.prototype.clone = function () {
  3851. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3852. };
  3853. /**
  3854. * Returns the string "Plane".
  3855. */
  3856. Plane.prototype.getClassName = function () {
  3857. return "Plane";
  3858. };
  3859. /**
  3860. * Returns the Plane hash code.
  3861. */
  3862. Plane.prototype.getHashCode = function () {
  3863. var hash = this.normal.getHashCode();
  3864. hash = (hash * 397) ^ (this.d || 0);
  3865. return hash;
  3866. };
  3867. /**
  3868. * Normalize the current Plane in place.
  3869. * Returns the updated Plane.
  3870. */
  3871. Plane.prototype.normalize = function () {
  3872. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3873. var magnitude = 0.0;
  3874. if (norm !== 0) {
  3875. magnitude = 1.0 / norm;
  3876. }
  3877. this.normal.x *= magnitude;
  3878. this.normal.y *= magnitude;
  3879. this.normal.z *= magnitude;
  3880. this.d *= magnitude;
  3881. return this;
  3882. };
  3883. /**
  3884. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3885. */
  3886. Plane.prototype.transform = function (transformation) {
  3887. var transposedMatrix = Matrix.Transpose(transformation);
  3888. var x = this.normal.x;
  3889. var y = this.normal.y;
  3890. var z = this.normal.z;
  3891. var d = this.d;
  3892. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3893. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3894. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3895. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3896. return new Plane(normalX, normalY, normalZ, finalD);
  3897. };
  3898. /**
  3899. * Returns the dot product (float) of the point coordinates and the plane normal.
  3900. */
  3901. Plane.prototype.dotCoordinate = function (point) {
  3902. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3903. };
  3904. /**
  3905. * Updates the current Plane from the plane defined by the three passed points.
  3906. * Returns the updated Plane.
  3907. */
  3908. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3909. var x1 = point2.x - point1.x;
  3910. var y1 = point2.y - point1.y;
  3911. var z1 = point2.z - point1.z;
  3912. var x2 = point3.x - point1.x;
  3913. var y2 = point3.y - point1.y;
  3914. var z2 = point3.z - point1.z;
  3915. var yz = (y1 * z2) - (z1 * y2);
  3916. var xz = (z1 * x2) - (x1 * z2);
  3917. var xy = (x1 * y2) - (y1 * x2);
  3918. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3919. var invPyth;
  3920. if (pyth !== 0) {
  3921. invPyth = 1.0 / pyth;
  3922. }
  3923. else {
  3924. invPyth = 0.0;
  3925. }
  3926. this.normal.x = yz * invPyth;
  3927. this.normal.y = xz * invPyth;
  3928. this.normal.z = xy * invPyth;
  3929. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3930. return this;
  3931. };
  3932. /**
  3933. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3934. */
  3935. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3936. var dot = Vector3.Dot(this.normal, direction);
  3937. return (dot <= epsilon);
  3938. };
  3939. /**
  3940. * Returns the signed distance (float) from the passed point to the Plane.
  3941. */
  3942. Plane.prototype.signedDistanceTo = function (point) {
  3943. return Vector3.Dot(point, this.normal) + this.d;
  3944. };
  3945. // Statics
  3946. /**
  3947. * Returns a new Plane from the passed array.
  3948. */
  3949. Plane.FromArray = function (array) {
  3950. return new Plane(array[0], array[1], array[2], array[3]);
  3951. };
  3952. /**
  3953. * Returns a new Plane defined by the three passed points.
  3954. */
  3955. Plane.FromPoints = function (point1, point2, point3) {
  3956. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3957. result.copyFromPoints(point1, point2, point3);
  3958. return result;
  3959. };
  3960. /**
  3961. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3962. * Note : the vector "normal" is updated because normalized.
  3963. */
  3964. Plane.FromPositionAndNormal = function (origin, normal) {
  3965. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3966. normal.normalize();
  3967. result.normal = normal;
  3968. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3969. return result;
  3970. };
  3971. /**
  3972. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3973. */
  3974. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3975. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3976. return Vector3.Dot(point, normal) + d;
  3977. };
  3978. return Plane;
  3979. }());
  3980. BABYLON.Plane = Plane;
  3981. var Viewport = (function () {
  3982. /**
  3983. * Creates a Viewport object located at (x, y) and sized (width, height).
  3984. */
  3985. function Viewport(x, y, width, height) {
  3986. this.x = x;
  3987. this.y = y;
  3988. this.width = width;
  3989. this.height = height;
  3990. }
  3991. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  3992. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  3993. };
  3994. /**
  3995. * Returns a new Viewport copied from the current one.
  3996. */
  3997. Viewport.prototype.clone = function () {
  3998. return new Viewport(this.x, this.y, this.width, this.height);
  3999. };
  4000. return Viewport;
  4001. }());
  4002. BABYLON.Viewport = Viewport;
  4003. var Frustum = (function () {
  4004. function Frustum() {
  4005. }
  4006. /**
  4007. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4008. */
  4009. Frustum.GetPlanes = function (transform) {
  4010. var frustumPlanes = [];
  4011. for (var index = 0; index < 6; index++) {
  4012. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4013. }
  4014. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4015. return frustumPlanes;
  4016. };
  4017. /**
  4018. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4019. */
  4020. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4021. // Near
  4022. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4023. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4024. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4025. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4026. frustumPlanes[0].normalize();
  4027. // Far
  4028. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4029. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4030. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4031. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4032. frustumPlanes[1].normalize();
  4033. // Left
  4034. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4035. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4036. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4037. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4038. frustumPlanes[2].normalize();
  4039. // Right
  4040. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4041. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4042. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4043. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4044. frustumPlanes[3].normalize();
  4045. // Top
  4046. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4047. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4048. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4049. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4050. frustumPlanes[4].normalize();
  4051. // Bottom
  4052. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4053. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4054. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4055. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4056. frustumPlanes[5].normalize();
  4057. };
  4058. return Frustum;
  4059. }());
  4060. BABYLON.Frustum = Frustum;
  4061. var Space;
  4062. (function (Space) {
  4063. Space[Space["LOCAL"] = 0] = "LOCAL";
  4064. Space[Space["WORLD"] = 1] = "WORLD";
  4065. Space[Space["BONE"] = 2] = "BONE";
  4066. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4067. var Axis = (function () {
  4068. function Axis() {
  4069. }
  4070. return Axis;
  4071. }());
  4072. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4073. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4074. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4075. BABYLON.Axis = Axis;
  4076. ;
  4077. var BezierCurve = (function () {
  4078. function BezierCurve() {
  4079. }
  4080. /**
  4081. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4082. */
  4083. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4084. // Extract X (which is equal to time here)
  4085. var f0 = 1 - 3 * x2 + 3 * x1;
  4086. var f1 = 3 * x2 - 6 * x1;
  4087. var f2 = 3 * x1;
  4088. var refinedT = t;
  4089. for (var i = 0; i < 5; i++) {
  4090. var refinedT2 = refinedT * refinedT;
  4091. var refinedT3 = refinedT2 * refinedT;
  4092. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4093. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4094. refinedT -= (x - t) * slope;
  4095. refinedT = Math.min(1, Math.max(0, refinedT));
  4096. }
  4097. // Resolve cubic bezier for the given x
  4098. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4099. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4100. Math.pow(refinedT, 3);
  4101. };
  4102. return BezierCurve;
  4103. }());
  4104. BABYLON.BezierCurve = BezierCurve;
  4105. var Orientation;
  4106. (function (Orientation) {
  4107. Orientation[Orientation["CW"] = 0] = "CW";
  4108. Orientation[Orientation["CCW"] = 1] = "CCW";
  4109. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4110. var Angle = (function () {
  4111. /**
  4112. * Creates an Angle object of "radians" radians (float).
  4113. */
  4114. function Angle(radians) {
  4115. var _this = this;
  4116. /**
  4117. * Returns the Angle value in degrees (float).
  4118. */
  4119. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4120. /**
  4121. * Returns the Angle value in radians (float).
  4122. */
  4123. this.radians = function () { return _this._radians; };
  4124. this._radians = radians;
  4125. if (this._radians < 0.0)
  4126. this._radians += (2.0 * Math.PI);
  4127. }
  4128. /**
  4129. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4130. */
  4131. Angle.BetweenTwoPoints = function (a, b) {
  4132. var delta = b.subtract(a);
  4133. var theta = Math.atan2(delta.y, delta.x);
  4134. return new Angle(theta);
  4135. };
  4136. /**
  4137. * Returns a new Angle object from the passed float in radians.
  4138. */
  4139. Angle.FromRadians = function (radians) {
  4140. return new Angle(radians);
  4141. };
  4142. /**
  4143. * Returns a new Angle object from the passed float in degrees.
  4144. */
  4145. Angle.FromDegrees = function (degrees) {
  4146. return new Angle(degrees * Math.PI / 180.0);
  4147. };
  4148. return Angle;
  4149. }());
  4150. BABYLON.Angle = Angle;
  4151. var Arc2 = (function () {
  4152. /**
  4153. * Creates an Arc object from the three passed points : start, middle and end.
  4154. */
  4155. function Arc2(startPoint, midPoint, endPoint) {
  4156. this.startPoint = startPoint;
  4157. this.midPoint = midPoint;
  4158. this.endPoint = endPoint;
  4159. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4160. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4161. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4162. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4163. 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);
  4164. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4165. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4166. var a1 = this.startAngle.degrees();
  4167. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4168. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4169. // angles correction
  4170. if (a2 - a1 > +180.0)
  4171. a2 -= 360.0;
  4172. if (a2 - a1 < -180.0)
  4173. a2 += 360.0;
  4174. if (a3 - a2 > +180.0)
  4175. a3 -= 360.0;
  4176. if (a3 - a2 < -180.0)
  4177. a3 += 360.0;
  4178. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4179. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4180. }
  4181. return Arc2;
  4182. }());
  4183. BABYLON.Arc2 = Arc2;
  4184. var Path2 = (function () {
  4185. /**
  4186. * Creates a Path2 object from the starting 2D coordinates x and y.
  4187. */
  4188. function Path2(x, y) {
  4189. this._points = new Array();
  4190. this._length = 0.0;
  4191. this.closed = false;
  4192. this._points.push(new Vector2(x, y));
  4193. }
  4194. /**
  4195. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4196. * Returns the updated Path2.
  4197. */
  4198. Path2.prototype.addLineTo = function (x, y) {
  4199. if (closed) {
  4200. //Tools.Error("cannot add lines to closed paths");
  4201. return this;
  4202. }
  4203. var newPoint = new Vector2(x, y);
  4204. var previousPoint = this._points[this._points.length - 1];
  4205. this._points.push(newPoint);
  4206. this._length += newPoint.subtract(previousPoint).length();
  4207. return this;
  4208. };
  4209. /**
  4210. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  4211. * Returns the updated Path2.
  4212. */
  4213. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4214. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4215. if (closed) {
  4216. //Tools.Error("cannot add arcs to closed paths");
  4217. return this;
  4218. }
  4219. var startPoint = this._points[this._points.length - 1];
  4220. var midPoint = new Vector2(midX, midY);
  4221. var endPoint = new Vector2(endX, endY);
  4222. var arc = new Arc2(startPoint, midPoint, endPoint);
  4223. var increment = arc.angle.radians() / numberOfSegments;
  4224. if (arc.orientation === Orientation.CW)
  4225. increment *= -1;
  4226. var currentAngle = arc.startAngle.radians() + increment;
  4227. for (var i = 0; i < numberOfSegments; i++) {
  4228. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4229. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4230. this.addLineTo(x, y);
  4231. currentAngle += increment;
  4232. }
  4233. return this;
  4234. };
  4235. /**
  4236. * Closes the Path2.
  4237. * Returns the Path2.
  4238. */
  4239. Path2.prototype.close = function () {
  4240. this.closed = true;
  4241. return this;
  4242. };
  4243. /**
  4244. * Returns the Path2 total length (float).
  4245. */
  4246. Path2.prototype.length = function () {
  4247. var result = this._length;
  4248. if (!this.closed) {
  4249. var lastPoint = this._points[this._points.length - 1];
  4250. var firstPoint = this._points[0];
  4251. result += (firstPoint.subtract(lastPoint).length());
  4252. }
  4253. return result;
  4254. };
  4255. /**
  4256. * Returns the Path2 internal array of points.
  4257. */
  4258. Path2.prototype.getPoints = function () {
  4259. return this._points;
  4260. };
  4261. /**
  4262. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4263. */
  4264. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4265. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4266. //Tools.Error("normalized length position should be between 0 and 1.");
  4267. return Vector2.Zero();
  4268. }
  4269. var lengthPosition = normalizedLengthPosition * this.length();
  4270. var previousOffset = 0;
  4271. for (var i = 0; i < this._points.length; i++) {
  4272. var j = (i + 1) % this._points.length;
  4273. var a = this._points[i];
  4274. var b = this._points[j];
  4275. var bToA = b.subtract(a);
  4276. var nextOffset = (bToA.length() + previousOffset);
  4277. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4278. var dir = bToA.normalize();
  4279. var localOffset = lengthPosition - previousOffset;
  4280. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4281. }
  4282. previousOffset = nextOffset;
  4283. }
  4284. //Tools.Error("internal error");
  4285. return Vector2.Zero();
  4286. };
  4287. /**
  4288. * Returns a new Path2 starting at the coordinates (x, y).
  4289. */
  4290. Path2.StartingAt = function (x, y) {
  4291. return new Path2(x, y);
  4292. };
  4293. return Path2;
  4294. }());
  4295. BABYLON.Path2 = Path2;
  4296. var Path3D = (function () {
  4297. /**
  4298. * new Path3D(path, normal, raw)
  4299. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4300. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4301. * path : an array of Vector3, the curve axis of the Path3D
  4302. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4303. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4304. */
  4305. function Path3D(path, firstNormal, raw) {
  4306. this.path = path;
  4307. this._curve = new Array();
  4308. this._distances = new Array();
  4309. this._tangents = new Array();
  4310. this._normals = new Array();
  4311. this._binormals = new Array();
  4312. for (var p = 0; p < path.length; p++) {
  4313. this._curve[p] = path[p].clone(); // hard copy
  4314. }
  4315. this._raw = raw || false;
  4316. this._compute(firstNormal);
  4317. }
  4318. /**
  4319. * Returns the Path3D array of successive Vector3 designing its curve.
  4320. */
  4321. Path3D.prototype.getCurve = function () {
  4322. return this._curve;
  4323. };
  4324. /**
  4325. * Returns an array populated with tangent vectors on each Path3D curve point.
  4326. */
  4327. Path3D.prototype.getTangents = function () {
  4328. return this._tangents;
  4329. };
  4330. /**
  4331. * Returns an array populated with normal vectors on each Path3D curve point.
  4332. */
  4333. Path3D.prototype.getNormals = function () {
  4334. return this._normals;
  4335. };
  4336. /**
  4337. * Returns an array populated with binormal vectors on each Path3D curve point.
  4338. */
  4339. Path3D.prototype.getBinormals = function () {
  4340. return this._binormals;
  4341. };
  4342. /**
  4343. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4344. */
  4345. Path3D.prototype.getDistances = function () {
  4346. return this._distances;
  4347. };
  4348. /**
  4349. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4350. * Returns the same object updated.
  4351. */
  4352. Path3D.prototype.update = function (path, firstNormal) {
  4353. for (var p = 0; p < path.length; p++) {
  4354. this._curve[p].x = path[p].x;
  4355. this._curve[p].y = path[p].y;
  4356. this._curve[p].z = path[p].z;
  4357. }
  4358. this._compute(firstNormal);
  4359. return this;
  4360. };
  4361. // private function compute() : computes tangents, normals and binormals
  4362. Path3D.prototype._compute = function (firstNormal) {
  4363. var l = this._curve.length;
  4364. // first and last tangents
  4365. this._tangents[0] = this._getFirstNonNullVector(0);
  4366. if (!this._raw) {
  4367. this._tangents[0].normalize();
  4368. }
  4369. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4370. if (!this._raw) {
  4371. this._tangents[l - 1].normalize();
  4372. }
  4373. // normals and binormals at first point : arbitrary vector with _normalVector()
  4374. var tg0 = this._tangents[0];
  4375. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4376. this._normals[0] = pp0;
  4377. if (!this._raw) {
  4378. this._normals[0].normalize();
  4379. }
  4380. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4381. if (!this._raw) {
  4382. this._binormals[0].normalize();
  4383. }
  4384. this._distances[0] = 0.0;
  4385. // normals and binormals : next points
  4386. var prev; // previous vector (segment)
  4387. var cur; // current vector (segment)
  4388. var curTang; // current tangent
  4389. // previous normal
  4390. var prevBinor; // previous binormal
  4391. for (var i = 1; i < l; i++) {
  4392. // tangents
  4393. prev = this._getLastNonNullVector(i);
  4394. if (i < l - 1) {
  4395. cur = this._getFirstNonNullVector(i);
  4396. this._tangents[i] = prev.add(cur);
  4397. this._tangents[i].normalize();
  4398. }
  4399. this._distances[i] = this._distances[i - 1] + prev.length();
  4400. // normals and binormals
  4401. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4402. curTang = this._tangents[i];
  4403. prevBinor = this._binormals[i - 1];
  4404. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4405. if (!this._raw) {
  4406. this._normals[i].normalize();
  4407. }
  4408. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4409. if (!this._raw) {
  4410. this._binormals[i].normalize();
  4411. }
  4412. }
  4413. };
  4414. // private function getFirstNonNullVector(index)
  4415. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4416. Path3D.prototype._getFirstNonNullVector = function (index) {
  4417. var i = 1;
  4418. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4419. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4420. i++;
  4421. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4422. }
  4423. return nNVector;
  4424. };
  4425. // private function getLastNonNullVector(index)
  4426. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4427. Path3D.prototype._getLastNonNullVector = function (index) {
  4428. var i = 1;
  4429. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4430. while (nLVector.length() === 0 && index > i + 1) {
  4431. i++;
  4432. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4433. }
  4434. return nLVector;
  4435. };
  4436. // private function normalVector(v0, vt, va) :
  4437. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4438. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4439. Path3D.prototype._normalVector = function (v0, vt, va) {
  4440. var normal0;
  4441. var tgl = vt.length();
  4442. if (tgl === 0.0) {
  4443. tgl = 1.0;
  4444. }
  4445. if (va === undefined || va === null) {
  4446. var point;
  4447. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4448. point = new Vector3(0.0, -1.0, 0.0);
  4449. }
  4450. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4451. point = new Vector3(1.0, 0.0, 0.0);
  4452. }
  4453. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4454. point = new Vector3(0.0, 0.0, 1.0);
  4455. }
  4456. normal0 = Vector3.Cross(vt, point);
  4457. }
  4458. else {
  4459. normal0 = Vector3.Cross(vt, va);
  4460. Vector3.CrossToRef(normal0, vt, normal0);
  4461. }
  4462. normal0.normalize();
  4463. return normal0;
  4464. };
  4465. return Path3D;
  4466. }());
  4467. BABYLON.Path3D = Path3D;
  4468. var Curve3 = (function () {
  4469. /**
  4470. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4471. * A Curve3 is designed from a series of successive Vector3.
  4472. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4473. */
  4474. function Curve3(points) {
  4475. this._length = 0.0;
  4476. this._points = points;
  4477. this._length = this._computeLength(points);
  4478. }
  4479. /**
  4480. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4481. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4482. * @param v1 (Vector3) the control point
  4483. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4484. * @param nbPoints (integer) the wanted number of points in the curve
  4485. */
  4486. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4487. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4488. var bez = new Array();
  4489. var equation = function (t, val0, val1, val2) {
  4490. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4491. return res;
  4492. };
  4493. for (var i = 0; i <= nbPoints; i++) {
  4494. 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)));
  4495. }
  4496. return new Curve3(bez);
  4497. };
  4498. /**
  4499. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4500. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4501. * @param v1 (Vector3) the first control point
  4502. * @param v2 (Vector3) the second control point
  4503. * @param v3 (Vector3) the end point of the Cubic Bezier
  4504. * @param nbPoints (integer) the wanted number of points in the curve
  4505. */
  4506. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4507. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4508. var bez = new Array();
  4509. var equation = function (t, val0, val1, val2, val3) {
  4510. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  4511. return res;
  4512. };
  4513. for (var i = 0; i <= nbPoints; i++) {
  4514. 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)));
  4515. }
  4516. return new Curve3(bez);
  4517. };
  4518. /**
  4519. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4520. * @param p1 (Vector3) the origin point of the Hermite Spline
  4521. * @param t1 (Vector3) the tangent vector at the origin point
  4522. * @param p2 (Vector3) the end point of the Hermite Spline
  4523. * @param t2 (Vector3) the tangent vector at the end point
  4524. * @param nbPoints (integer) the wanted number of points in the curve
  4525. */
  4526. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4527. var hermite = new Array();
  4528. var step = 1.0 / nbPoints;
  4529. for (var i = 0; i <= nbPoints; i++) {
  4530. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4531. }
  4532. return new Curve3(hermite);
  4533. };
  4534. /**
  4535. * Returns a Curve3 object along a CatmullRom Spline curve :
  4536. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4537. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4538. */
  4539. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4540. var totalPoints = new Array();
  4541. totalPoints.push(points[0].clone());
  4542. Array.prototype.push.apply(totalPoints, points);
  4543. totalPoints.push(points[points.length - 1].clone());
  4544. var catmullRom = new Array();
  4545. var step = 1.0 / nbPoints;
  4546. for (var i = 0; i < totalPoints.length - 3; i++) {
  4547. var amount = 0.0;
  4548. for (var c = 0; c < nbPoints; c++) {
  4549. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4550. amount += step;
  4551. }
  4552. }
  4553. i--;
  4554. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4555. return new Curve3(catmullRom);
  4556. };
  4557. /**
  4558. * Returns the Curve3 stored array of successive Vector3
  4559. */
  4560. Curve3.prototype.getPoints = function () {
  4561. return this._points;
  4562. };
  4563. /**
  4564. * Returns the computed length (float) of the curve.
  4565. */
  4566. Curve3.prototype.length = function () {
  4567. return this._length;
  4568. };
  4569. /**
  4570. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4571. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4572. * curveA and curveB keep unchanged.
  4573. */
  4574. Curve3.prototype.continue = function (curve) {
  4575. var lastPoint = this._points[this._points.length - 1];
  4576. var continuedPoints = this._points.slice();
  4577. var curvePoints = curve.getPoints();
  4578. for (var i = 1; i < curvePoints.length; i++) {
  4579. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4580. }
  4581. var continuedCurve = new Curve3(continuedPoints);
  4582. return continuedCurve;
  4583. };
  4584. Curve3.prototype._computeLength = function (path) {
  4585. var l = 0;
  4586. for (var i = 1; i < path.length; i++) {
  4587. l += (path[i].subtract(path[i - 1])).length();
  4588. }
  4589. return l;
  4590. };
  4591. return Curve3;
  4592. }());
  4593. BABYLON.Curve3 = Curve3;
  4594. // SphericalHarmonics
  4595. var SphericalHarmonics = (function () {
  4596. function SphericalHarmonics() {
  4597. this.L00 = Vector3.Zero();
  4598. this.L1_1 = Vector3.Zero();
  4599. this.L10 = Vector3.Zero();
  4600. this.L11 = Vector3.Zero();
  4601. this.L2_2 = Vector3.Zero();
  4602. this.L2_1 = Vector3.Zero();
  4603. this.L20 = Vector3.Zero();
  4604. this.L21 = Vector3.Zero();
  4605. this.L22 = Vector3.Zero();
  4606. }
  4607. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  4608. var colorVector = new Vector3(color.r, color.g, color.b);
  4609. var c = colorVector.scale(deltaSolidAngle);
  4610. this.L00 = this.L00.add(c.scale(0.282095));
  4611. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  4612. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  4613. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  4614. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  4615. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  4616. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  4617. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  4618. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  4619. };
  4620. SphericalHarmonics.prototype.scale = function (scale) {
  4621. this.L00 = this.L00.scale(scale);
  4622. this.L1_1 = this.L1_1.scale(scale);
  4623. this.L10 = this.L10.scale(scale);
  4624. this.L11 = this.L11.scale(scale);
  4625. this.L2_2 = this.L2_2.scale(scale);
  4626. this.L2_1 = this.L2_1.scale(scale);
  4627. this.L20 = this.L20.scale(scale);
  4628. this.L21 = this.L21.scale(scale);
  4629. this.L22 = this.L22.scale(scale);
  4630. };
  4631. return SphericalHarmonics;
  4632. }());
  4633. BABYLON.SphericalHarmonics = SphericalHarmonics;
  4634. // SphericalPolynomial
  4635. var SphericalPolynomial = (function () {
  4636. function SphericalPolynomial() {
  4637. this.x = Vector3.Zero();
  4638. this.y = Vector3.Zero();
  4639. this.z = Vector3.Zero();
  4640. this.xx = Vector3.Zero();
  4641. this.yy = Vector3.Zero();
  4642. this.zz = Vector3.Zero();
  4643. this.xy = Vector3.Zero();
  4644. this.yz = Vector3.Zero();
  4645. this.zx = Vector3.Zero();
  4646. }
  4647. SphericalPolynomial.prototype.addAmbient = function (color) {
  4648. var colorVector = new Vector3(color.r, color.g, color.b);
  4649. this.xx = this.xx.add(colorVector);
  4650. this.yy = this.yy.add(colorVector);
  4651. this.zz = this.zz.add(colorVector);
  4652. };
  4653. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  4654. var result = new SphericalPolynomial();
  4655. result.x = harmonics.L11.scale(1.02333);
  4656. result.y = harmonics.L1_1.scale(1.02333);
  4657. result.z = harmonics.L10.scale(1.02333);
  4658. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  4659. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  4660. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  4661. result.yz = harmonics.L2_1.scale(0.858086);
  4662. result.zx = harmonics.L21.scale(0.858086);
  4663. result.xy = harmonics.L2_2.scale(0.858086);
  4664. return result;
  4665. };
  4666. return SphericalPolynomial;
  4667. }());
  4668. BABYLON.SphericalPolynomial = SphericalPolynomial;
  4669. // Vertex formats
  4670. var PositionNormalVertex = (function () {
  4671. function PositionNormalVertex(position, normal) {
  4672. if (position === void 0) { position = Vector3.Zero(); }
  4673. if (normal === void 0) { normal = Vector3.Up(); }
  4674. this.position = position;
  4675. this.normal = normal;
  4676. }
  4677. PositionNormalVertex.prototype.clone = function () {
  4678. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4679. };
  4680. return PositionNormalVertex;
  4681. }());
  4682. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4683. var PositionNormalTextureVertex = (function () {
  4684. function PositionNormalTextureVertex(position, normal, uv) {
  4685. if (position === void 0) { position = Vector3.Zero(); }
  4686. if (normal === void 0) { normal = Vector3.Up(); }
  4687. if (uv === void 0) { uv = Vector2.Zero(); }
  4688. this.position = position;
  4689. this.normal = normal;
  4690. this.uv = uv;
  4691. }
  4692. PositionNormalTextureVertex.prototype.clone = function () {
  4693. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4694. };
  4695. return PositionNormalTextureVertex;
  4696. }());
  4697. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4698. // Temporary pre-allocated objects for engine internal use
  4699. // usage in any internal function :
  4700. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4701. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4702. var Tmp = (function () {
  4703. function Tmp() {
  4704. }
  4705. return Tmp;
  4706. }());
  4707. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4708. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4709. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4710. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4711. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4712. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4713. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4714. Matrix.Zero(), Matrix.Zero(),
  4715. Matrix.Zero(), Matrix.Zero(),
  4716. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4717. BABYLON.Tmp = Tmp;
  4718. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4719. var MathTmp = (function () {
  4720. function MathTmp() {
  4721. }
  4722. return MathTmp;
  4723. }());
  4724. MathTmp.Vector3 = [Vector3.Zero()];
  4725. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4726. MathTmp.Quaternion = [Quaternion.Zero()];
  4727. })(BABYLON || (BABYLON = {}));
  4728. //# sourceMappingURL=babylon.math.js.map
  4729. //# sourceMappingURL=babylon.mixins.js.map
  4730. var BABYLON;
  4731. (function (BABYLON) {
  4732. function generateSerializableMember(type, sourceName) {
  4733. return function (target, propertyKey) {
  4734. if (!target.__serializableMembers) {
  4735. target.__serializableMembers = {};
  4736. }
  4737. if (!target.__serializableMembers[propertyKey]) {
  4738. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4739. }
  4740. };
  4741. }
  4742. function generateExpandMember(setCallback) {
  4743. return function (target, propertyKey) {
  4744. if (setCallback) {
  4745. var key = "_" + propertyKey;
  4746. Object.defineProperty(target, propertyKey, {
  4747. get: function () {
  4748. return this[key];
  4749. },
  4750. set: function (value) {
  4751. if (this[key] === value) {
  4752. return;
  4753. }
  4754. this[key] = value;
  4755. target[setCallback].apply(this);
  4756. },
  4757. enumerable: true,
  4758. configurable: true
  4759. });
  4760. }
  4761. };
  4762. }
  4763. function expandToProperty(callback) {
  4764. return generateExpandMember(callback);
  4765. }
  4766. BABYLON.expandToProperty = expandToProperty;
  4767. function serialize(sourceName) {
  4768. return generateSerializableMember(0, sourceName); // value member
  4769. }
  4770. BABYLON.serialize = serialize;
  4771. function serializeAsTexture(sourceName) {
  4772. return generateSerializableMember(1, sourceName); // texture member
  4773. }
  4774. BABYLON.serializeAsTexture = serializeAsTexture;
  4775. function serializeAsColor3(sourceName) {
  4776. return generateSerializableMember(2, sourceName); // color3 member
  4777. }
  4778. BABYLON.serializeAsColor3 = serializeAsColor3;
  4779. function serializeAsFresnelParameters(sourceName) {
  4780. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4781. }
  4782. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4783. function serializeAsVector2(sourceName) {
  4784. return generateSerializableMember(4, sourceName); // vector2 member
  4785. }
  4786. BABYLON.serializeAsVector2 = serializeAsVector2;
  4787. function serializeAsVector3(sourceName) {
  4788. return generateSerializableMember(5, sourceName); // vector3 member
  4789. }
  4790. BABYLON.serializeAsVector3 = serializeAsVector3;
  4791. function serializeAsMeshReference(sourceName) {
  4792. return generateSerializableMember(6, sourceName); // mesh reference member
  4793. }
  4794. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4795. function serializeAsColorCurves(sourceName) {
  4796. return generateSerializableMember(7, sourceName); // color curves
  4797. }
  4798. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4799. var SerializationHelper = (function () {
  4800. function SerializationHelper() {
  4801. }
  4802. SerializationHelper.Serialize = function (entity, serializationObject) {
  4803. if (!serializationObject) {
  4804. serializationObject = {};
  4805. }
  4806. // Tags
  4807. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4808. // Properties
  4809. for (var property in entity.__serializableMembers) {
  4810. var propertyDescriptor = entity.__serializableMembers[property];
  4811. var targetPropertyName = propertyDescriptor.sourceName || property;
  4812. var propertyType = propertyDescriptor.type;
  4813. var sourceProperty = entity[property];
  4814. if (sourceProperty !== undefined && sourceProperty !== null) {
  4815. switch (propertyType) {
  4816. case 0:
  4817. serializationObject[targetPropertyName] = sourceProperty;
  4818. break;
  4819. case 1:
  4820. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4821. break;
  4822. case 2:
  4823. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4824. break;
  4825. case 3:
  4826. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4827. break;
  4828. case 4:
  4829. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4830. break;
  4831. case 5:
  4832. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4833. break;
  4834. case 6:
  4835. serializationObject[targetPropertyName] = sourceProperty.id;
  4836. break;
  4837. case 7:
  4838. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4839. break;
  4840. }
  4841. }
  4842. }
  4843. return serializationObject;
  4844. };
  4845. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4846. var destination = creationFunction();
  4847. // Tags
  4848. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4849. // Properties
  4850. for (var property in destination.__serializableMembers) {
  4851. var propertyDescriptor = destination.__serializableMembers[property];
  4852. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4853. var propertyType = propertyDescriptor.type;
  4854. if (sourceProperty !== undefined && sourceProperty !== null) {
  4855. switch (propertyType) {
  4856. case 0:
  4857. destination[property] = sourceProperty;
  4858. break;
  4859. case 1:
  4860. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4861. break;
  4862. case 2:
  4863. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4864. break;
  4865. case 3:
  4866. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4867. break;
  4868. case 4:
  4869. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4870. break;
  4871. case 5:
  4872. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4873. break;
  4874. case 6:
  4875. destination[property] = scene.getLastMeshByID(sourceProperty);
  4876. break;
  4877. case 7:
  4878. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4879. break;
  4880. }
  4881. }
  4882. }
  4883. return destination;
  4884. };
  4885. SerializationHelper.Clone = function (creationFunction, source) {
  4886. var destination = creationFunction();
  4887. // Tags
  4888. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4889. // Properties
  4890. for (var property in destination.__serializableMembers) {
  4891. var propertyDescriptor = destination.__serializableMembers[property];
  4892. var sourceProperty = source[property];
  4893. var propertyType = propertyDescriptor.type;
  4894. if (sourceProperty !== undefined && sourceProperty !== null) {
  4895. switch (propertyType) {
  4896. case 0: // Value
  4897. case 6:
  4898. destination[property] = sourceProperty;
  4899. break;
  4900. case 1: // Texture
  4901. case 2: // Color3
  4902. case 3: // FresnelParameters
  4903. case 4: // Vector2
  4904. case 5: // Vector3
  4905. case 7:
  4906. destination[property] = sourceProperty.clone();
  4907. break;
  4908. }
  4909. }
  4910. }
  4911. return destination;
  4912. };
  4913. return SerializationHelper;
  4914. }());
  4915. BABYLON.SerializationHelper = SerializationHelper;
  4916. })(BABYLON || (BABYLON = {}));
  4917. //# sourceMappingURL=babylon.decorators.js.map
  4918. var BABYLON;
  4919. (function (BABYLON) {
  4920. /**
  4921. * A class serves as a medium between the observable and its observers
  4922. */
  4923. var EventState = (function () {
  4924. /**
  4925. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4926. */
  4927. function EventState(mask, skipNextObservers) {
  4928. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4929. this.initalize(mask, skipNextObservers);
  4930. }
  4931. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4932. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4933. this.mask = mask;
  4934. this.skipNextObservers = skipNextObservers;
  4935. return this;
  4936. };
  4937. return EventState;
  4938. }());
  4939. BABYLON.EventState = EventState;
  4940. /**
  4941. * Represent an Observer registered to a given Observable object.
  4942. */
  4943. var Observer = (function () {
  4944. function Observer(callback, mask) {
  4945. this.callback = callback;
  4946. this.mask = mask;
  4947. }
  4948. return Observer;
  4949. }());
  4950. BABYLON.Observer = Observer;
  4951. /**
  4952. * The Observable class is a simple implementation of the Observable pattern.
  4953. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  4954. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4955. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  4956. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  4957. */
  4958. var Observable = (function () {
  4959. function Observable() {
  4960. this._observers = new Array();
  4961. this._eventState = new EventState(0);
  4962. }
  4963. /**
  4964. * Create a new Observer with the specified callback
  4965. * @param callback the callback that will be executed for that Observer
  4966. * @param mask the mask used to filter observers
  4967. * @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.
  4968. */
  4969. Observable.prototype.add = function (callback, mask, insertFirst) {
  4970. if (mask === void 0) { mask = -1; }
  4971. if (insertFirst === void 0) { insertFirst = false; }
  4972. if (!callback) {
  4973. return null;
  4974. }
  4975. var observer = new Observer(callback, mask);
  4976. if (insertFirst) {
  4977. this._observers.unshift(observer);
  4978. }
  4979. else {
  4980. this._observers.push(observer);
  4981. }
  4982. return observer;
  4983. };
  4984. /**
  4985. * Remove an Observer from the Observable object
  4986. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  4987. */
  4988. Observable.prototype.remove = function (observer) {
  4989. var index = this._observers.indexOf(observer);
  4990. if (index !== -1) {
  4991. this._observers.splice(index, 1);
  4992. return true;
  4993. }
  4994. return false;
  4995. };
  4996. /**
  4997. * Remove a callback from the Observable object
  4998. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  4999. */
  5000. Observable.prototype.removeCallback = function (callback) {
  5001. for (var index = 0; index < this._observers.length; index++) {
  5002. if (this._observers[index].callback === callback) {
  5003. this._observers.splice(index, 1);
  5004. return true;
  5005. }
  5006. }
  5007. return false;
  5008. };
  5009. /**
  5010. * Notify all Observers by calling their respective callback with the given data
  5011. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5012. * @param eventData
  5013. * @param mask
  5014. */
  5015. Observable.prototype.notifyObservers = function (eventData, mask) {
  5016. if (mask === void 0) { mask = -1; }
  5017. var state = this._eventState;
  5018. state.mask = mask;
  5019. state.skipNextObservers = false;
  5020. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5021. var obs = _a[_i];
  5022. if (obs.mask & mask) {
  5023. obs.callback(eventData, state);
  5024. }
  5025. if (state.skipNextObservers) {
  5026. return false;
  5027. }
  5028. }
  5029. return true;
  5030. };
  5031. /**
  5032. * return true is the Observable has at least one Observer registered
  5033. */
  5034. Observable.prototype.hasObservers = function () {
  5035. return this._observers.length > 0;
  5036. };
  5037. /**
  5038. * Clear the list of observers
  5039. */
  5040. Observable.prototype.clear = function () {
  5041. this._observers = new Array();
  5042. };
  5043. /**
  5044. * Clone the current observable
  5045. */
  5046. Observable.prototype.clone = function () {
  5047. var result = new Observable();
  5048. result._observers = this._observers.slice(0);
  5049. return result;
  5050. };
  5051. /**
  5052. * Does this observable handles observer registered with a given mask
  5053. * @param {number} trigger - the mask to be tested
  5054. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5055. **/
  5056. Observable.prototype.hasSpecificMask = function (mask) {
  5057. if (mask === void 0) { mask = -1; }
  5058. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5059. var obs = _a[_i];
  5060. if (obs.mask & mask && obs.mask === mask) {
  5061. return true;
  5062. }
  5063. }
  5064. return false;
  5065. };
  5066. return Observable;
  5067. }());
  5068. BABYLON.Observable = Observable;
  5069. })(BABYLON || (BABYLON = {}));
  5070. //# sourceMappingURL=babylon.observable.js.map
  5071. var BABYLON;
  5072. (function (BABYLON) {
  5073. var SmartArray = (function () {
  5074. function SmartArray(capacity) {
  5075. this.length = 0;
  5076. this._duplicateId = 0;
  5077. this.data = new Array(capacity);
  5078. this._id = SmartArray._GlobalId++;
  5079. }
  5080. SmartArray.prototype.push = function (value) {
  5081. this.data[this.length++] = value;
  5082. if (this.length > this.data.length) {
  5083. this.data.length *= 2;
  5084. }
  5085. if (!value.__smartArrayFlags) {
  5086. value.__smartArrayFlags = {};
  5087. }
  5088. value.__smartArrayFlags[this._id] = this._duplicateId;
  5089. };
  5090. SmartArray.prototype.forEach = function (func) {
  5091. for (var index = 0; index < this.length; index++) {
  5092. func(this.data[index]);
  5093. }
  5094. };
  5095. SmartArray.prototype.pushNoDuplicate = function (value) {
  5096. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5097. return false;
  5098. }
  5099. this.push(value);
  5100. return true;
  5101. };
  5102. SmartArray.prototype.sort = function (compareFn) {
  5103. this.data.sort(compareFn);
  5104. };
  5105. SmartArray.prototype.reset = function () {
  5106. this.length = 0;
  5107. this._duplicateId++;
  5108. };
  5109. SmartArray.prototype.dispose = function () {
  5110. this.reset();
  5111. this.data.length = 0;
  5112. };
  5113. SmartArray.prototype.concat = function (array) {
  5114. if (array.length === 0) {
  5115. return;
  5116. }
  5117. if (this.length + array.length > this.data.length) {
  5118. this.data.length = (this.length + array.length) * 2;
  5119. }
  5120. for (var index = 0; index < array.length; index++) {
  5121. this.data[this.length++] = (array.data || array)[index];
  5122. }
  5123. };
  5124. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5125. if (array.length === 0) {
  5126. return;
  5127. }
  5128. if (this.length + array.length > this.data.length) {
  5129. this.data.length = (this.length + array.length) * 2;
  5130. }
  5131. for (var index = 0; index < array.length; index++) {
  5132. var item = (array.data || array)[index];
  5133. this.pushNoDuplicate(item);
  5134. }
  5135. };
  5136. SmartArray.prototype.indexOf = function (value) {
  5137. var position = this.data.indexOf(value);
  5138. if (position >= this.length) {
  5139. return -1;
  5140. }
  5141. return position;
  5142. };
  5143. SmartArray.prototype.contains = function (value) {
  5144. return this.data.indexOf(value) !== -1;
  5145. };
  5146. return SmartArray;
  5147. }());
  5148. // Statics
  5149. SmartArray._GlobalId = 0;
  5150. BABYLON.SmartArray = SmartArray;
  5151. })(BABYLON || (BABYLON = {}));
  5152. //# sourceMappingURL=babylon.smartArray.js.map
  5153. var BABYLON;
  5154. (function (BABYLON) {
  5155. // Screenshots
  5156. var screenshotCanvas;
  5157. var cloneValue = function (source, destinationObject) {
  5158. if (!source)
  5159. return null;
  5160. if (source instanceof BABYLON.Mesh) {
  5161. return null;
  5162. }
  5163. if (source instanceof BABYLON.SubMesh) {
  5164. return source.clone(destinationObject);
  5165. }
  5166. else if (source.clone) {
  5167. return source.clone();
  5168. }
  5169. return null;
  5170. };
  5171. var Tools = (function () {
  5172. function Tools() {
  5173. }
  5174. ;
  5175. Tools.Instantiate = function (className) {
  5176. var arr = className.split(".");
  5177. var fn = (window || this);
  5178. for (var i = 0, len = arr.length; i < len; i++) {
  5179. fn = fn[arr[i]];
  5180. }
  5181. if (typeof fn !== "function") {
  5182. return null;
  5183. }
  5184. return fn;
  5185. };
  5186. Tools.SetImmediate = function (action) {
  5187. if (window.setImmediate) {
  5188. window.setImmediate(action);
  5189. }
  5190. else {
  5191. setTimeout(action, 1);
  5192. }
  5193. };
  5194. Tools.IsExponentOfTwo = function (value) {
  5195. var count = 1;
  5196. do {
  5197. count *= 2;
  5198. } while (count < value);
  5199. return count === value;
  5200. };
  5201. Tools.GetExponentOfTwo = function (value, max) {
  5202. var count = 1;
  5203. do {
  5204. count *= 2;
  5205. } while (count < value);
  5206. if (count > max)
  5207. count = max;
  5208. return count;
  5209. };
  5210. Tools.GetFilename = function (path) {
  5211. var index = path.lastIndexOf("/");
  5212. if (index < 0)
  5213. return path;
  5214. return path.substring(index + 1);
  5215. };
  5216. Tools.GetDOMTextContent = function (element) {
  5217. var result = "";
  5218. var child = element.firstChild;
  5219. while (child) {
  5220. if (child.nodeType === 3) {
  5221. result += child.textContent;
  5222. }
  5223. child = child.nextSibling;
  5224. }
  5225. return result;
  5226. };
  5227. Tools.ToDegrees = function (angle) {
  5228. return angle * 180 / Math.PI;
  5229. };
  5230. Tools.ToRadians = function (angle) {
  5231. return angle * Math.PI / 180;
  5232. };
  5233. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5234. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5235. var output = "";
  5236. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5237. var i = 0;
  5238. var bytes = new Uint8Array(buffer);
  5239. while (i < bytes.length) {
  5240. chr1 = bytes[i++];
  5241. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5242. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5243. enc1 = chr1 >> 2;
  5244. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5245. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5246. enc4 = chr3 & 63;
  5247. if (isNaN(chr2)) {
  5248. enc3 = enc4 = 64;
  5249. }
  5250. else if (isNaN(chr3)) {
  5251. enc4 = 64;
  5252. }
  5253. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5254. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5255. }
  5256. return "data:image/png;base64," + output;
  5257. };
  5258. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5259. if (bias === void 0) { bias = null; }
  5260. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5261. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5262. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5263. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5264. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5265. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5266. }
  5267. if (bias) {
  5268. minimum.x -= minimum.x * bias.x + bias.y;
  5269. minimum.y -= minimum.y * bias.x + bias.y;
  5270. minimum.z -= minimum.z * bias.x + bias.y;
  5271. maximum.x += maximum.x * bias.x + bias.y;
  5272. maximum.y += maximum.y * bias.x + bias.y;
  5273. maximum.z += maximum.z * bias.x + bias.y;
  5274. }
  5275. return {
  5276. minimum: minimum,
  5277. maximum: maximum
  5278. };
  5279. };
  5280. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5281. if (bias === void 0) { bias = null; }
  5282. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5283. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5284. if (!stride) {
  5285. stride = 3;
  5286. }
  5287. for (var index = start; index < start + count; index++) {
  5288. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5289. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5290. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5291. }
  5292. if (bias) {
  5293. minimum.x -= minimum.x * bias.x + bias.y;
  5294. minimum.y -= minimum.y * bias.x + bias.y;
  5295. minimum.z -= minimum.z * bias.x + bias.y;
  5296. maximum.x += maximum.x * bias.x + bias.y;
  5297. maximum.y += maximum.y * bias.x + bias.y;
  5298. maximum.z += maximum.z * bias.x + bias.y;
  5299. }
  5300. return {
  5301. minimum: minimum,
  5302. maximum: maximum
  5303. };
  5304. };
  5305. Tools.Vector2ArrayFeeder = function (array) {
  5306. return function (index) {
  5307. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5308. var length = isFloatArray ? array.length / 2 : array.length;
  5309. if (index >= length) {
  5310. return null;
  5311. }
  5312. if (isFloatArray) {
  5313. var fa = array;
  5314. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5315. }
  5316. var a = array;
  5317. return a[index];
  5318. };
  5319. };
  5320. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5321. if (bias === void 0) { bias = null; }
  5322. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5323. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5324. var i = 0;
  5325. var cur = feeder(i++);
  5326. while (cur) {
  5327. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5328. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5329. cur = feeder(i++);
  5330. }
  5331. if (bias) {
  5332. minimum.x -= minimum.x * bias.x + bias.y;
  5333. minimum.y -= minimum.y * bias.x + bias.y;
  5334. maximum.x += maximum.x * bias.x + bias.y;
  5335. maximum.y += maximum.y * bias.x + bias.y;
  5336. }
  5337. return {
  5338. minimum: minimum,
  5339. maximum: maximum
  5340. };
  5341. };
  5342. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5343. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5344. return undefined;
  5345. return Array.isArray(obj) ? obj : [obj];
  5346. };
  5347. // Misc.
  5348. Tools.GetPointerPrefix = function () {
  5349. var eventPrefix = "pointer";
  5350. // Check if pointer events are supported
  5351. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5352. eventPrefix = "mouse";
  5353. }
  5354. return eventPrefix;
  5355. };
  5356. /**
  5357. * @param func - the function to be called
  5358. * @param requester - the object that will request the next frame. Falls back to window.
  5359. */
  5360. Tools.QueueNewFrame = function (func, requester) {
  5361. if (requester === void 0) { requester = window; }
  5362. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5363. /*if(requester.isPresenting) {
  5364. return;
  5365. } else*/ if (requester.requestAnimationFrame)
  5366. requester.requestAnimationFrame(func);
  5367. else if (requester.msRequestAnimationFrame)
  5368. requester.msRequestAnimationFrame(func);
  5369. else if (requester.webkitRequestAnimationFrame)
  5370. requester.webkitRequestAnimationFrame(func);
  5371. else if (requester.mozRequestAnimationFrame)
  5372. requester.mozRequestAnimationFrame(func);
  5373. else if (requester.oRequestAnimationFrame)
  5374. requester.oRequestAnimationFrame(func);
  5375. else {
  5376. window.setTimeout(func, 16);
  5377. }
  5378. };
  5379. Tools.RequestFullscreen = function (element) {
  5380. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5381. if (!requestFunction)
  5382. return;
  5383. requestFunction.call(element);
  5384. };
  5385. Tools.ExitFullscreen = function () {
  5386. if (document.exitFullscreen) {
  5387. document.exitFullscreen();
  5388. }
  5389. else if (document.mozCancelFullScreen) {
  5390. document.mozCancelFullScreen();
  5391. }
  5392. else if (document.webkitCancelFullScreen) {
  5393. document.webkitCancelFullScreen();
  5394. }
  5395. else if (document.msCancelFullScreen) {
  5396. document.msCancelFullScreen();
  5397. }
  5398. };
  5399. Tools.SetCorsBehavior = function (url, img) {
  5400. if (Tools.CorsBehavior) {
  5401. switch (typeof (Tools.CorsBehavior)) {
  5402. case "function":
  5403. var result = Tools.CorsBehavior(url);
  5404. if (result) {
  5405. img.crossOrigin = result;
  5406. }
  5407. break;
  5408. case "string":
  5409. default:
  5410. img.crossOrigin = Tools.CorsBehavior;
  5411. break;
  5412. }
  5413. }
  5414. };
  5415. // External files
  5416. Tools.CleanUrl = function (url) {
  5417. url = url.replace(/#/mg, "%23");
  5418. return url;
  5419. };
  5420. Tools.LoadImage = function (url, onload, onerror, database) {
  5421. if (url instanceof ArrayBuffer) {
  5422. url = Tools.EncodeArrayBufferTobase64(url);
  5423. }
  5424. url = Tools.CleanUrl(url);
  5425. var img = new Image();
  5426. if (url.substr(0, 5) !== "data:") {
  5427. Tools.SetCorsBehavior(url, img);
  5428. }
  5429. img.onload = function () {
  5430. onload(img);
  5431. };
  5432. img.onerror = function (err) {
  5433. Tools.Error("Error while trying to load image: " + url);
  5434. if (Tools.UseFallbackTexture) {
  5435. img.src = Tools.fallbackTexture;
  5436. onload(img);
  5437. }
  5438. else {
  5439. onerror();
  5440. }
  5441. };
  5442. var noIndexedDB = function () {
  5443. img.src = url;
  5444. };
  5445. var loadFromIndexedDB = function () {
  5446. database.loadImageFromDB(url, img);
  5447. };
  5448. //ANY database to do!
  5449. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5450. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5451. }
  5452. else {
  5453. if (url.indexOf("file:") === -1) {
  5454. noIndexedDB();
  5455. }
  5456. else {
  5457. var textureName = url.substring(5).toLowerCase();
  5458. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5459. try {
  5460. var blobURL;
  5461. try {
  5462. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5463. }
  5464. catch (ex) {
  5465. // Chrome doesn't support oneTimeOnly parameter
  5466. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5467. }
  5468. img.src = blobURL;
  5469. }
  5470. catch (e) {
  5471. img.src = null;
  5472. }
  5473. }
  5474. else {
  5475. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5476. img.src = Tools.fallbackTexture;
  5477. }
  5478. }
  5479. }
  5480. return img;
  5481. };
  5482. //ANY
  5483. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5484. url = Tools.CleanUrl(url);
  5485. var noIndexedDB = function () {
  5486. var request = new XMLHttpRequest();
  5487. var loadUrl = Tools.BaseUrl + url;
  5488. request.open('GET', loadUrl, true);
  5489. if (useArrayBuffer) {
  5490. request.responseType = "arraybuffer";
  5491. }
  5492. request.onprogress = progressCallBack;
  5493. request.onreadystatechange = function () {
  5494. if (request.readyState === 4) {
  5495. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5496. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5497. callback(!useArrayBuffer ? request.responseText : request.response);
  5498. }
  5499. else {
  5500. if (onError) {
  5501. onError();
  5502. }
  5503. else {
  5504. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5505. }
  5506. }
  5507. }
  5508. };
  5509. request.send(null);
  5510. };
  5511. var loadFromIndexedDB = function () {
  5512. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5513. };
  5514. if (url.indexOf("file:") !== -1) {
  5515. var fileName = url.substring(5).toLowerCase();
  5516. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5517. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5518. }
  5519. else {
  5520. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5521. }
  5522. }
  5523. else {
  5524. // Caching all files
  5525. if (database && database.enableSceneOffline) {
  5526. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5527. }
  5528. else {
  5529. noIndexedDB();
  5530. }
  5531. }
  5532. };
  5533. /**
  5534. * Load a script (identified by an url). When the url returns, the
  5535. * content of this file is added into a new script element, attached to the DOM (body element)
  5536. */
  5537. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5538. var head = document.getElementsByTagName('head')[0];
  5539. var script = document.createElement('script');
  5540. script.type = 'text/javascript';
  5541. script.src = scriptUrl;
  5542. var self = this;
  5543. script.onload = function () {
  5544. if (onSuccess) {
  5545. onSuccess();
  5546. }
  5547. };
  5548. script.onerror = function () {
  5549. if (onError) {
  5550. onError();
  5551. }
  5552. };
  5553. head.appendChild(script);
  5554. };
  5555. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5556. var reader = new FileReader();
  5557. reader.onload = function (e) {
  5558. //target doesn't have result from ts 1.3
  5559. callback(e.target['result']);
  5560. };
  5561. reader.onprogress = progressCallback;
  5562. reader.readAsDataURL(fileToLoad);
  5563. };
  5564. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5565. var reader = new FileReader();
  5566. reader.onerror = function (e) {
  5567. Tools.Log("Error while reading file: " + fileToLoad.name);
  5568. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5569. };
  5570. reader.onload = function (e) {
  5571. //target doesn't have result from ts 1.3
  5572. callback(e.target['result']);
  5573. };
  5574. reader.onprogress = progressCallBack;
  5575. if (!useArrayBuffer) {
  5576. // Asynchronous read
  5577. reader.readAsText(fileToLoad);
  5578. }
  5579. else {
  5580. reader.readAsArrayBuffer(fileToLoad);
  5581. }
  5582. };
  5583. //returns a downloadable url to a file content.
  5584. Tools.FileAsURL = function (content) {
  5585. var fileBlob = new Blob([content]);
  5586. var url = window.URL || window.webkitURL;
  5587. var link = url.createObjectURL(fileBlob);
  5588. return link;
  5589. };
  5590. // Misc.
  5591. Tools.Format = function (value, decimals) {
  5592. if (decimals === void 0) { decimals = 2; }
  5593. return value.toFixed(decimals);
  5594. };
  5595. Tools.CheckExtends = function (v, min, max) {
  5596. if (v.x < min.x)
  5597. min.x = v.x;
  5598. if (v.y < min.y)
  5599. min.y = v.y;
  5600. if (v.z < min.z)
  5601. min.z = v.z;
  5602. if (v.x > max.x)
  5603. max.x = v.x;
  5604. if (v.y > max.y)
  5605. max.y = v.y;
  5606. if (v.z > max.z)
  5607. max.z = v.z;
  5608. };
  5609. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5610. for (var prop in source) {
  5611. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5612. continue;
  5613. }
  5614. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5615. continue;
  5616. }
  5617. var sourceValue = source[prop];
  5618. var typeOfSourceValue = typeof sourceValue;
  5619. if (typeOfSourceValue === "function") {
  5620. continue;
  5621. }
  5622. if (typeOfSourceValue === "object") {
  5623. if (sourceValue instanceof Array) {
  5624. destination[prop] = [];
  5625. if (sourceValue.length > 0) {
  5626. if (typeof sourceValue[0] == "object") {
  5627. for (var index = 0; index < sourceValue.length; index++) {
  5628. var clonedValue = cloneValue(sourceValue[index], destination);
  5629. if (destination[prop].indexOf(clonedValue) === -1) {
  5630. destination[prop].push(clonedValue);
  5631. }
  5632. }
  5633. }
  5634. else {
  5635. destination[prop] = sourceValue.slice(0);
  5636. }
  5637. }
  5638. }
  5639. else {
  5640. destination[prop] = cloneValue(sourceValue, destination);
  5641. }
  5642. }
  5643. else {
  5644. destination[prop] = sourceValue;
  5645. }
  5646. }
  5647. };
  5648. Tools.IsEmpty = function (obj) {
  5649. for (var i in obj) {
  5650. return false;
  5651. }
  5652. return true;
  5653. };
  5654. Tools.RegisterTopRootEvents = function (events) {
  5655. for (var index = 0; index < events.length; index++) {
  5656. var event = events[index];
  5657. window.addEventListener(event.name, event.handler, false);
  5658. try {
  5659. if (window.parent) {
  5660. window.parent.addEventListener(event.name, event.handler, false);
  5661. }
  5662. }
  5663. catch (e) {
  5664. // Silently fails...
  5665. }
  5666. }
  5667. };
  5668. Tools.UnregisterTopRootEvents = function (events) {
  5669. for (var index = 0; index < events.length; index++) {
  5670. var event = events[index];
  5671. window.removeEventListener(event.name, event.handler);
  5672. try {
  5673. if (window.parent) {
  5674. window.parent.removeEventListener(event.name, event.handler);
  5675. }
  5676. }
  5677. catch (e) {
  5678. // Silently fails...
  5679. }
  5680. }
  5681. };
  5682. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5683. if (mimeType === void 0) { mimeType = "image/png"; }
  5684. // Read the contents of the framebuffer
  5685. var numberOfChannelsByLine = width * 4;
  5686. var halfHeight = height / 2;
  5687. //Reading datas from WebGL
  5688. var data = engine.readPixels(0, 0, width, height);
  5689. //To flip image on Y axis.
  5690. for (var i = 0; i < halfHeight; i++) {
  5691. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5692. var currentCell = j + i * numberOfChannelsByLine;
  5693. var targetLine = height - i - 1;
  5694. var targetCell = j + targetLine * numberOfChannelsByLine;
  5695. var temp = data[currentCell];
  5696. data[currentCell] = data[targetCell];
  5697. data[targetCell] = temp;
  5698. }
  5699. }
  5700. // Create a 2D canvas to store the result
  5701. if (!screenshotCanvas) {
  5702. screenshotCanvas = document.createElement('canvas');
  5703. }
  5704. screenshotCanvas.width = width;
  5705. screenshotCanvas.height = height;
  5706. var context = screenshotCanvas.getContext('2d');
  5707. // Copy the pixels to a 2D canvas
  5708. var imageData = context.createImageData(width, height);
  5709. var castData = (imageData.data);
  5710. castData.set(data);
  5711. context.putImageData(imageData, 0, 0);
  5712. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5713. };
  5714. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5715. if (mimeType === void 0) { mimeType = "image/png"; }
  5716. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5717. if (successCallback) {
  5718. successCallback(base64Image);
  5719. }
  5720. else {
  5721. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5722. if (("download" in document.createElement("a"))) {
  5723. var a = window.document.createElement("a");
  5724. a.href = base64Image;
  5725. var date = new Date();
  5726. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5727. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5728. window.document.body.appendChild(a);
  5729. a.addEventListener("click", function () {
  5730. a.parentElement.removeChild(a);
  5731. });
  5732. a.click();
  5733. //Or opening a new tab with the image if it is not possible to automatically start download.
  5734. }
  5735. else {
  5736. var newWindow = window.open("");
  5737. var img = newWindow.document.createElement("img");
  5738. img.src = base64Image;
  5739. newWindow.document.body.appendChild(img);
  5740. }
  5741. }
  5742. };
  5743. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5744. if (mimeType === void 0) { mimeType = "image/png"; }
  5745. var width;
  5746. var height;
  5747. // If a precision value is specified
  5748. if (size.precision) {
  5749. width = Math.round(engine.getRenderWidth() * size.precision);
  5750. height = Math.round(width / engine.getAspectRatio(camera));
  5751. }
  5752. else if (size.width && size.height) {
  5753. width = size.width;
  5754. height = size.height;
  5755. }
  5756. else if (size.width && !size.height) {
  5757. width = size.width;
  5758. height = Math.round(width / engine.getAspectRatio(camera));
  5759. }
  5760. else if (size.height && !size.width) {
  5761. height = size.height;
  5762. width = Math.round(height * engine.getAspectRatio(camera));
  5763. }
  5764. else if (!isNaN(size)) {
  5765. height = size;
  5766. width = size;
  5767. }
  5768. else {
  5769. Tools.Error("Invalid 'size' parameter !");
  5770. return;
  5771. }
  5772. if (!screenshotCanvas) {
  5773. screenshotCanvas = document.createElement('canvas');
  5774. }
  5775. screenshotCanvas.width = width;
  5776. screenshotCanvas.height = height;
  5777. var renderContext = screenshotCanvas.getContext("2d");
  5778. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5779. var newWidth = width;
  5780. var newHeight = newWidth / ratio;
  5781. if (newHeight > height) {
  5782. newHeight = height;
  5783. newWidth = newHeight * ratio;
  5784. }
  5785. var offsetX = Math.max(0, width - newWidth) / 2;
  5786. var offsetY = Math.max(0, height - newHeight) / 2;
  5787. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5788. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5789. };
  5790. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  5791. if (mimeType === void 0) { mimeType = "image/png"; }
  5792. if (samples === void 0) { samples = 1; }
  5793. var width;
  5794. var height;
  5795. //If a precision value is specified
  5796. if (size.precision) {
  5797. width = Math.round(engine.getRenderWidth() * size.precision);
  5798. height = Math.round(width / engine.getAspectRatio(camera));
  5799. size = { width: width, height: height };
  5800. }
  5801. else if (size.width && size.height) {
  5802. width = size.width;
  5803. height = size.height;
  5804. }
  5805. else if (size.width && !size.height) {
  5806. width = size.width;
  5807. height = Math.round(width / engine.getAspectRatio(camera));
  5808. size = { width: width, height: height };
  5809. }
  5810. else if (size.height && !size.width) {
  5811. height = size.height;
  5812. width = Math.round(height * engine.getAspectRatio(camera));
  5813. size = { width: width, height: height };
  5814. }
  5815. else if (!isNaN(size)) {
  5816. height = size;
  5817. width = size;
  5818. }
  5819. else {
  5820. Tools.Error("Invalid 'size' parameter !");
  5821. return;
  5822. }
  5823. var scene = camera.getScene();
  5824. var previousCamera = null;
  5825. if (scene.activeCamera !== camera) {
  5826. previousCamera = scene.activeCamera;
  5827. scene.activeCamera = camera;
  5828. }
  5829. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5830. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5831. texture.renderList = scene.meshes;
  5832. texture.samples = samples;
  5833. texture.onAfterRenderObservable.add(function () {
  5834. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5835. });
  5836. scene.incrementRenderId();
  5837. scene.resetCachedMaterial();
  5838. texture.render(true);
  5839. texture.dispose();
  5840. if (previousCamera) {
  5841. scene.activeCamera = previousCamera;
  5842. }
  5843. camera.getProjectionMatrix(true); // Force cache refresh;
  5844. };
  5845. // XHR response validator for local file scenario
  5846. Tools.ValidateXHRData = function (xhr, dataType) {
  5847. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5848. if (dataType === void 0) { dataType = 7; }
  5849. try {
  5850. if (dataType & 1) {
  5851. if (xhr.responseText && xhr.responseText.length > 0) {
  5852. return true;
  5853. }
  5854. else if (dataType === 1) {
  5855. return false;
  5856. }
  5857. }
  5858. if (dataType & 2) {
  5859. // Check header width and height since there is no "TGA" magic number
  5860. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5861. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5862. return true;
  5863. }
  5864. else if (dataType === 2) {
  5865. return false;
  5866. }
  5867. }
  5868. if (dataType & 4) {
  5869. // Check for the "DDS" magic number
  5870. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5871. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5872. return true;
  5873. }
  5874. else {
  5875. return false;
  5876. }
  5877. }
  5878. }
  5879. catch (e) {
  5880. // Global protection
  5881. }
  5882. return false;
  5883. };
  5884. /**
  5885. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5886. * Be aware Math.random() could cause collisions, but:
  5887. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  5888. */
  5889. Tools.RandomId = function () {
  5890. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5891. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5892. return v.toString(16);
  5893. });
  5894. };
  5895. Object.defineProperty(Tools, "NoneLogLevel", {
  5896. get: function () {
  5897. return Tools._NoneLogLevel;
  5898. },
  5899. enumerable: true,
  5900. configurable: true
  5901. });
  5902. Object.defineProperty(Tools, "MessageLogLevel", {
  5903. get: function () {
  5904. return Tools._MessageLogLevel;
  5905. },
  5906. enumerable: true,
  5907. configurable: true
  5908. });
  5909. Object.defineProperty(Tools, "WarningLogLevel", {
  5910. get: function () {
  5911. return Tools._WarningLogLevel;
  5912. },
  5913. enumerable: true,
  5914. configurable: true
  5915. });
  5916. Object.defineProperty(Tools, "ErrorLogLevel", {
  5917. get: function () {
  5918. return Tools._ErrorLogLevel;
  5919. },
  5920. enumerable: true,
  5921. configurable: true
  5922. });
  5923. Object.defineProperty(Tools, "AllLogLevel", {
  5924. get: function () {
  5925. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5926. },
  5927. enumerable: true,
  5928. configurable: true
  5929. });
  5930. Tools._AddLogEntry = function (entry) {
  5931. Tools._LogCache = entry + Tools._LogCache;
  5932. if (Tools.OnNewCacheEntry) {
  5933. Tools.OnNewCacheEntry(entry);
  5934. }
  5935. };
  5936. Tools._FormatMessage = function (message) {
  5937. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5938. var date = new Date();
  5939. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5940. };
  5941. Tools._LogDisabled = function (message) {
  5942. // nothing to do
  5943. };
  5944. Tools._LogEnabled = function (message) {
  5945. var formattedMessage = Tools._FormatMessage(message);
  5946. console.log("BJS - " + formattedMessage);
  5947. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5948. Tools._AddLogEntry(entry);
  5949. };
  5950. Tools._WarnDisabled = function (message) {
  5951. // nothing to do
  5952. };
  5953. Tools._WarnEnabled = function (message) {
  5954. var formattedMessage = Tools._FormatMessage(message);
  5955. console.warn("BJS - " + formattedMessage);
  5956. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5957. Tools._AddLogEntry(entry);
  5958. };
  5959. Tools._ErrorDisabled = function (message) {
  5960. // nothing to do
  5961. };
  5962. Tools._ErrorEnabled = function (message) {
  5963. Tools.errorsCount++;
  5964. var formattedMessage = Tools._FormatMessage(message);
  5965. console.error("BJS - " + formattedMessage);
  5966. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5967. Tools._AddLogEntry(entry);
  5968. };
  5969. Object.defineProperty(Tools, "LogCache", {
  5970. get: function () {
  5971. return Tools._LogCache;
  5972. },
  5973. enumerable: true,
  5974. configurable: true
  5975. });
  5976. Tools.ClearLogCache = function () {
  5977. Tools._LogCache = "";
  5978. Tools.errorsCount = 0;
  5979. };
  5980. Object.defineProperty(Tools, "LogLevels", {
  5981. set: function (level) {
  5982. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5983. Tools.Log = Tools._LogEnabled;
  5984. }
  5985. else {
  5986. Tools.Log = Tools._LogDisabled;
  5987. }
  5988. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5989. Tools.Warn = Tools._WarnEnabled;
  5990. }
  5991. else {
  5992. Tools.Warn = Tools._WarnDisabled;
  5993. }
  5994. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5995. Tools.Error = Tools._ErrorEnabled;
  5996. }
  5997. else {
  5998. Tools.Error = Tools._ErrorDisabled;
  5999. }
  6000. },
  6001. enumerable: true,
  6002. configurable: true
  6003. });
  6004. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6005. get: function () {
  6006. return Tools._PerformanceNoneLogLevel;
  6007. },
  6008. enumerable: true,
  6009. configurable: true
  6010. });
  6011. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6012. get: function () {
  6013. return Tools._PerformanceUserMarkLogLevel;
  6014. },
  6015. enumerable: true,
  6016. configurable: true
  6017. });
  6018. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6019. get: function () {
  6020. return Tools._PerformanceConsoleLogLevel;
  6021. },
  6022. enumerable: true,
  6023. configurable: true
  6024. });
  6025. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6026. set: function (level) {
  6027. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6028. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6029. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6030. return;
  6031. }
  6032. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6033. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6034. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6035. return;
  6036. }
  6037. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6038. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6039. },
  6040. enumerable: true,
  6041. configurable: true
  6042. });
  6043. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6044. };
  6045. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6046. };
  6047. Tools._StartUserMark = function (counterName, condition) {
  6048. if (condition === void 0) { condition = true; }
  6049. if (!condition || !Tools._performance.mark) {
  6050. return;
  6051. }
  6052. Tools._performance.mark(counterName + "-Begin");
  6053. };
  6054. Tools._EndUserMark = function (counterName, condition) {
  6055. if (condition === void 0) { condition = true; }
  6056. if (!condition || !Tools._performance.mark) {
  6057. return;
  6058. }
  6059. Tools._performance.mark(counterName + "-End");
  6060. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6061. };
  6062. Tools._StartPerformanceConsole = function (counterName, condition) {
  6063. if (condition === void 0) { condition = true; }
  6064. if (!condition) {
  6065. return;
  6066. }
  6067. Tools._StartUserMark(counterName, condition);
  6068. if (console.time) {
  6069. console.time(counterName);
  6070. }
  6071. };
  6072. Tools._EndPerformanceConsole = function (counterName, condition) {
  6073. if (condition === void 0) { condition = true; }
  6074. if (!condition) {
  6075. return;
  6076. }
  6077. Tools._EndUserMark(counterName, condition);
  6078. if (console.time) {
  6079. console.timeEnd(counterName);
  6080. }
  6081. };
  6082. Object.defineProperty(Tools, "Now", {
  6083. get: function () {
  6084. if (window.performance && window.performance.now) {
  6085. return window.performance.now();
  6086. }
  6087. return new Date().getTime();
  6088. },
  6089. enumerable: true,
  6090. configurable: true
  6091. });
  6092. /**
  6093. * This method will return the name of the class used to create the instance of the given object.
  6094. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6095. * @param object the object to get the class name from
  6096. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6097. */
  6098. Tools.getClassName = function (object, isType) {
  6099. if (isType === void 0) { isType = false; }
  6100. var name = null;
  6101. if (!isType && object.getClassName) {
  6102. name = object.getClassName();
  6103. }
  6104. else {
  6105. if (object instanceof Object) {
  6106. var classObj = isType ? object : Object.getPrototypeOf(object);
  6107. name = classObj.constructor["__bjsclassName__"];
  6108. }
  6109. if (!name) {
  6110. name = typeof object;
  6111. }
  6112. }
  6113. return name;
  6114. };
  6115. Tools.first = function (array, predicate) {
  6116. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6117. var el = array_1[_i];
  6118. if (predicate(el)) {
  6119. return el;
  6120. }
  6121. }
  6122. };
  6123. /**
  6124. * This method will return the name of the full name of the class, including its owning module (if any).
  6125. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  6126. * @param object the object to get the class name from
  6127. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  6128. */
  6129. Tools.getFullClassName = function (object, isType) {
  6130. if (isType === void 0) { isType = false; }
  6131. var className = null;
  6132. var moduleName = null;
  6133. if (!isType && object.getClassName) {
  6134. className = object.getClassName();
  6135. }
  6136. else {
  6137. if (object instanceof Object) {
  6138. var classObj = isType ? object : Object.getPrototypeOf(object);
  6139. className = classObj.constructor["__bjsclassName__"];
  6140. moduleName = classObj.constructor["__bjsmoduleName__"];
  6141. }
  6142. if (!className) {
  6143. className = typeof object;
  6144. }
  6145. }
  6146. if (!className) {
  6147. return null;
  6148. }
  6149. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6150. };
  6151. /**
  6152. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  6153. * @param array
  6154. */
  6155. Tools.arrayOrStringFeeder = function (array) {
  6156. return function (index) {
  6157. if (index >= array.length) {
  6158. return null;
  6159. }
  6160. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6161. if (val && val.getHashCode) {
  6162. val = val.getHashCode();
  6163. }
  6164. if (typeof val === "string") {
  6165. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6166. }
  6167. return val;
  6168. };
  6169. };
  6170. /**
  6171. * Compute the hashCode of a stream of number
  6172. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6173. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6174. * @return the hash code computed
  6175. */
  6176. Tools.hashCodeFromStream = function (feeder) {
  6177. // Based from here: http://stackoverflow.com/a/7616484/802124
  6178. var hash = 0;
  6179. var index = 0;
  6180. var chr = feeder(index++);
  6181. while (chr != null) {
  6182. hash = ((hash << 5) - hash) + chr;
  6183. hash |= 0; // Convert to 32bit integer
  6184. chr = feeder(index++);
  6185. }
  6186. return hash;
  6187. };
  6188. return Tools;
  6189. }());
  6190. Tools.BaseUrl = "";
  6191. Tools.CorsBehavior = "anonymous";
  6192. Tools.UseFallbackTexture = true;
  6193. // Used in case of a texture loading problem
  6194. Tools.fallbackTexture = "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";
  6195. // Logs
  6196. Tools._NoneLogLevel = 0;
  6197. Tools._MessageLogLevel = 1;
  6198. Tools._WarningLogLevel = 2;
  6199. Tools._ErrorLogLevel = 4;
  6200. Tools._LogCache = "";
  6201. Tools.errorsCount = 0;
  6202. Tools.Log = Tools._LogEnabled;
  6203. Tools.Warn = Tools._WarnEnabled;
  6204. Tools.Error = Tools._ErrorEnabled;
  6205. // Performances
  6206. Tools._PerformanceNoneLogLevel = 0;
  6207. Tools._PerformanceUserMarkLogLevel = 1;
  6208. Tools._PerformanceConsoleLogLevel = 2;
  6209. Tools._performance = window.performance;
  6210. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6211. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6212. BABYLON.Tools = Tools;
  6213. /**
  6214. * This class is used to track a performance counter which is number based.
  6215. * The user has access to many properties which give statistics of different nature
  6216. *
  6217. * The implementer can track two kinds of Performance Counter: time and count
  6218. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  6219. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  6220. */
  6221. var PerfCounter = (function () {
  6222. function PerfCounter() {
  6223. this._startMonitoringTime = 0;
  6224. this._min = 0;
  6225. this._max = 0;
  6226. this._average = 0;
  6227. this._lastSecAverage = 0;
  6228. this._current = 0;
  6229. this._totalValueCount = 0;
  6230. this._totalAccumulated = 0;
  6231. this._lastSecAccumulated = 0;
  6232. this._lastSecTime = 0;
  6233. this._lastSecValueCount = 0;
  6234. }
  6235. Object.defineProperty(PerfCounter.prototype, "min", {
  6236. /**
  6237. * Returns the smallest value ever
  6238. */
  6239. get: function () {
  6240. return this._min;
  6241. },
  6242. enumerable: true,
  6243. configurable: true
  6244. });
  6245. Object.defineProperty(PerfCounter.prototype, "max", {
  6246. /**
  6247. * Returns the biggest value ever
  6248. */
  6249. get: function () {
  6250. return this._max;
  6251. },
  6252. enumerable: true,
  6253. configurable: true
  6254. });
  6255. Object.defineProperty(PerfCounter.prototype, "average", {
  6256. /**
  6257. * Returns the average value since the performance counter is running
  6258. */
  6259. get: function () {
  6260. return this._average;
  6261. },
  6262. enumerable: true,
  6263. configurable: true
  6264. });
  6265. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6266. /**
  6267. * Returns the average value of the last second the counter was monitored
  6268. */
  6269. get: function () {
  6270. return this._lastSecAverage;
  6271. },
  6272. enumerable: true,
  6273. configurable: true
  6274. });
  6275. Object.defineProperty(PerfCounter.prototype, "current", {
  6276. /**
  6277. * Returns the current value
  6278. */
  6279. get: function () {
  6280. return this._current;
  6281. },
  6282. enumerable: true,
  6283. configurable: true
  6284. });
  6285. Object.defineProperty(PerfCounter.prototype, "total", {
  6286. get: function () {
  6287. return this._totalAccumulated;
  6288. },
  6289. enumerable: true,
  6290. configurable: true
  6291. });
  6292. /**
  6293. * Call this method to start monitoring a new frame.
  6294. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  6295. */
  6296. PerfCounter.prototype.fetchNewFrame = function () {
  6297. this._totalValueCount++;
  6298. this._current = 0;
  6299. this._lastSecValueCount++;
  6300. };
  6301. /**
  6302. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6303. * @param newCount the count value to add to the monitored count
  6304. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  6305. */
  6306. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6307. if (!PerfCounter.Enabled) {
  6308. return;
  6309. }
  6310. this._current += newCount;
  6311. if (fetchResult) {
  6312. this._fetchResult();
  6313. }
  6314. };
  6315. /**
  6316. * Start monitoring this performance counter
  6317. */
  6318. PerfCounter.prototype.beginMonitoring = function () {
  6319. if (!PerfCounter.Enabled) {
  6320. return;
  6321. }
  6322. this._startMonitoringTime = Tools.Now;
  6323. };
  6324. /**
  6325. * Compute the time lapsed since the previous beginMonitoring() call.
  6326. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  6327. */
  6328. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6329. if (newFrame === void 0) { newFrame = true; }
  6330. if (!PerfCounter.Enabled) {
  6331. return;
  6332. }
  6333. if (newFrame) {
  6334. this.fetchNewFrame();
  6335. }
  6336. var currentTime = Tools.Now;
  6337. this._current = currentTime - this._startMonitoringTime;
  6338. if (newFrame) {
  6339. this._fetchResult();
  6340. }
  6341. };
  6342. PerfCounter.prototype._fetchResult = function () {
  6343. this._totalAccumulated += this._current;
  6344. this._lastSecAccumulated += this._current;
  6345. // Min/Max update
  6346. this._min = Math.min(this._min, this._current);
  6347. this._max = Math.max(this._max, this._current);
  6348. this._average = this._totalAccumulated / this._totalValueCount;
  6349. // Reset last sec?
  6350. var now = Tools.Now;
  6351. if ((now - this._lastSecTime) > 1000) {
  6352. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6353. this._lastSecTime = now;
  6354. this._lastSecAccumulated = 0;
  6355. this._lastSecValueCount = 0;
  6356. }
  6357. };
  6358. return PerfCounter;
  6359. }());
  6360. PerfCounter.Enabled = true;
  6361. BABYLON.PerfCounter = PerfCounter;
  6362. /**
  6363. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6364. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6365. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6366. * @param name The name of the class, case should be preserved
  6367. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6368. */
  6369. function className(name, module) {
  6370. return function (target) {
  6371. target["__bjsclassName__"] = name;
  6372. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6373. };
  6374. }
  6375. BABYLON.className = className;
  6376. /**
  6377. * An implementation of a loop for asynchronous functions.
  6378. */
  6379. var AsyncLoop = (function () {
  6380. /**
  6381. * Constroctor.
  6382. * @param iterations the number of iterations.
  6383. * @param _fn the function to run each iteration
  6384. * @param _successCallback the callback that will be called upon succesful execution
  6385. * @param offset starting offset.
  6386. */
  6387. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6388. if (offset === void 0) { offset = 0; }
  6389. this.iterations = iterations;
  6390. this._fn = _fn;
  6391. this._successCallback = _successCallback;
  6392. this.index = offset - 1;
  6393. this._done = false;
  6394. }
  6395. /**
  6396. * Execute the next iteration. Must be called after the last iteration was finished.
  6397. */
  6398. AsyncLoop.prototype.executeNext = function () {
  6399. if (!this._done) {
  6400. if (this.index + 1 < this.iterations) {
  6401. ++this.index;
  6402. this._fn(this);
  6403. }
  6404. else {
  6405. this.breakLoop();
  6406. }
  6407. }
  6408. };
  6409. /**
  6410. * Break the loop and run the success callback.
  6411. */
  6412. AsyncLoop.prototype.breakLoop = function () {
  6413. this._done = true;
  6414. this._successCallback();
  6415. };
  6416. /**
  6417. * Helper function
  6418. */
  6419. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6420. if (offset === void 0) { offset = 0; }
  6421. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6422. loop.executeNext();
  6423. return loop;
  6424. };
  6425. /**
  6426. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6427. * @param iterations total number of iterations
  6428. * @param syncedIterations number of synchronous iterations in each async iteration.
  6429. * @param fn the function to call each iteration.
  6430. * @param callback a success call back that will be called when iterating stops.
  6431. * @param breakFunction a break condition (optional)
  6432. * @param timeout timeout settings for the setTimeout function. default - 0.
  6433. * @constructor
  6434. */
  6435. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6436. if (timeout === void 0) { timeout = 0; }
  6437. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6438. if (breakFunction && breakFunction())
  6439. loop.breakLoop();
  6440. else {
  6441. setTimeout(function () {
  6442. for (var i = 0; i < syncedIterations; ++i) {
  6443. var iteration = (loop.index * syncedIterations) + i;
  6444. if (iteration >= iterations)
  6445. break;
  6446. fn(iteration);
  6447. if (breakFunction && breakFunction()) {
  6448. loop.breakLoop();
  6449. break;
  6450. }
  6451. }
  6452. loop.executeNext();
  6453. }, timeout);
  6454. }
  6455. }, callback);
  6456. };
  6457. return AsyncLoop;
  6458. }());
  6459. BABYLON.AsyncLoop = AsyncLoop;
  6460. })(BABYLON || (BABYLON = {}));
  6461. //# sourceMappingURL=babylon.tools.js.map
  6462. var BABYLON;
  6463. (function (BABYLON) {
  6464. var Internals;
  6465. (function (Internals) {
  6466. var _AlphaState = (function () {
  6467. /**
  6468. * Initializes the state.
  6469. */
  6470. function _AlphaState() {
  6471. this._isAlphaBlendDirty = false;
  6472. this._isBlendFunctionParametersDirty = false;
  6473. this._alphaBlend = false;
  6474. this._blendFunctionParameters = new Array(4);
  6475. this.reset();
  6476. }
  6477. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6478. get: function () {
  6479. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6480. },
  6481. enumerable: true,
  6482. configurable: true
  6483. });
  6484. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6485. get: function () {
  6486. return this._alphaBlend;
  6487. },
  6488. set: function (value) {
  6489. if (this._alphaBlend === value) {
  6490. return;
  6491. }
  6492. this._alphaBlend = value;
  6493. this._isAlphaBlendDirty = true;
  6494. },
  6495. enumerable: true,
  6496. configurable: true
  6497. });
  6498. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6499. if (this._blendFunctionParameters[0] === value0 &&
  6500. this._blendFunctionParameters[1] === value1 &&
  6501. this._blendFunctionParameters[2] === value2 &&
  6502. this._blendFunctionParameters[3] === value3) {
  6503. return;
  6504. }
  6505. this._blendFunctionParameters[0] = value0;
  6506. this._blendFunctionParameters[1] = value1;
  6507. this._blendFunctionParameters[2] = value2;
  6508. this._blendFunctionParameters[3] = value3;
  6509. this._isBlendFunctionParametersDirty = true;
  6510. };
  6511. _AlphaState.prototype.reset = function () {
  6512. this._alphaBlend = false;
  6513. this._blendFunctionParameters[0] = null;
  6514. this._blendFunctionParameters[1] = null;
  6515. this._blendFunctionParameters[2] = null;
  6516. this._blendFunctionParameters[3] = null;
  6517. this._isAlphaBlendDirty = true;
  6518. this._isBlendFunctionParametersDirty = false;
  6519. };
  6520. _AlphaState.prototype.apply = function (gl) {
  6521. if (!this.isDirty) {
  6522. return;
  6523. }
  6524. // Alpha blend
  6525. if (this._isAlphaBlendDirty) {
  6526. if (this._alphaBlend) {
  6527. gl.enable(gl.BLEND);
  6528. }
  6529. else {
  6530. gl.disable(gl.BLEND);
  6531. }
  6532. this._isAlphaBlendDirty = false;
  6533. }
  6534. // Alpha function
  6535. if (this._isBlendFunctionParametersDirty) {
  6536. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6537. this._isBlendFunctionParametersDirty = false;
  6538. }
  6539. };
  6540. return _AlphaState;
  6541. }());
  6542. Internals._AlphaState = _AlphaState;
  6543. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6544. })(BABYLON || (BABYLON = {}));
  6545. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6546. var BABYLON;
  6547. (function (BABYLON) {
  6548. var Internals;
  6549. (function (Internals) {
  6550. var _DepthCullingState = (function () {
  6551. /**
  6552. * Initializes the state.
  6553. */
  6554. function _DepthCullingState() {
  6555. this._isDepthTestDirty = false;
  6556. this._isDepthMaskDirty = false;
  6557. this._isDepthFuncDirty = false;
  6558. this._isCullFaceDirty = false;
  6559. this._isCullDirty = false;
  6560. this._isZOffsetDirty = false;
  6561. this.reset();
  6562. }
  6563. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6564. get: function () {
  6565. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6566. },
  6567. enumerable: true,
  6568. configurable: true
  6569. });
  6570. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6571. get: function () {
  6572. return this._zOffset;
  6573. },
  6574. set: function (value) {
  6575. if (this._zOffset === value) {
  6576. return;
  6577. }
  6578. this._zOffset = value;
  6579. this._isZOffsetDirty = true;
  6580. },
  6581. enumerable: true,
  6582. configurable: true
  6583. });
  6584. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6585. get: function () {
  6586. return this._cullFace;
  6587. },
  6588. set: function (value) {
  6589. if (this._cullFace === value) {
  6590. return;
  6591. }
  6592. this._cullFace = value;
  6593. this._isCullFaceDirty = true;
  6594. },
  6595. enumerable: true,
  6596. configurable: true
  6597. });
  6598. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6599. get: function () {
  6600. return this._cull;
  6601. },
  6602. set: function (value) {
  6603. if (this._cull === value) {
  6604. return;
  6605. }
  6606. this._cull = value;
  6607. this._isCullDirty = true;
  6608. },
  6609. enumerable: true,
  6610. configurable: true
  6611. });
  6612. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6613. get: function () {
  6614. return this._depthFunc;
  6615. },
  6616. set: function (value) {
  6617. if (this._depthFunc === value) {
  6618. return;
  6619. }
  6620. this._depthFunc = value;
  6621. this._isDepthFuncDirty = true;
  6622. },
  6623. enumerable: true,
  6624. configurable: true
  6625. });
  6626. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6627. get: function () {
  6628. return this._depthMask;
  6629. },
  6630. set: function (value) {
  6631. if (this._depthMask === value) {
  6632. return;
  6633. }
  6634. this._depthMask = value;
  6635. this._isDepthMaskDirty = true;
  6636. },
  6637. enumerable: true,
  6638. configurable: true
  6639. });
  6640. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6641. get: function () {
  6642. return this._depthTest;
  6643. },
  6644. set: function (value) {
  6645. if (this._depthTest === value) {
  6646. return;
  6647. }
  6648. this._depthTest = value;
  6649. this._isDepthTestDirty = true;
  6650. },
  6651. enumerable: true,
  6652. configurable: true
  6653. });
  6654. _DepthCullingState.prototype.reset = function () {
  6655. this._depthMask = true;
  6656. this._depthTest = true;
  6657. this._depthFunc = null;
  6658. this._cullFace = null;
  6659. this._cull = null;
  6660. this._zOffset = 0;
  6661. this._isDepthTestDirty = true;
  6662. this._isDepthMaskDirty = true;
  6663. this._isDepthFuncDirty = false;
  6664. this._isCullFaceDirty = false;
  6665. this._isCullDirty = false;
  6666. this._isZOffsetDirty = false;
  6667. };
  6668. _DepthCullingState.prototype.apply = function (gl) {
  6669. if (!this.isDirty) {
  6670. return;
  6671. }
  6672. // Cull
  6673. if (this._isCullDirty) {
  6674. if (this.cull) {
  6675. gl.enable(gl.CULL_FACE);
  6676. }
  6677. else {
  6678. gl.disable(gl.CULL_FACE);
  6679. }
  6680. this._isCullDirty = false;
  6681. }
  6682. // Cull face
  6683. if (this._isCullFaceDirty) {
  6684. gl.cullFace(this.cullFace);
  6685. this._isCullFaceDirty = false;
  6686. }
  6687. // Depth mask
  6688. if (this._isDepthMaskDirty) {
  6689. gl.depthMask(this.depthMask);
  6690. this._isDepthMaskDirty = false;
  6691. }
  6692. // Depth test
  6693. if (this._isDepthTestDirty) {
  6694. if (this.depthTest) {
  6695. gl.enable(gl.DEPTH_TEST);
  6696. }
  6697. else {
  6698. gl.disable(gl.DEPTH_TEST);
  6699. }
  6700. this._isDepthTestDirty = false;
  6701. }
  6702. // Depth func
  6703. if (this._isDepthFuncDirty) {
  6704. gl.depthFunc(this.depthFunc);
  6705. this._isDepthFuncDirty = false;
  6706. }
  6707. // zOffset
  6708. if (this._isZOffsetDirty) {
  6709. if (this.zOffset) {
  6710. gl.enable(gl.POLYGON_OFFSET_FILL);
  6711. gl.polygonOffset(this.zOffset, 0);
  6712. }
  6713. else {
  6714. gl.disable(gl.POLYGON_OFFSET_FILL);
  6715. }
  6716. this._isZOffsetDirty = false;
  6717. }
  6718. };
  6719. return _DepthCullingState;
  6720. }());
  6721. Internals._DepthCullingState = _DepthCullingState;
  6722. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6723. })(BABYLON || (BABYLON = {}));
  6724. //# sourceMappingURL=babylon.depthCullingState.js.map
  6725. var BABYLON;
  6726. (function (BABYLON) {
  6727. var Internals;
  6728. (function (Internals) {
  6729. var _StencilState = (function () {
  6730. function _StencilState() {
  6731. this._isStencilTestDirty = false;
  6732. this._isStencilMaskDirty = false;
  6733. this._isStencilFuncDirty = false;
  6734. this._isStencilOpDirty = false;
  6735. this.reset();
  6736. }
  6737. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6738. get: function () {
  6739. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6740. },
  6741. enumerable: true,
  6742. configurable: true
  6743. });
  6744. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6745. get: function () {
  6746. return this._stencilFunc;
  6747. },
  6748. set: function (value) {
  6749. if (this._stencilFunc === value) {
  6750. return;
  6751. }
  6752. this._stencilFunc = value;
  6753. this._isStencilFuncDirty = true;
  6754. },
  6755. enumerable: true,
  6756. configurable: true
  6757. });
  6758. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6759. get: function () {
  6760. return this._stencilFuncRef;
  6761. },
  6762. set: function (value) {
  6763. if (this._stencilFuncRef === value) {
  6764. return;
  6765. }
  6766. this._stencilFuncRef = value;
  6767. this._isStencilFuncDirty = true;
  6768. },
  6769. enumerable: true,
  6770. configurable: true
  6771. });
  6772. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6773. get: function () {
  6774. return this._stencilFuncMask;
  6775. },
  6776. set: function (value) {
  6777. if (this._stencilFuncMask === value) {
  6778. return;
  6779. }
  6780. this._stencilFuncMask = value;
  6781. this._isStencilFuncDirty = true;
  6782. },
  6783. enumerable: true,
  6784. configurable: true
  6785. });
  6786. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6787. get: function () {
  6788. return this._stencilOpStencilFail;
  6789. },
  6790. set: function (value) {
  6791. if (this._stencilOpStencilFail === value) {
  6792. return;
  6793. }
  6794. this._stencilOpStencilFail = value;
  6795. this._isStencilOpDirty = true;
  6796. },
  6797. enumerable: true,
  6798. configurable: true
  6799. });
  6800. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6801. get: function () {
  6802. return this._stencilOpDepthFail;
  6803. },
  6804. set: function (value) {
  6805. if (this._stencilOpDepthFail === value) {
  6806. return;
  6807. }
  6808. this._stencilOpDepthFail = value;
  6809. this._isStencilOpDirty = true;
  6810. },
  6811. enumerable: true,
  6812. configurable: true
  6813. });
  6814. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6815. get: function () {
  6816. return this._stencilOpStencilDepthPass;
  6817. },
  6818. set: function (value) {
  6819. if (this._stencilOpStencilDepthPass === value) {
  6820. return;
  6821. }
  6822. this._stencilOpStencilDepthPass = value;
  6823. this._isStencilOpDirty = true;
  6824. },
  6825. enumerable: true,
  6826. configurable: true
  6827. });
  6828. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6829. get: function () {
  6830. return this._stencilMask;
  6831. },
  6832. set: function (value) {
  6833. if (this._stencilMask === value) {
  6834. return;
  6835. }
  6836. this._stencilMask = value;
  6837. this._isStencilMaskDirty = true;
  6838. },
  6839. enumerable: true,
  6840. configurable: true
  6841. });
  6842. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6843. get: function () {
  6844. return this._stencilTest;
  6845. },
  6846. set: function (value) {
  6847. if (this._stencilTest === value) {
  6848. return;
  6849. }
  6850. this._stencilTest = value;
  6851. this._isStencilTestDirty = true;
  6852. },
  6853. enumerable: true,
  6854. configurable: true
  6855. });
  6856. _StencilState.prototype.reset = function () {
  6857. this._stencilTest = false;
  6858. this._stencilMask = 0xFF;
  6859. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6860. this._stencilFuncRef = 1;
  6861. this._stencilFuncMask = 0xFF;
  6862. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6863. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6864. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6865. this._isStencilTestDirty = true;
  6866. this._isStencilMaskDirty = true;
  6867. this._isStencilFuncDirty = true;
  6868. this._isStencilOpDirty = true;
  6869. };
  6870. _StencilState.prototype.apply = function (gl) {
  6871. if (!this.isDirty) {
  6872. return;
  6873. }
  6874. // Stencil test
  6875. if (this._isStencilTestDirty) {
  6876. if (this.stencilTest) {
  6877. gl.enable(gl.STENCIL_TEST);
  6878. }
  6879. else {
  6880. gl.disable(gl.STENCIL_TEST);
  6881. }
  6882. this._isStencilTestDirty = false;
  6883. }
  6884. // Stencil mask
  6885. if (this._isStencilMaskDirty) {
  6886. gl.stencilMask(this.stencilMask);
  6887. this._isStencilMaskDirty = false;
  6888. }
  6889. // Stencil func
  6890. if (this._isStencilFuncDirty) {
  6891. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6892. this._isStencilFuncDirty = false;
  6893. }
  6894. // Stencil op
  6895. if (this._isStencilOpDirty) {
  6896. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6897. this._isStencilOpDirty = false;
  6898. }
  6899. };
  6900. return _StencilState;
  6901. }());
  6902. Internals._StencilState = _StencilState;
  6903. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6904. })(BABYLON || (BABYLON = {}));
  6905. //# sourceMappingURL=babylon.stencilState.js.map
  6906. var BABYLON;
  6907. (function (BABYLON) {
  6908. var compileShader = function (gl, source, type, defines, shaderVersion) {
  6909. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6910. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  6911. gl.compileShader(shader);
  6912. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6913. throw new Error(gl.getShaderInfoLog(shader));
  6914. }
  6915. return shader;
  6916. };
  6917. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6918. var magFilter = gl.NEAREST;
  6919. var minFilter = gl.NEAREST;
  6920. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6921. magFilter = gl.LINEAR;
  6922. if (generateMipMaps) {
  6923. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6924. }
  6925. else {
  6926. minFilter = gl.LINEAR;
  6927. }
  6928. }
  6929. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6930. magFilter = gl.LINEAR;
  6931. if (generateMipMaps) {
  6932. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6933. }
  6934. else {
  6935. minFilter = gl.LINEAR;
  6936. }
  6937. }
  6938. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6939. magFilter = gl.NEAREST;
  6940. if (generateMipMaps) {
  6941. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6942. }
  6943. else {
  6944. minFilter = gl.NEAREST;
  6945. }
  6946. }
  6947. return {
  6948. min: minFilter,
  6949. mag: magFilter
  6950. };
  6951. };
  6952. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6953. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6954. var engine = scene.getEngine();
  6955. if (!engine) {
  6956. return;
  6957. }
  6958. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6959. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6960. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6961. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6962. texture._baseWidth = width;
  6963. texture._baseHeight = height;
  6964. texture._width = potWidth;
  6965. texture._height = potHeight;
  6966. texture.isReady = true;
  6967. processFunction(potWidth, potHeight);
  6968. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6969. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6970. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6971. if (!noMipmap && !isCompressed) {
  6972. gl.generateMipmap(gl.TEXTURE_2D);
  6973. }
  6974. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6975. engine.resetTextureCache();
  6976. scene._removePendingData(texture);
  6977. texture.onLoadedCallbacks.forEach(function (callback) {
  6978. callback();
  6979. });
  6980. texture.onLoadedCallbacks = [];
  6981. };
  6982. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  6983. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  6984. var img;
  6985. var onload = function () {
  6986. loadedImages[index] = img;
  6987. loadedImages._internalCount++;
  6988. scene._removePendingData(img);
  6989. if (loadedImages._internalCount === 6) {
  6990. onfinish(loadedImages);
  6991. }
  6992. };
  6993. var onerror = function () {
  6994. scene._removePendingData(img);
  6995. if (onErrorCallBack) {
  6996. onErrorCallBack();
  6997. }
  6998. };
  6999. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7000. scene._addPendingData(img);
  7001. };
  7002. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7003. if (onError === void 0) { onError = null; }
  7004. var loadedImages = [];
  7005. loadedImages._internalCount = 0;
  7006. for (var index = 0; index < 6; index++) {
  7007. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7008. }
  7009. };
  7010. var InstancingAttributeInfo = (function () {
  7011. function InstancingAttributeInfo() {
  7012. }
  7013. return InstancingAttributeInfo;
  7014. }());
  7015. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7016. var EngineCapabilities = (function () {
  7017. function EngineCapabilities() {
  7018. }
  7019. return EngineCapabilities;
  7020. }());
  7021. BABYLON.EngineCapabilities = EngineCapabilities;
  7022. /**
  7023. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7024. */
  7025. var Engine = (function () {
  7026. /**
  7027. * @constructor
  7028. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7029. * @param {boolean} [antialias] - enable antialias
  7030. * @param options - further options to be sent to the getContext function
  7031. */
  7032. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7033. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7034. var _this = this;
  7035. // Public members
  7036. this.isFullscreen = false;
  7037. this.isPointerLock = false;
  7038. this.cullBackFaces = true;
  7039. this.renderEvenInBackground = true;
  7040. this.preventCacheWipeBetweenFrames = false;
  7041. // To enable/disable IDB support and avoid XHR on .manifest
  7042. this.enableOfflineSupport = BABYLON.Database;
  7043. this.scenes = new Array();
  7044. // Observables
  7045. /**
  7046. * Observable event triggered each time the rendering canvas is resized
  7047. */
  7048. this.onResizeObservable = new BABYLON.Observable();
  7049. this._windowIsBackground = false;
  7050. this._webGLVersion = 1.0;
  7051. this._badOS = false;
  7052. this._drawCalls = new BABYLON.PerfCounter();
  7053. this._renderingQueueLaunched = false;
  7054. this._activeRenderLoops = [];
  7055. // FPS
  7056. this.fpsRange = 60;
  7057. this.previousFramesDuration = [];
  7058. this.fps = 60;
  7059. this.deltaTime = 0;
  7060. // States
  7061. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7062. this._stencilState = new BABYLON.Internals._StencilState();
  7063. this._alphaState = new BABYLON.Internals._AlphaState();
  7064. this._alphaMode = Engine.ALPHA_DISABLE;
  7065. // Cache
  7066. this._loadedTexturesCache = new Array();
  7067. this._maxTextureChannels = 16;
  7068. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7069. this._compiledEffects = {};
  7070. this._vertexAttribArraysEnabled = [];
  7071. this._uintIndicesCurrentlySet = false;
  7072. this._currentBoundBuffer = new Array();
  7073. this._currentBufferPointers = [];
  7074. this._currentInstanceLocations = new Array();
  7075. this._currentInstanceBuffers = new Array();
  7076. this._vaoRecordInProgress = false;
  7077. this._mustWipeVertexAttributes = false;
  7078. // Hardware supported Compressed Textures
  7079. this._texturesSupported = new Array();
  7080. this._onVRFullScreenTriggered = function () {
  7081. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7082. //get the old size before we change
  7083. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7084. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7085. //get the width and height, change the render size
  7086. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7087. var width, height;
  7088. _this.setHardwareScalingLevel(1);
  7089. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7090. }
  7091. else {
  7092. //When the specs are implemented, need to uncomment this.
  7093. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7094. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7095. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7096. _this._vrDisplayEnabled = undefined;
  7097. }
  7098. };
  7099. this._renderingCanvas = canvas;
  7100. Engine.Instances.push(this);
  7101. options = options || {};
  7102. if (antialias != null) {
  7103. options.antialias = antialias;
  7104. }
  7105. if (options.preserveDrawingBuffer === undefined) {
  7106. options.preserveDrawingBuffer = false;
  7107. }
  7108. if (options.audioEngine === undefined) {
  7109. options.audioEngine = true;
  7110. }
  7111. if (options.stencil === undefined) {
  7112. options.stencil = true;
  7113. }
  7114. // GL
  7115. if (!options.disableWebGL2Support) {
  7116. try {
  7117. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7118. if (this._gl) {
  7119. this._webGLVersion = 2.0;
  7120. }
  7121. }
  7122. catch (e) {
  7123. // Do nothing
  7124. }
  7125. }
  7126. if (!this._gl) {
  7127. if (!canvas) {
  7128. throw new Error("The provided canvas is null or undefined.");
  7129. }
  7130. try {
  7131. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7132. }
  7133. catch (e) {
  7134. throw new Error("WebGL not supported");
  7135. }
  7136. }
  7137. if (!this._gl) {
  7138. throw new Error("WebGL not supported");
  7139. }
  7140. this._onBlur = function () {
  7141. _this._windowIsBackground = true;
  7142. };
  7143. this._onFocus = function () {
  7144. _this._windowIsBackground = false;
  7145. };
  7146. window.addEventListener("blur", this._onBlur);
  7147. window.addEventListener("focus", this._onFocus);
  7148. // Viewport
  7149. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7150. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7151. this.resize();
  7152. // Caps
  7153. this._isStencilEnable = options.stencil;
  7154. this._caps = new EngineCapabilities();
  7155. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7156. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  7157. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7158. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7159. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7160. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7161. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7162. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7163. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7164. // Infos
  7165. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7166. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7167. if (rendererInfo != null) {
  7168. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7169. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7170. }
  7171. if (!this._glVendor) {
  7172. this._glVendor = "Unknown vendor";
  7173. }
  7174. if (!this._glRenderer) {
  7175. this._glRenderer = "Unknown renderer";
  7176. }
  7177. // Extensions
  7178. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7179. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7180. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7181. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7182. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7183. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7184. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7185. 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');
  7186. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7187. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7188. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7189. this._caps.highPrecisionShaderSupported = true;
  7190. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7191. // Checks if some of the format renders first to allow the use of webgl inspector.
  7192. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7193. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7194. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7195. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7196. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7197. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7198. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7199. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7200. // Vertex array object
  7201. if (this._webGLVersion > 1) {
  7202. this._caps.vertexArrayObject = true;
  7203. }
  7204. else {
  7205. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7206. if (vertexArrayObjectExtension != null) {
  7207. this._caps.vertexArrayObject = true;
  7208. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7209. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7210. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7211. }
  7212. else {
  7213. this._caps.vertexArrayObject = false;
  7214. }
  7215. }
  7216. // Instances count
  7217. if (this._webGLVersion > 1) {
  7218. this._caps.instancedArrays = true;
  7219. }
  7220. else {
  7221. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7222. if (instanceExtension != null) {
  7223. this._caps.instancedArrays = true;
  7224. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7225. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7226. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7227. }
  7228. else {
  7229. this._caps.instancedArrays = false;
  7230. }
  7231. }
  7232. // Intelligently add supported compressed formats in order to check for.
  7233. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7234. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7235. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7236. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7237. if (this._caps.astc)
  7238. this.texturesSupported.push('-astc.ktx');
  7239. if (this._caps.s3tc)
  7240. this.texturesSupported.push('-dxt.ktx');
  7241. if (this._caps.pvrtc)
  7242. this.texturesSupported.push('-pvrtc.ktx');
  7243. if (this._caps.etc2)
  7244. this.texturesSupported.push('-etc2.ktx');
  7245. if (this._caps.etc1)
  7246. this.texturesSupported.push('-etc1.ktx');
  7247. if (this._gl.getShaderPrecisionFormat) {
  7248. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7249. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7250. }
  7251. // Depth buffer
  7252. this.setDepthBuffer(true);
  7253. this.setDepthFunctionToLessOrEqual();
  7254. this.setDepthWrite(true);
  7255. // Fullscreen
  7256. this._onFullscreenChange = function () {
  7257. if (document.fullscreen !== undefined) {
  7258. _this.isFullscreen = document.fullscreen;
  7259. }
  7260. else if (document.mozFullScreen !== undefined) {
  7261. _this.isFullscreen = document.mozFullScreen;
  7262. }
  7263. else if (document.webkitIsFullScreen !== undefined) {
  7264. _this.isFullscreen = document.webkitIsFullScreen;
  7265. }
  7266. else if (document.msIsFullScreen !== undefined) {
  7267. _this.isFullscreen = document.msIsFullScreen;
  7268. }
  7269. // Pointer lock
  7270. if (_this.isFullscreen && _this._pointerLockRequested) {
  7271. canvas.requestPointerLock = canvas.requestPointerLock ||
  7272. canvas.msRequestPointerLock ||
  7273. canvas.mozRequestPointerLock ||
  7274. canvas.webkitRequestPointerLock;
  7275. if (canvas.requestPointerLock) {
  7276. canvas.requestPointerLock();
  7277. }
  7278. }
  7279. };
  7280. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7281. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7282. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7283. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7284. // Pointer lock
  7285. this._onPointerLockChange = function () {
  7286. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7287. document.webkitPointerLockElement === canvas ||
  7288. document.msPointerLockElement === canvas ||
  7289. document.pointerLockElement === canvas);
  7290. };
  7291. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7292. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7293. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7294. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7295. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7296. Engine.audioEngine = new BABYLON.AudioEngine();
  7297. }
  7298. //Load WebVR Devices
  7299. if (options.autoEnableWebVR) {
  7300. this.initWebVR();
  7301. }
  7302. //Detect if we are running on a faulty buggy OS.
  7303. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  7304. //ua sniffing is the tool of the devil.
  7305. this._badOS = regexp.test(navigator.userAgent);
  7306. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7307. }
  7308. Object.defineProperty(Engine, "LastCreatedEngine", {
  7309. get: function () {
  7310. if (Engine.Instances.length === 0) {
  7311. return null;
  7312. }
  7313. return Engine.Instances[Engine.Instances.length - 1];
  7314. },
  7315. enumerable: true,
  7316. configurable: true
  7317. });
  7318. Object.defineProperty(Engine, "LastCreatedScene", {
  7319. get: function () {
  7320. var lastCreatedEngine = Engine.LastCreatedEngine;
  7321. if (!lastCreatedEngine) {
  7322. return null;
  7323. }
  7324. if (lastCreatedEngine.scenes.length === 0) {
  7325. return null;
  7326. }
  7327. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7328. },
  7329. enumerable: true,
  7330. configurable: true
  7331. });
  7332. /**
  7333. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7334. */
  7335. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7336. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7337. var engine = Engine.Instances[engineIndex];
  7338. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7339. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7340. }
  7341. }
  7342. };
  7343. Object.defineProperty(Engine, "NEVER", {
  7344. get: function () {
  7345. return Engine._NEVER;
  7346. },
  7347. enumerable: true,
  7348. configurable: true
  7349. });
  7350. Object.defineProperty(Engine, "ALWAYS", {
  7351. get: function () {
  7352. return Engine._ALWAYS;
  7353. },
  7354. enumerable: true,
  7355. configurable: true
  7356. });
  7357. Object.defineProperty(Engine, "LESS", {
  7358. get: function () {
  7359. return Engine._LESS;
  7360. },
  7361. enumerable: true,
  7362. configurable: true
  7363. });
  7364. Object.defineProperty(Engine, "EQUAL", {
  7365. get: function () {
  7366. return Engine._EQUAL;
  7367. },
  7368. enumerable: true,
  7369. configurable: true
  7370. });
  7371. Object.defineProperty(Engine, "LEQUAL", {
  7372. get: function () {
  7373. return Engine._LEQUAL;
  7374. },
  7375. enumerable: true,
  7376. configurable: true
  7377. });
  7378. Object.defineProperty(Engine, "GREATER", {
  7379. get: function () {
  7380. return Engine._GREATER;
  7381. },
  7382. enumerable: true,
  7383. configurable: true
  7384. });
  7385. Object.defineProperty(Engine, "GEQUAL", {
  7386. get: function () {
  7387. return Engine._GEQUAL;
  7388. },
  7389. enumerable: true,
  7390. configurable: true
  7391. });
  7392. Object.defineProperty(Engine, "NOTEQUAL", {
  7393. get: function () {
  7394. return Engine._NOTEQUAL;
  7395. },
  7396. enumerable: true,
  7397. configurable: true
  7398. });
  7399. Object.defineProperty(Engine, "KEEP", {
  7400. get: function () {
  7401. return Engine._KEEP;
  7402. },
  7403. enumerable: true,
  7404. configurable: true
  7405. });
  7406. Object.defineProperty(Engine, "REPLACE", {
  7407. get: function () {
  7408. return Engine._REPLACE;
  7409. },
  7410. enumerable: true,
  7411. configurable: true
  7412. });
  7413. Object.defineProperty(Engine, "INCR", {
  7414. get: function () {
  7415. return Engine._INCR;
  7416. },
  7417. enumerable: true,
  7418. configurable: true
  7419. });
  7420. Object.defineProperty(Engine, "DECR", {
  7421. get: function () {
  7422. return Engine._DECR;
  7423. },
  7424. enumerable: true,
  7425. configurable: true
  7426. });
  7427. Object.defineProperty(Engine, "INVERT", {
  7428. get: function () {
  7429. return Engine._INVERT;
  7430. },
  7431. enumerable: true,
  7432. configurable: true
  7433. });
  7434. Object.defineProperty(Engine, "INCR_WRAP", {
  7435. get: function () {
  7436. return Engine._INCR_WRAP;
  7437. },
  7438. enumerable: true,
  7439. configurable: true
  7440. });
  7441. Object.defineProperty(Engine, "DECR_WRAP", {
  7442. get: function () {
  7443. return Engine._DECR_WRAP;
  7444. },
  7445. enumerable: true,
  7446. configurable: true
  7447. });
  7448. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7449. get: function () {
  7450. return Engine._ALPHA_DISABLE;
  7451. },
  7452. enumerable: true,
  7453. configurable: true
  7454. });
  7455. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7456. get: function () {
  7457. return Engine._ALPHA_ONEONE;
  7458. },
  7459. enumerable: true,
  7460. configurable: true
  7461. });
  7462. Object.defineProperty(Engine, "ALPHA_ADD", {
  7463. get: function () {
  7464. return Engine._ALPHA_ADD;
  7465. },
  7466. enumerable: true,
  7467. configurable: true
  7468. });
  7469. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7470. get: function () {
  7471. return Engine._ALPHA_COMBINE;
  7472. },
  7473. enumerable: true,
  7474. configurable: true
  7475. });
  7476. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7477. get: function () {
  7478. return Engine._ALPHA_SUBTRACT;
  7479. },
  7480. enumerable: true,
  7481. configurable: true
  7482. });
  7483. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7484. get: function () {
  7485. return Engine._ALPHA_MULTIPLY;
  7486. },
  7487. enumerable: true,
  7488. configurable: true
  7489. });
  7490. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7491. get: function () {
  7492. return Engine._ALPHA_MAXIMIZED;
  7493. },
  7494. enumerable: true,
  7495. configurable: true
  7496. });
  7497. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7498. get: function () {
  7499. return Engine._ALPHA_PREMULTIPLIED;
  7500. },
  7501. enumerable: true,
  7502. configurable: true
  7503. });
  7504. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7505. get: function () {
  7506. return Engine._DELAYLOADSTATE_NONE;
  7507. },
  7508. enumerable: true,
  7509. configurable: true
  7510. });
  7511. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7512. get: function () {
  7513. return Engine._DELAYLOADSTATE_LOADED;
  7514. },
  7515. enumerable: true,
  7516. configurable: true
  7517. });
  7518. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7519. get: function () {
  7520. return Engine._DELAYLOADSTATE_LOADING;
  7521. },
  7522. enumerable: true,
  7523. configurable: true
  7524. });
  7525. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7526. get: function () {
  7527. return Engine._DELAYLOADSTATE_NOTLOADED;
  7528. },
  7529. enumerable: true,
  7530. configurable: true
  7531. });
  7532. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7533. get: function () {
  7534. return Engine._TEXTUREFORMAT_ALPHA;
  7535. },
  7536. enumerable: true,
  7537. configurable: true
  7538. });
  7539. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7540. get: function () {
  7541. return Engine._TEXTUREFORMAT_LUMINANCE;
  7542. },
  7543. enumerable: true,
  7544. configurable: true
  7545. });
  7546. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7547. get: function () {
  7548. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7549. },
  7550. enumerable: true,
  7551. configurable: true
  7552. });
  7553. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7554. get: function () {
  7555. return Engine._TEXTUREFORMAT_RGB;
  7556. },
  7557. enumerable: true,
  7558. configurable: true
  7559. });
  7560. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7561. get: function () {
  7562. return Engine._TEXTUREFORMAT_RGBA;
  7563. },
  7564. enumerable: true,
  7565. configurable: true
  7566. });
  7567. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7568. get: function () {
  7569. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7570. },
  7571. enumerable: true,
  7572. configurable: true
  7573. });
  7574. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7575. get: function () {
  7576. return Engine._TEXTURETYPE_FLOAT;
  7577. },
  7578. enumerable: true,
  7579. configurable: true
  7580. });
  7581. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7582. get: function () {
  7583. return Engine._TEXTURETYPE_HALF_FLOAT;
  7584. },
  7585. enumerable: true,
  7586. configurable: true
  7587. });
  7588. Object.defineProperty(Engine, "Version", {
  7589. get: function () {
  7590. return "3.0-alpha";
  7591. },
  7592. enumerable: true,
  7593. configurable: true
  7594. });
  7595. Object.defineProperty(Engine.prototype, "texturesSupported", {
  7596. get: function () {
  7597. return this._texturesSupported;
  7598. },
  7599. enumerable: true,
  7600. configurable: true
  7601. });
  7602. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  7603. get: function () {
  7604. return this._textureFormatInUse;
  7605. },
  7606. enumerable: true,
  7607. configurable: true
  7608. });
  7609. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7610. get: function () {
  7611. return this._webGLVersion;
  7612. },
  7613. enumerable: true,
  7614. configurable: true
  7615. });
  7616. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7617. /**
  7618. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7619. */
  7620. get: function () {
  7621. return this._isStencilEnable;
  7622. },
  7623. enumerable: true,
  7624. configurable: true
  7625. });
  7626. Engine.prototype._prepareWorkingCanvas = function () {
  7627. if (this._workingCanvas) {
  7628. return;
  7629. }
  7630. this._workingCanvas = document.createElement("canvas");
  7631. this._workingContext = this._workingCanvas.getContext("2d");
  7632. };
  7633. Engine.prototype.resetTextureCache = function () {
  7634. for (var index = 0; index < this._maxTextureChannels; index++) {
  7635. this._activeTexturesCache[index] = null;
  7636. }
  7637. };
  7638. Engine.prototype.getGlInfo = function () {
  7639. return {
  7640. vendor: this._glVendor,
  7641. renderer: this._glRenderer,
  7642. version: this._glVersion
  7643. };
  7644. };
  7645. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7646. if (useScreen === void 0) { useScreen = false; }
  7647. var viewport = camera.viewport;
  7648. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7649. };
  7650. Engine.prototype.getRenderWidth = function (useScreen) {
  7651. if (useScreen === void 0) { useScreen = false; }
  7652. if (!useScreen && this._currentRenderTarget) {
  7653. return this._currentRenderTarget._width;
  7654. }
  7655. return this._renderingCanvas.width;
  7656. };
  7657. Engine.prototype.getRenderHeight = function (useScreen) {
  7658. if (useScreen === void 0) { useScreen = false; }
  7659. if (!useScreen && this._currentRenderTarget) {
  7660. return this._currentRenderTarget._height;
  7661. }
  7662. return this._renderingCanvas.height;
  7663. };
  7664. Engine.prototype.getRenderingCanvas = function () {
  7665. return this._renderingCanvas;
  7666. };
  7667. Engine.prototype.getRenderingCanvasClientRect = function () {
  7668. return this._renderingCanvas.getBoundingClientRect();
  7669. };
  7670. Engine.prototype.setHardwareScalingLevel = function (level) {
  7671. this._hardwareScalingLevel = level;
  7672. this.resize();
  7673. };
  7674. Engine.prototype.getHardwareScalingLevel = function () {
  7675. return this._hardwareScalingLevel;
  7676. };
  7677. Engine.prototype.getLoadedTexturesCache = function () {
  7678. return this._loadedTexturesCache;
  7679. };
  7680. Engine.prototype.getCaps = function () {
  7681. return this._caps;
  7682. };
  7683. Object.defineProperty(Engine.prototype, "drawCalls", {
  7684. get: function () {
  7685. return this._drawCalls.current;
  7686. },
  7687. enumerable: true,
  7688. configurable: true
  7689. });
  7690. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7691. get: function () {
  7692. return this._drawCalls;
  7693. },
  7694. enumerable: true,
  7695. configurable: true
  7696. });
  7697. Engine.prototype.getDepthFunction = function () {
  7698. return this._depthCullingState.depthFunc;
  7699. };
  7700. Engine.prototype.setDepthFunction = function (depthFunc) {
  7701. this._depthCullingState.depthFunc = depthFunc;
  7702. };
  7703. Engine.prototype.setDepthFunctionToGreater = function () {
  7704. this._depthCullingState.depthFunc = this._gl.GREATER;
  7705. };
  7706. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7707. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7708. };
  7709. Engine.prototype.setDepthFunctionToLess = function () {
  7710. this._depthCullingState.depthFunc = this._gl.LESS;
  7711. };
  7712. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7713. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7714. };
  7715. Engine.prototype.getStencilBuffer = function () {
  7716. return this._stencilState.stencilTest;
  7717. };
  7718. Engine.prototype.setStencilBuffer = function (enable) {
  7719. this._stencilState.stencilTest = enable;
  7720. };
  7721. Engine.prototype.getStencilMask = function () {
  7722. return this._stencilState.stencilMask;
  7723. };
  7724. Engine.prototype.setStencilMask = function (mask) {
  7725. this._stencilState.stencilMask = mask;
  7726. };
  7727. Engine.prototype.getStencilFunction = function () {
  7728. return this._stencilState.stencilFunc;
  7729. };
  7730. Engine.prototype.getStencilFunctionReference = function () {
  7731. return this._stencilState.stencilFuncRef;
  7732. };
  7733. Engine.prototype.getStencilFunctionMask = function () {
  7734. return this._stencilState.stencilFuncMask;
  7735. };
  7736. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7737. this._stencilState.stencilFunc = stencilFunc;
  7738. };
  7739. Engine.prototype.setStencilFunctionReference = function (reference) {
  7740. this._stencilState.stencilFuncRef = reference;
  7741. };
  7742. Engine.prototype.setStencilFunctionMask = function (mask) {
  7743. this._stencilState.stencilFuncMask = mask;
  7744. };
  7745. Engine.prototype.getStencilOperationFail = function () {
  7746. return this._stencilState.stencilOpStencilFail;
  7747. };
  7748. Engine.prototype.getStencilOperationDepthFail = function () {
  7749. return this._stencilState.stencilOpDepthFail;
  7750. };
  7751. Engine.prototype.getStencilOperationPass = function () {
  7752. return this._stencilState.stencilOpStencilDepthPass;
  7753. };
  7754. Engine.prototype.setStencilOperationFail = function (operation) {
  7755. this._stencilState.stencilOpStencilFail = operation;
  7756. };
  7757. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7758. this._stencilState.stencilOpDepthFail = operation;
  7759. };
  7760. Engine.prototype.setStencilOperationPass = function (operation) {
  7761. this._stencilState.stencilOpStencilDepthPass = operation;
  7762. };
  7763. Engine.prototype.setDitheringState = function (value) {
  7764. if (value) {
  7765. this._gl.enable(this._gl.DITHER);
  7766. }
  7767. else {
  7768. this._gl.disable(this._gl.DITHER);
  7769. }
  7770. };
  7771. /**
  7772. * stop executing a render loop function and remove it from the execution array
  7773. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7774. */
  7775. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7776. if (!renderFunction) {
  7777. this._activeRenderLoops = [];
  7778. return;
  7779. }
  7780. var index = this._activeRenderLoops.indexOf(renderFunction);
  7781. if (index >= 0) {
  7782. this._activeRenderLoops.splice(index, 1);
  7783. }
  7784. };
  7785. Engine.prototype._renderLoop = function () {
  7786. var shouldRender = true;
  7787. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7788. shouldRender = false;
  7789. }
  7790. if (shouldRender) {
  7791. // Start new frame
  7792. this.beginFrame();
  7793. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7794. var renderFunction = this._activeRenderLoops[index];
  7795. renderFunction();
  7796. }
  7797. // Present
  7798. this.endFrame();
  7799. }
  7800. if (this._activeRenderLoops.length > 0) {
  7801. // Register new frame
  7802. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7803. }
  7804. else {
  7805. this._renderingQueueLaunched = false;
  7806. }
  7807. };
  7808. /**
  7809. * Register and execute a render loop. The engine can have more than one render function.
  7810. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7811. * @example
  7812. * engine.runRenderLoop(function () {
  7813. * scene.render()
  7814. * })
  7815. */
  7816. Engine.prototype.runRenderLoop = function (renderFunction) {
  7817. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  7818. return;
  7819. }
  7820. this._activeRenderLoops.push(renderFunction);
  7821. if (!this._renderingQueueLaunched) {
  7822. this._renderingQueueLaunched = true;
  7823. this._bindedRenderFunction = this._renderLoop.bind(this);
  7824. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  7825. }
  7826. };
  7827. /**
  7828. * Toggle full screen mode.
  7829. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  7830. * @param {any} options - an options object to be sent to the requestFullscreen function
  7831. */
  7832. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  7833. if (this.isFullscreen) {
  7834. BABYLON.Tools.ExitFullscreen();
  7835. }
  7836. else {
  7837. this._pointerLockRequested = requestPointerLock;
  7838. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  7839. }
  7840. };
  7841. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  7842. if (stencil === void 0) { stencil = false; }
  7843. this.applyStates();
  7844. var mode = 0;
  7845. if (backBuffer && color) {
  7846. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  7847. mode |= this._gl.COLOR_BUFFER_BIT;
  7848. }
  7849. if (depth) {
  7850. this._gl.clearDepth(1.0);
  7851. mode |= this._gl.DEPTH_BUFFER_BIT;
  7852. }
  7853. if (stencil) {
  7854. this._gl.clearStencil(0);
  7855. mode |= this._gl.STENCIL_BUFFER_BIT;
  7856. }
  7857. this._gl.clear(mode);
  7858. };
  7859. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  7860. var gl = this._gl;
  7861. // Save state
  7862. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  7863. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  7864. // Change state
  7865. gl.enable(gl.SCISSOR_TEST);
  7866. gl.scissor(x, y, width, height);
  7867. // Clear
  7868. this.clear(clearColor, true, true, true);
  7869. // Restore state
  7870. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  7871. if (curScissor === true) {
  7872. gl.enable(gl.SCISSOR_TEST);
  7873. }
  7874. else {
  7875. gl.disable(gl.SCISSOR_TEST);
  7876. }
  7877. };
  7878. /**
  7879. * Set the WebGL's viewport
  7880. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  7881. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  7882. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  7883. */
  7884. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  7885. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  7886. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  7887. var x = viewport.x || 0;
  7888. var y = viewport.y || 0;
  7889. this._cachedViewport = viewport;
  7890. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  7891. };
  7892. /**
  7893. * Directly set the WebGL Viewport
  7894. * The x, y, width & height are directly passed to the WebGL call
  7895. * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state.
  7896. */
  7897. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  7898. var currentViewport = this._cachedViewport;
  7899. this._cachedViewport = null;
  7900. this._gl.viewport(x, y, width, height);
  7901. return currentViewport;
  7902. };
  7903. Engine.prototype.beginFrame = function () {
  7904. this._measureFps();
  7905. };
  7906. Engine.prototype.endFrame = function () {
  7907. //force a flush in case we are using a bad OS.
  7908. if (this._badOS) {
  7909. this.flushFramebuffer();
  7910. }
  7911. //submit frame to the vr device, if enabled
  7912. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  7913. this._vrDisplayEnabled.submitFrame();
  7914. }
  7915. };
  7916. /**
  7917. * resize the view according to the canvas' size.
  7918. * @example
  7919. * window.addEventListener("resize", function () {
  7920. * engine.resize();
  7921. * });
  7922. */
  7923. Engine.prototype.resize = function () {
  7924. // We're not resizing the size of the canvas while in VR mode & presenting
  7925. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  7926. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  7927. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  7928. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  7929. }
  7930. };
  7931. /**
  7932. * force a specific size of the canvas
  7933. * @param {number} width - the new canvas' width
  7934. * @param {number} height - the new canvas' height
  7935. */
  7936. Engine.prototype.setSize = function (width, height) {
  7937. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  7938. return;
  7939. }
  7940. this._renderingCanvas.width = width;
  7941. this._renderingCanvas.height = height;
  7942. for (var index = 0; index < this.scenes.length; index++) {
  7943. var scene = this.scenes[index];
  7944. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  7945. var cam = scene.cameras[camIndex];
  7946. cam._currentRenderId = 0;
  7947. }
  7948. }
  7949. if (this.onResizeObservable.hasObservers) {
  7950. this.onResizeObservable.notifyObservers(this);
  7951. }
  7952. };
  7953. //WebVR functions
  7954. Engine.prototype.isVRDevicePresent = function (callback) {
  7955. this.getVRDevice(null, function (device) {
  7956. callback(device !== null);
  7957. });
  7958. };
  7959. Engine.prototype.getVRDevice = function (name, callback) {
  7960. if (!this.vrDisplaysPromise) {
  7961. callback(null);
  7962. return;
  7963. }
  7964. this.vrDisplaysPromise.then(function (devices) {
  7965. if (devices.length > 0) {
  7966. if (name) {
  7967. var found = devices.some(function (device) {
  7968. if (device.displayName === name) {
  7969. callback(device);
  7970. return true;
  7971. }
  7972. else {
  7973. return false;
  7974. }
  7975. });
  7976. if (!found) {
  7977. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  7978. callback(devices[0]);
  7979. }
  7980. }
  7981. else {
  7982. //choose the first one
  7983. callback(devices[0]);
  7984. }
  7985. }
  7986. else {
  7987. BABYLON.Tools.Error("No WebVR devices found!");
  7988. callback(null);
  7989. }
  7990. });
  7991. };
  7992. Engine.prototype.initWebVR = function () {
  7993. if (!this.vrDisplaysPromise) {
  7994. this._getVRDisplays();
  7995. }
  7996. };
  7997. Engine.prototype.enableVR = function (vrDevice) {
  7998. this._vrDisplayEnabled = vrDevice;
  7999. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8000. };
  8001. Engine.prototype.disableVR = function () {
  8002. if (this._vrDisplayEnabled) {
  8003. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8004. }
  8005. };
  8006. Engine.prototype._getVRDisplays = function () {
  8007. var _this = this;
  8008. var getWebVRDevices = function (devices) {
  8009. var size = devices.length;
  8010. var i = 0;
  8011. _this._vrDisplays = devices.filter(function (device) {
  8012. return devices[i] instanceof VRDisplay;
  8013. });
  8014. return _this._vrDisplays;
  8015. };
  8016. //using a key due to typescript
  8017. if (navigator.getVRDisplays) {
  8018. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8019. }
  8020. };
  8021. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  8022. this._currentRenderTarget = texture;
  8023. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8024. var gl = this._gl;
  8025. if (texture.isCube) {
  8026. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  8027. }
  8028. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  8029. this.wipeCaches();
  8030. };
  8031. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8032. if (this._currentFramebuffer !== framebuffer) {
  8033. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8034. this._currentFramebuffer = framebuffer;
  8035. }
  8036. };
  8037. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8038. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8039. this._currentRenderTarget = null;
  8040. // If MSAA, we need to bitblt back to main texture
  8041. var gl = this._gl;
  8042. if (texture._MSAAFramebuffer) {
  8043. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8044. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8045. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8046. }
  8047. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  8048. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8049. gl.generateMipmap(gl.TEXTURE_2D);
  8050. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8051. }
  8052. if (onBeforeUnbind) {
  8053. if (texture._MSAAFramebuffer) {
  8054. // Bind the correct framebuffer
  8055. this.bindUnboundFramebuffer(texture._framebuffer);
  8056. }
  8057. onBeforeUnbind();
  8058. }
  8059. this.bindUnboundFramebuffer(null);
  8060. };
  8061. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8062. if (texture.generateMipMaps) {
  8063. var gl = this._gl;
  8064. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8065. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8066. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8067. }
  8068. };
  8069. Engine.prototype.flushFramebuffer = function () {
  8070. this._gl.flush();
  8071. };
  8072. Engine.prototype.restoreDefaultFramebuffer = function () {
  8073. this._currentRenderTarget = null;
  8074. this.bindUnboundFramebuffer(null);
  8075. this.setViewport(this._cachedViewport);
  8076. this.wipeCaches();
  8077. };
  8078. // UBOs
  8079. Engine.prototype.createUniformBuffer = function (elements) {
  8080. var ubo = this._gl.createBuffer();
  8081. this.bindUniformBuffer(ubo);
  8082. if (elements instanceof Float32Array) {
  8083. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8084. }
  8085. else {
  8086. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8087. }
  8088. this.bindUniformBuffer(null);
  8089. ubo.references = 1;
  8090. return ubo;
  8091. };
  8092. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8093. var ubo = this._gl.createBuffer();
  8094. this.bindUniformBuffer(ubo);
  8095. if (elements instanceof Float32Array) {
  8096. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8097. }
  8098. else {
  8099. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8100. }
  8101. this.bindUniformBuffer(null);
  8102. ubo.references = 1;
  8103. return ubo;
  8104. };
  8105. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8106. this.bindUniformBuffer(uniformBuffer);
  8107. if (offset === undefined) {
  8108. offset = 0;
  8109. }
  8110. if (count === undefined) {
  8111. if (elements instanceof Float32Array) {
  8112. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8113. }
  8114. else {
  8115. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8116. }
  8117. }
  8118. else {
  8119. if (elements instanceof Float32Array) {
  8120. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8121. }
  8122. else {
  8123. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8124. }
  8125. }
  8126. this.bindUniformBuffer(null);
  8127. };
  8128. // VBOs
  8129. Engine.prototype._resetVertexBufferBinding = function () {
  8130. this.bindArrayBuffer(null);
  8131. this._cachedVertexBuffers = null;
  8132. };
  8133. Engine.prototype.createVertexBuffer = function (vertices) {
  8134. var vbo = this._gl.createBuffer();
  8135. this.bindArrayBuffer(vbo);
  8136. if (vertices instanceof Float32Array) {
  8137. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8138. }
  8139. else {
  8140. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8141. }
  8142. this._resetVertexBufferBinding();
  8143. vbo.references = 1;
  8144. return vbo;
  8145. };
  8146. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8147. var vbo = this._gl.createBuffer();
  8148. this.bindArrayBuffer(vbo);
  8149. if (vertices instanceof Float32Array) {
  8150. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8151. }
  8152. else {
  8153. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8154. }
  8155. this._resetVertexBufferBinding();
  8156. vbo.references = 1;
  8157. return vbo;
  8158. };
  8159. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8160. this.bindArrayBuffer(vertexBuffer);
  8161. if (offset === undefined) {
  8162. offset = 0;
  8163. }
  8164. if (count === undefined) {
  8165. if (vertices instanceof Float32Array) {
  8166. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8167. }
  8168. else {
  8169. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8170. }
  8171. }
  8172. else {
  8173. if (vertices instanceof Float32Array) {
  8174. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8175. }
  8176. else {
  8177. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8178. }
  8179. }
  8180. this._resetVertexBufferBinding();
  8181. };
  8182. Engine.prototype._resetIndexBufferBinding = function () {
  8183. this.bindIndexBuffer(null);
  8184. this._cachedIndexBuffer = null;
  8185. };
  8186. Engine.prototype.createIndexBuffer = function (indices) {
  8187. var vbo = this._gl.createBuffer();
  8188. this.bindIndexBuffer(vbo);
  8189. // Check for 32 bits indices
  8190. var arrayBuffer;
  8191. var need32Bits = false;
  8192. if (indices instanceof Uint16Array) {
  8193. arrayBuffer = indices;
  8194. }
  8195. else {
  8196. //check 32 bit support
  8197. if (this._caps.uintIndices) {
  8198. if (indices instanceof Uint32Array) {
  8199. arrayBuffer = indices;
  8200. need32Bits = true;
  8201. }
  8202. else {
  8203. //number[] or Int32Array, check if 32 bit is necessary
  8204. for (var index = 0; index < indices.length; index++) {
  8205. if (indices[index] > 65535) {
  8206. need32Bits = true;
  8207. break;
  8208. }
  8209. }
  8210. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8211. }
  8212. }
  8213. else {
  8214. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8215. arrayBuffer = new Uint16Array(indices);
  8216. }
  8217. }
  8218. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8219. this._resetIndexBufferBinding();
  8220. vbo.references = 1;
  8221. vbo.is32Bits = need32Bits;
  8222. return vbo;
  8223. };
  8224. Engine.prototype.bindArrayBuffer = function (buffer) {
  8225. if (!this._vaoRecordInProgress) {
  8226. this._unBindVertexArrayObject();
  8227. }
  8228. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8229. };
  8230. Engine.prototype.bindUniformBuffer = function (buffer) {
  8231. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8232. };
  8233. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8234. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8235. };
  8236. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8237. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8238. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8239. };
  8240. ;
  8241. Engine.prototype.bindIndexBuffer = function (buffer) {
  8242. if (!this._vaoRecordInProgress) {
  8243. this._unBindVertexArrayObject();
  8244. }
  8245. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8246. };
  8247. Engine.prototype.bindBuffer = function (buffer, target) {
  8248. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8249. this._gl.bindBuffer(target, buffer);
  8250. this._currentBoundBuffer[target] = buffer;
  8251. }
  8252. };
  8253. Engine.prototype.updateArrayBuffer = function (data) {
  8254. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8255. };
  8256. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8257. var pointer = this._currentBufferPointers[indx];
  8258. var changed = false;
  8259. if (!pointer) {
  8260. changed = true;
  8261. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8262. }
  8263. else {
  8264. if (pointer.buffer !== buffer) {
  8265. pointer.buffer = buffer;
  8266. changed = true;
  8267. }
  8268. if (pointer.size !== size) {
  8269. pointer.size = size;
  8270. changed = true;
  8271. }
  8272. if (pointer.type !== type) {
  8273. pointer.type = type;
  8274. changed = true;
  8275. }
  8276. if (pointer.normalized !== normalized) {
  8277. pointer.normalized = normalized;
  8278. changed = true;
  8279. }
  8280. if (pointer.stride !== stride) {
  8281. pointer.stride = stride;
  8282. changed = true;
  8283. }
  8284. if (pointer.offset !== offset) {
  8285. pointer.offset = offset;
  8286. changed = true;
  8287. }
  8288. }
  8289. if (changed || this._vaoRecordInProgress) {
  8290. this.bindArrayBuffer(buffer);
  8291. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8292. }
  8293. };
  8294. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8295. if (indexBuffer == null) {
  8296. return;
  8297. }
  8298. if (this._cachedIndexBuffer !== indexBuffer) {
  8299. this._cachedIndexBuffer = indexBuffer;
  8300. this.bindIndexBuffer(indexBuffer);
  8301. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8302. }
  8303. };
  8304. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8305. var attributes = effect.getAttributesNames();
  8306. if (!this._vaoRecordInProgress) {
  8307. this._unBindVertexArrayObject();
  8308. }
  8309. this.unbindAllAttributes();
  8310. for (var index = 0; index < attributes.length; index++) {
  8311. var order = effect.getAttributeLocation(index);
  8312. if (order >= 0) {
  8313. var vertexBuffer = vertexBuffers[attributes[index]];
  8314. if (!vertexBuffer) {
  8315. continue;
  8316. }
  8317. this._gl.enableVertexAttribArray(order);
  8318. if (!this._vaoRecordInProgress) {
  8319. this._vertexAttribArraysEnabled[order] = true;
  8320. }
  8321. var buffer = vertexBuffer.getBuffer();
  8322. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8323. if (vertexBuffer.getIsInstanced()) {
  8324. this._gl.vertexAttribDivisor(order, 1);
  8325. if (!this._vaoRecordInProgress) {
  8326. this._currentInstanceLocations.push(order);
  8327. this._currentInstanceBuffers.push(buffer);
  8328. }
  8329. }
  8330. }
  8331. }
  8332. };
  8333. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8334. var vao = this._gl.createVertexArray();
  8335. this._vaoRecordInProgress = true;
  8336. this._gl.bindVertexArray(vao);
  8337. this._mustWipeVertexAttributes = true;
  8338. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8339. this.bindIndexBuffer(indexBuffer);
  8340. this._vaoRecordInProgress = false;
  8341. this._gl.bindVertexArray(null);
  8342. return vao;
  8343. };
  8344. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8345. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8346. this._cachedVertexArrayObject = vertexArrayObject;
  8347. this._gl.bindVertexArray(vertexArrayObject);
  8348. this._cachedVertexBuffers = null;
  8349. this._cachedIndexBuffer = null;
  8350. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8351. this._mustWipeVertexAttributes = true;
  8352. }
  8353. };
  8354. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8355. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8356. this._cachedVertexBuffers = vertexBuffer;
  8357. this._cachedEffectForVertexBuffers = effect;
  8358. var attributesCount = effect.getAttributesCount();
  8359. this._unBindVertexArrayObject();
  8360. this.unbindAllAttributes();
  8361. var offset = 0;
  8362. for (var index = 0; index < attributesCount; index++) {
  8363. if (index < vertexDeclaration.length) {
  8364. var order = effect.getAttributeLocation(index);
  8365. if (order >= 0) {
  8366. this._gl.enableVertexAttribArray(order);
  8367. this._vertexAttribArraysEnabled[order] = true;
  8368. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8369. }
  8370. offset += vertexDeclaration[index] * 4;
  8371. }
  8372. }
  8373. }
  8374. this._bindIndexBufferWithCache(indexBuffer);
  8375. };
  8376. Engine.prototype._unBindVertexArrayObject = function () {
  8377. if (!this._cachedVertexArrayObject) {
  8378. return;
  8379. }
  8380. this._cachedVertexArrayObject = null;
  8381. this._gl.bindVertexArray(null);
  8382. };
  8383. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8384. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8385. this._cachedVertexBuffers = vertexBuffers;
  8386. this._cachedEffectForVertexBuffers = effect;
  8387. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8388. }
  8389. this._bindIndexBufferWithCache(indexBuffer);
  8390. };
  8391. Engine.prototype.unbindInstanceAttributes = function () {
  8392. var boundBuffer;
  8393. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8394. var instancesBuffer = this._currentInstanceBuffers[i];
  8395. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  8396. boundBuffer = instancesBuffer;
  8397. this.bindArrayBuffer(instancesBuffer);
  8398. }
  8399. var offsetLocation = this._currentInstanceLocations[i];
  8400. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8401. }
  8402. this._currentInstanceBuffers.length = 0;
  8403. this._currentInstanceLocations.length = 0;
  8404. };
  8405. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8406. this._gl.deleteVertexArray(vao);
  8407. };
  8408. Engine.prototype._releaseBuffer = function (buffer) {
  8409. buffer.references--;
  8410. if (buffer.references === 0) {
  8411. this._gl.deleteBuffer(buffer);
  8412. return true;
  8413. }
  8414. return false;
  8415. };
  8416. Engine.prototype.createInstancesBuffer = function (capacity) {
  8417. var buffer = this._gl.createBuffer();
  8418. buffer.capacity = capacity;
  8419. this.bindArrayBuffer(buffer);
  8420. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8421. return buffer;
  8422. };
  8423. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8424. this._gl.deleteBuffer(buffer);
  8425. };
  8426. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8427. this.bindArrayBuffer(instancesBuffer);
  8428. if (data) {
  8429. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8430. }
  8431. if (offsetLocations[0].index !== undefined) {
  8432. var stride = 0;
  8433. for (var i = 0; i < offsetLocations.length; i++) {
  8434. var ai = offsetLocations[i];
  8435. stride += ai.attributeSize * 4;
  8436. }
  8437. for (var i = 0; i < offsetLocations.length; i++) {
  8438. var ai = offsetLocations[i];
  8439. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8440. this._gl.enableVertexAttribArray(ai.index);
  8441. this._vertexAttribArraysEnabled[ai.index] = true;
  8442. }
  8443. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8444. this._gl.vertexAttribDivisor(ai.index, 1);
  8445. this._currentInstanceLocations.push(ai.index);
  8446. this._currentInstanceBuffers.push(instancesBuffer);
  8447. }
  8448. }
  8449. else {
  8450. for (var index = 0; index < 4; index++) {
  8451. var offsetLocation = offsetLocations[index];
  8452. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  8453. this._gl.enableVertexAttribArray(offsetLocation);
  8454. this._vertexAttribArraysEnabled[offsetLocation] = true;
  8455. }
  8456. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  8457. this._gl.vertexAttribDivisor(offsetLocation, 1);
  8458. this._currentInstanceLocations.push(offsetLocation);
  8459. this._currentInstanceBuffers.push(instancesBuffer);
  8460. }
  8461. }
  8462. };
  8463. Engine.prototype.applyStates = function () {
  8464. this._depthCullingState.apply(this._gl);
  8465. this._stencilState.apply(this._gl);
  8466. this._alphaState.apply(this._gl);
  8467. };
  8468. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  8469. // Apply states
  8470. this.applyStates();
  8471. this._drawCalls.addCount(1, false);
  8472. // Render
  8473. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  8474. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  8475. if (instancesCount) {
  8476. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  8477. return;
  8478. }
  8479. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  8480. };
  8481. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  8482. // Apply states
  8483. this.applyStates();
  8484. this._drawCalls.addCount(1, false);
  8485. if (instancesCount) {
  8486. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  8487. return;
  8488. }
  8489. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  8490. };
  8491. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  8492. // Apply states
  8493. this.applyStates();
  8494. this._drawCalls.addCount(1, false);
  8495. if (instancesCount) {
  8496. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  8497. return;
  8498. }
  8499. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  8500. };
  8501. // Shaders
  8502. Engine.prototype._releaseEffect = function (effect) {
  8503. if (this._compiledEffects[effect._key]) {
  8504. delete this._compiledEffects[effect._key];
  8505. if (effect.getProgram()) {
  8506. this._gl.deleteProgram(effect.getProgram());
  8507. }
  8508. }
  8509. };
  8510. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  8511. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  8512. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  8513. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  8514. if (this._compiledEffects[name]) {
  8515. return this._compiledEffects[name];
  8516. }
  8517. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  8518. effect._key = name;
  8519. this._compiledEffects[name] = effect;
  8520. return effect;
  8521. };
  8522. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  8523. if (uniformsNames === void 0) { uniformsNames = []; }
  8524. if (samplers === void 0) { samplers = []; }
  8525. if (defines === void 0) { defines = ""; }
  8526. return this.createEffect({
  8527. vertex: "particles",
  8528. fragmentElement: fragmentName
  8529. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  8530. };
  8531. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  8532. context = context || this._gl;
  8533. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  8534. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  8535. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  8536. var shaderProgram = context.createProgram();
  8537. context.attachShader(shaderProgram, vertexShader);
  8538. context.attachShader(shaderProgram, fragmentShader);
  8539. context.linkProgram(shaderProgram);
  8540. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  8541. if (!linked) {
  8542. var error = context.getProgramInfoLog(shaderProgram);
  8543. if (error) {
  8544. throw new Error(error);
  8545. }
  8546. }
  8547. context.deleteShader(vertexShader);
  8548. context.deleteShader(fragmentShader);
  8549. return shaderProgram;
  8550. };
  8551. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  8552. var results = [];
  8553. for (var index = 0; index < uniformsNames.length; index++) {
  8554. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  8555. }
  8556. return results;
  8557. };
  8558. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  8559. var results = [];
  8560. for (var index = 0; index < attributesNames.length; index++) {
  8561. try {
  8562. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  8563. }
  8564. catch (e) {
  8565. results.push(-1);
  8566. }
  8567. }
  8568. return results;
  8569. };
  8570. Engine.prototype.enableEffect = function (effect) {
  8571. // Use program
  8572. this.setProgram(effect.getProgram());
  8573. this._currentEffect = effect;
  8574. if (effect.onBind) {
  8575. effect.onBind(effect);
  8576. }
  8577. };
  8578. Engine.prototype.setIntArray = function (uniform, array) {
  8579. if (!uniform)
  8580. return;
  8581. this._gl.uniform1iv(uniform, array);
  8582. };
  8583. Engine.prototype.setIntArray2 = function (uniform, array) {
  8584. if (!uniform || array.length % 2 !== 0)
  8585. return;
  8586. this._gl.uniform2iv(uniform, array);
  8587. };
  8588. Engine.prototype.setIntArray3 = function (uniform, array) {
  8589. if (!uniform || array.length % 3 !== 0)
  8590. return;
  8591. this._gl.uniform3iv(uniform, array);
  8592. };
  8593. Engine.prototype.setIntArray4 = function (uniform, array) {
  8594. if (!uniform || array.length % 4 !== 0)
  8595. return;
  8596. this._gl.uniform4iv(uniform, array);
  8597. };
  8598. Engine.prototype.setFloatArray = function (uniform, array) {
  8599. if (!uniform)
  8600. return;
  8601. this._gl.uniform1fv(uniform, array);
  8602. };
  8603. Engine.prototype.setFloatArray2 = function (uniform, array) {
  8604. if (!uniform || array.length % 2 !== 0)
  8605. return;
  8606. this._gl.uniform2fv(uniform, array);
  8607. };
  8608. Engine.prototype.setFloatArray3 = function (uniform, array) {
  8609. if (!uniform || array.length % 3 !== 0)
  8610. return;
  8611. this._gl.uniform3fv(uniform, array);
  8612. };
  8613. Engine.prototype.setFloatArray4 = function (uniform, array) {
  8614. if (!uniform || array.length % 4 !== 0)
  8615. return;
  8616. this._gl.uniform4fv(uniform, array);
  8617. };
  8618. Engine.prototype.setArray = function (uniform, array) {
  8619. if (!uniform)
  8620. return;
  8621. this._gl.uniform1fv(uniform, array);
  8622. };
  8623. Engine.prototype.setArray2 = function (uniform, array) {
  8624. if (!uniform || array.length % 2 !== 0)
  8625. return;
  8626. this._gl.uniform2fv(uniform, array);
  8627. };
  8628. Engine.prototype.setArray3 = function (uniform, array) {
  8629. if (!uniform || array.length % 3 !== 0)
  8630. return;
  8631. this._gl.uniform3fv(uniform, array);
  8632. };
  8633. Engine.prototype.setArray4 = function (uniform, array) {
  8634. if (!uniform || array.length % 4 !== 0)
  8635. return;
  8636. this._gl.uniform4fv(uniform, array);
  8637. };
  8638. Engine.prototype.setMatrices = function (uniform, matrices) {
  8639. if (!uniform)
  8640. return;
  8641. this._gl.uniformMatrix4fv(uniform, false, matrices);
  8642. };
  8643. Engine.prototype.setMatrix = function (uniform, matrix) {
  8644. if (!uniform)
  8645. return;
  8646. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  8647. };
  8648. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  8649. if (!uniform)
  8650. return;
  8651. this._gl.uniformMatrix3fv(uniform, false, matrix);
  8652. };
  8653. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  8654. if (!uniform)
  8655. return;
  8656. this._gl.uniformMatrix2fv(uniform, false, matrix);
  8657. };
  8658. Engine.prototype.setFloat = function (uniform, value) {
  8659. if (!uniform)
  8660. return;
  8661. this._gl.uniform1f(uniform, value);
  8662. };
  8663. Engine.prototype.setFloat2 = function (uniform, x, y) {
  8664. if (!uniform)
  8665. return;
  8666. this._gl.uniform2f(uniform, x, y);
  8667. };
  8668. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  8669. if (!uniform)
  8670. return;
  8671. this._gl.uniform3f(uniform, x, y, z);
  8672. };
  8673. Engine.prototype.setBool = function (uniform, bool) {
  8674. if (!uniform)
  8675. return;
  8676. this._gl.uniform1i(uniform, bool);
  8677. };
  8678. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  8679. if (!uniform)
  8680. return;
  8681. this._gl.uniform4f(uniform, x, y, z, w);
  8682. };
  8683. Engine.prototype.setColor3 = function (uniform, color3) {
  8684. if (!uniform)
  8685. return;
  8686. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  8687. };
  8688. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  8689. if (!uniform)
  8690. return;
  8691. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  8692. };
  8693. // States
  8694. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  8695. if (zOffset === void 0) { zOffset = 0; }
  8696. if (reverseSide === void 0) { reverseSide = false; }
  8697. // Culling
  8698. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  8699. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  8700. var cullFace = this.cullBackFaces ? showSide : hideSide;
  8701. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  8702. if (culling) {
  8703. this._depthCullingState.cullFace = cullFace;
  8704. this._depthCullingState.cull = true;
  8705. }
  8706. else {
  8707. this._depthCullingState.cull = false;
  8708. }
  8709. }
  8710. // Z offset
  8711. this._depthCullingState.zOffset = zOffset;
  8712. };
  8713. Engine.prototype.setDepthBuffer = function (enable) {
  8714. this._depthCullingState.depthTest = enable;
  8715. };
  8716. Engine.prototype.getDepthWrite = function () {
  8717. return this._depthCullingState.depthMask;
  8718. };
  8719. Engine.prototype.setDepthWrite = function (enable) {
  8720. this._depthCullingState.depthMask = enable;
  8721. };
  8722. Engine.prototype.setColorWrite = function (enable) {
  8723. this._gl.colorMask(enable, enable, enable, enable);
  8724. };
  8725. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  8726. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  8727. if (this._alphaMode === mode) {
  8728. return;
  8729. }
  8730. switch (mode) {
  8731. case Engine.ALPHA_DISABLE:
  8732. this._alphaState.alphaBlend = false;
  8733. break;
  8734. case Engine.ALPHA_PREMULTIPLIED:
  8735. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8736. this._alphaState.alphaBlend = true;
  8737. break;
  8738. case Engine.ALPHA_COMBINE:
  8739. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8740. this._alphaState.alphaBlend = true;
  8741. break;
  8742. case Engine.ALPHA_ONEONE:
  8743. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8744. this._alphaState.alphaBlend = true;
  8745. break;
  8746. case Engine.ALPHA_ADD:
  8747. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8748. this._alphaState.alphaBlend = true;
  8749. break;
  8750. case Engine.ALPHA_SUBTRACT:
  8751. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8752. this._alphaState.alphaBlend = true;
  8753. break;
  8754. case Engine.ALPHA_MULTIPLY:
  8755. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  8756. this._alphaState.alphaBlend = true;
  8757. break;
  8758. case Engine.ALPHA_MAXIMIZED:
  8759. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8760. this._alphaState.alphaBlend = true;
  8761. break;
  8762. }
  8763. if (!noDepthWriteChange) {
  8764. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  8765. }
  8766. this._alphaMode = mode;
  8767. };
  8768. Engine.prototype.getAlphaMode = function () {
  8769. return this._alphaMode;
  8770. };
  8771. Engine.prototype.setAlphaTesting = function (enable) {
  8772. this._alphaTest = enable;
  8773. };
  8774. Engine.prototype.getAlphaTesting = function () {
  8775. return !!this._alphaTest;
  8776. };
  8777. // Textures
  8778. Engine.prototype.wipeCaches = function () {
  8779. if (this.preventCacheWipeBetweenFrames) {
  8780. return;
  8781. }
  8782. this.resetTextureCache();
  8783. this._currentEffect = null;
  8784. this._stencilState.reset();
  8785. this._depthCullingState.reset();
  8786. this.setDepthFunctionToLessOrEqual();
  8787. this._alphaState.reset();
  8788. this._cachedVertexBuffers = null;
  8789. this._cachedIndexBuffer = null;
  8790. this._cachedEffectForVertexBuffers = null;
  8791. this._unBindVertexArrayObject();
  8792. this.bindIndexBuffer(null);
  8793. this.bindArrayBuffer(null);
  8794. };
  8795. /**
  8796. * Set the compressed texture format to use, based on the formats you have, and the formats
  8797. * supported by the hardware / browser.
  8798. *
  8799. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  8800. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  8801. * to API arguments needed to compressed textures. This puts the burden on the container
  8802. * generator to house the arcane code for determining these for current & future formats.
  8803. *
  8804. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  8805. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  8806. *
  8807. * Note: The result of this call is not taken into account when a texture is base64.
  8808. *
  8809. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  8810. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  8811. *
  8812. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  8813. * @returns The extension selected.
  8814. */
  8815. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  8816. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  8817. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  8818. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  8819. return this._textureFormatInUse = this._texturesSupported[i];
  8820. }
  8821. }
  8822. }
  8823. // actively set format to nothing, to allow this to be called more than once
  8824. // and possibly fail the 2nd time
  8825. return this._textureFormatInUse = null;
  8826. };
  8827. /**
  8828. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  8829. * @param {string} urlArg- This contains one of the following:
  8830. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  8831. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  8832. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  8833. *
  8834. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  8835. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  8836. * @param {Scene} scene- Needed for loading to the correct scene.
  8837. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  8838. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  8839. * @param {callback} onError- Optional callback to be called upon failure.
  8840. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  8841. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  8842. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  8843. *
  8844. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  8845. */
  8846. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  8847. var _this = this;
  8848. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  8849. if (onLoad === void 0) { onLoad = null; }
  8850. if (onError === void 0) { onError = null; }
  8851. if (buffer === void 0) { buffer = null; }
  8852. var texture = fallBack ? fallBack : this._gl.createTexture();
  8853. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  8854. var fromData = url.substr(0, 5) === "data:";
  8855. var isBase64 = fromData && url.indexOf("base64") !== -1;
  8856. // establish the file extension, if possible
  8857. var lastDot = url.lastIndexOf('.');
  8858. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  8859. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8860. if (isDDS) {
  8861. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  8862. }
  8863. var isTGA = (extension === ".tga");
  8864. // determine if a ktx file should be substituted
  8865. var isKTX = false;
  8866. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  8867. url = url.substring(0, lastDot) + this._textureFormatInUse;
  8868. isKTX = true;
  8869. }
  8870. scene._addPendingData(texture);
  8871. texture.url = url;
  8872. texture.noMipmap = noMipmap;
  8873. texture.references = 1;
  8874. texture.samplingMode = samplingMode;
  8875. texture.onLoadedCallbacks = [];
  8876. if (onLoad) {
  8877. texture.onLoadedCallbacks.push(onLoad);
  8878. }
  8879. if (!fallBack)
  8880. this._loadedTexturesCache.push(texture);
  8881. var onerror = function () {
  8882. scene._removePendingData(texture);
  8883. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  8884. if (isKTX) {
  8885. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  8886. }
  8887. else if (onError) {
  8888. onError();
  8889. }
  8890. };
  8891. var callback;
  8892. // processing for non-image formats
  8893. if (isKTX || isTGA || isDDS) {
  8894. if (isKTX) {
  8895. callback = function (data) {
  8896. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  8897. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  8898. ktx.uploadLevels(_this._gl, !noMipmap);
  8899. }, samplingMode);
  8900. };
  8901. }
  8902. else if (isTGA) {
  8903. callback = function (arrayBuffer) {
  8904. var data = new Uint8Array(arrayBuffer);
  8905. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  8906. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  8907. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  8908. }, samplingMode);
  8909. };
  8910. }
  8911. else if (isDDS) {
  8912. callback = function (data) {
  8913. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8914. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  8915. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  8916. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  8917. }, samplingMode);
  8918. };
  8919. }
  8920. if (!buffer) {
  8921. BABYLON.Tools.LoadFile(url, function (data) {
  8922. callback(data);
  8923. }, null, scene.database, true, onerror);
  8924. }
  8925. else {
  8926. callback(buffer);
  8927. }
  8928. // image format processing
  8929. }
  8930. else {
  8931. var onload = function (img) {
  8932. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  8933. var isPot = (img.width === potWidth && img.height === potHeight);
  8934. if (!isPot) {
  8935. _this._prepareWorkingCanvas();
  8936. _this._workingCanvas.width = potWidth;
  8937. _this._workingCanvas.height = potHeight;
  8938. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8939. _this._workingContext.imageSmoothingEnabled = false;
  8940. _this._workingContext.mozImageSmoothingEnabled = false;
  8941. _this._workingContext.oImageSmoothingEnabled = false;
  8942. _this._workingContext.webkitImageSmoothingEnabled = false;
  8943. _this._workingContext.msImageSmoothingEnabled = false;
  8944. }
  8945. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  8946. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8947. _this._workingContext.imageSmoothingEnabled = true;
  8948. _this._workingContext.mozImageSmoothingEnabled = true;
  8949. _this._workingContext.oImageSmoothingEnabled = true;
  8950. _this._workingContext.webkitImageSmoothingEnabled = true;
  8951. _this._workingContext.msImageSmoothingEnabled = true;
  8952. }
  8953. }
  8954. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? _this._gl.RGB : _this._gl.RGBA);
  8955. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  8956. }, samplingMode);
  8957. };
  8958. if (!fromData || isBase64)
  8959. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  8960. else if (buffer instanceof Array || typeof buffer === "string")
  8961. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  8962. else
  8963. onload(buffer);
  8964. }
  8965. return texture;
  8966. };
  8967. Engine.prototype._getInternalFormat = function (format) {
  8968. var internalFormat = this._gl.RGBA;
  8969. switch (format) {
  8970. case Engine.TEXTUREFORMAT_ALPHA:
  8971. internalFormat = this._gl.ALPHA;
  8972. break;
  8973. case Engine.TEXTUREFORMAT_LUMINANCE:
  8974. internalFormat = this._gl.LUMINANCE;
  8975. break;
  8976. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  8977. internalFormat = this._gl.LUMINANCE_ALPHA;
  8978. break;
  8979. case Engine.TEXTUREFORMAT_RGB:
  8980. internalFormat = this._gl.RGB;
  8981. break;
  8982. case Engine.TEXTUREFORMAT_RGBA:
  8983. internalFormat = this._gl.RGBA;
  8984. break;
  8985. }
  8986. return internalFormat;
  8987. };
  8988. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  8989. if (compression === void 0) { compression = null; }
  8990. var internalFormat = this._getInternalFormat(format);
  8991. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8992. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  8993. if (texture._width % 4 !== 0) {
  8994. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  8995. }
  8996. if (compression) {
  8997. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  8998. }
  8999. else {
  9000. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9001. }
  9002. if (texture.generateMipMaps) {
  9003. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9004. }
  9005. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9006. this.resetTextureCache();
  9007. texture.isReady = true;
  9008. };
  9009. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9010. if (compression === void 0) { compression = null; }
  9011. var texture = this._gl.createTexture();
  9012. texture._baseWidth = width;
  9013. texture._baseHeight = height;
  9014. texture._width = width;
  9015. texture._height = height;
  9016. texture.references = 1;
  9017. this.updateRawTexture(texture, data, format, invertY, compression);
  9018. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9019. // Filters
  9020. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9021. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9022. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9023. if (generateMipMaps) {
  9024. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9025. }
  9026. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9027. texture.samplingMode = samplingMode;
  9028. this._loadedTexturesCache.push(texture);
  9029. return texture;
  9030. };
  9031. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9032. var texture = this._gl.createTexture();
  9033. texture._baseWidth = width;
  9034. texture._baseHeight = height;
  9035. if (generateMipMaps) {
  9036. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  9037. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  9038. }
  9039. this.resetTextureCache();
  9040. texture._width = width;
  9041. texture._height = height;
  9042. texture.isReady = false;
  9043. texture.generateMipMaps = generateMipMaps;
  9044. texture.references = 1;
  9045. texture.samplingMode = samplingMode;
  9046. this.updateTextureSamplingMode(samplingMode, texture);
  9047. this._loadedTexturesCache.push(texture);
  9048. return texture;
  9049. };
  9050. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9051. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9052. if (texture.isCube) {
  9053. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9054. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9055. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9056. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9057. }
  9058. else {
  9059. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9060. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9061. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9062. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9063. }
  9064. texture.samplingMode = samplingMode;
  9065. };
  9066. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9067. if (premulAlpha === void 0) { premulAlpha = false; }
  9068. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9069. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9070. if (premulAlpha) {
  9071. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9072. }
  9073. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9074. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9075. if (texture.generateMipMaps) {
  9076. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9077. }
  9078. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9079. if (premulAlpha) {
  9080. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9081. }
  9082. this.resetTextureCache();
  9083. texture.isReady = true;
  9084. };
  9085. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9086. if (texture._isDisabled) {
  9087. return;
  9088. }
  9089. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9090. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9091. try {
  9092. // Testing video texture support
  9093. if (this._videoTextureSupported === undefined) {
  9094. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9095. if (this._gl.getError() !== 0) {
  9096. this._videoTextureSupported = false;
  9097. }
  9098. else {
  9099. this._videoTextureSupported = true;
  9100. }
  9101. }
  9102. // Copy video through the current working canvas if video texture is not supported
  9103. if (!this._videoTextureSupported) {
  9104. if (!texture._workingCanvas) {
  9105. texture._workingCanvas = document.createElement("canvas");
  9106. texture._workingContext = texture._workingCanvas.getContext("2d");
  9107. texture._workingCanvas.width = texture._width;
  9108. texture._workingCanvas.height = texture._height;
  9109. }
  9110. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9111. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9112. }
  9113. else {
  9114. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9115. }
  9116. if (texture.generateMipMaps) {
  9117. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9118. }
  9119. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9120. this.resetTextureCache();
  9121. texture.isReady = true;
  9122. }
  9123. catch (ex) {
  9124. // Something unexpected
  9125. // Let's disable the texture
  9126. texture._isDisabled = true;
  9127. }
  9128. };
  9129. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9130. // old version had a "generateMipMaps" arg instead of options.
  9131. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9132. // in the same way, generateDepthBuffer is defaulted to true
  9133. var generateMipMaps = false;
  9134. var generateDepthBuffer = true;
  9135. var generateStencilBuffer = false;
  9136. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9137. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9138. if (options !== undefined) {
  9139. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9140. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9141. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9142. type = options.type === undefined ? type : options.type;
  9143. if (options.samplingMode !== undefined) {
  9144. samplingMode = options.samplingMode;
  9145. }
  9146. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9147. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9148. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9149. }
  9150. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9151. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9152. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9153. }
  9154. }
  9155. var gl = this._gl;
  9156. var texture = gl.createTexture();
  9157. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9158. var width = size.width || size;
  9159. var height = size.height || size;
  9160. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9161. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9162. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9163. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9164. }
  9165. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9166. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9167. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9168. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9169. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9170. // Create the framebuffer
  9171. var framebuffer = gl.createFramebuffer();
  9172. this.bindUnboundFramebuffer(framebuffer);
  9173. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9174. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9175. if (generateMipMaps) {
  9176. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9177. }
  9178. // Unbind
  9179. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9180. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9181. this.bindUnboundFramebuffer(null);
  9182. texture._framebuffer = framebuffer;
  9183. texture._baseWidth = width;
  9184. texture._baseHeight = height;
  9185. texture._width = width;
  9186. texture._height = height;
  9187. texture.isReady = true;
  9188. texture.samples = 1;
  9189. texture.generateMipMaps = generateMipMaps;
  9190. texture.references = 1;
  9191. texture.samplingMode = samplingMode;
  9192. texture.type = type;
  9193. texture._generateDepthBuffer = generateDepthBuffer;
  9194. texture._generateStencilBuffer = generateStencilBuffer;
  9195. this.resetTextureCache();
  9196. this._loadedTexturesCache.push(texture);
  9197. return texture;
  9198. };
  9199. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9200. if (samples === void 0) { samples = 1; }
  9201. var depthStencilBuffer = null;
  9202. var gl = this._gl;
  9203. // Create the depth/stencil buffer
  9204. if (generateStencilBuffer) {
  9205. depthStencilBuffer = gl.createRenderbuffer();
  9206. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9207. if (samples > 1) {
  9208. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9209. }
  9210. else {
  9211. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9212. }
  9213. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9214. }
  9215. else if (generateDepthBuffer) {
  9216. depthStencilBuffer = gl.createRenderbuffer();
  9217. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9218. if (samples > 1) {
  9219. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9220. }
  9221. else {
  9222. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9223. }
  9224. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9225. }
  9226. return depthStencilBuffer;
  9227. };
  9228. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9229. if (this.webGLVersion < 2) {
  9230. return 1;
  9231. }
  9232. if (texture.samples === samples) {
  9233. return samples;
  9234. }
  9235. var gl = this._gl;
  9236. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9237. // Dispose previous render buffers
  9238. if (texture._depthStencilBuffer) {
  9239. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9240. }
  9241. if (texture._MSAAFramebuffer) {
  9242. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9243. }
  9244. if (texture._MSAARenderBuffer) {
  9245. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9246. }
  9247. if (samples > 1) {
  9248. texture._MSAAFramebuffer = gl.createFramebuffer();
  9249. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9250. var colorRenderbuffer = gl.createRenderbuffer();
  9251. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9252. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9253. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9254. texture._MSAARenderBuffer = colorRenderbuffer;
  9255. }
  9256. else {
  9257. this.bindUnboundFramebuffer(texture._framebuffer);
  9258. }
  9259. texture.samples = samples;
  9260. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9261. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9262. this.bindUnboundFramebuffer(null);
  9263. return samples;
  9264. };
  9265. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9266. var gl = this._gl;
  9267. var texture = gl.createTexture();
  9268. var generateMipMaps = true;
  9269. var generateDepthBuffer = true;
  9270. var generateStencilBuffer = false;
  9271. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9272. if (options !== undefined) {
  9273. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9274. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9275. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9276. if (options.samplingMode !== undefined) {
  9277. samplingMode = options.samplingMode;
  9278. }
  9279. }
  9280. texture.isCube = true;
  9281. texture.references = 1;
  9282. texture.generateMipMaps = generateMipMaps;
  9283. texture.references = 1;
  9284. texture.samples = 1;
  9285. texture.samplingMode = samplingMode;
  9286. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9287. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9288. for (var face = 0; face < 6; face++) {
  9289. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9290. }
  9291. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9292. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9293. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9294. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9295. // Create the framebuffer
  9296. var framebuffer = gl.createFramebuffer();
  9297. this.bindUnboundFramebuffer(framebuffer);
  9298. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  9299. // Mipmaps
  9300. if (texture.generateMipMaps) {
  9301. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9302. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9303. }
  9304. // Unbind
  9305. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9306. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9307. this.bindUnboundFramebuffer(null);
  9308. texture._framebuffer = framebuffer;
  9309. texture._width = size;
  9310. texture._height = size;
  9311. texture.isReady = true;
  9312. this.resetTextureCache();
  9313. this._loadedTexturesCache.push(texture);
  9314. return texture;
  9315. };
  9316. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  9317. var _this = this;
  9318. if (onLoad === void 0) { onLoad = null; }
  9319. if (onError === void 0) { onError = null; }
  9320. var gl = this._gl;
  9321. var texture = gl.createTexture();
  9322. texture.isCube = true;
  9323. texture.url = rootUrl;
  9324. texture.references = 1;
  9325. texture.onLoadedCallbacks = [];
  9326. var isKTX = false;
  9327. var lastDot = rootUrl.lastIndexOf('.');
  9328. var extension = rootUrl.substring(lastDot).toLowerCase();
  9329. if (this._textureFormatInUse) {
  9330. extension = this._textureFormatInUse;
  9331. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  9332. isKTX = true;
  9333. }
  9334. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9335. if (isDDS) {
  9336. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9337. }
  9338. if (isKTX) {
  9339. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9340. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  9341. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  9342. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9343. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9344. ktx.uploadLevels(_this._gl, !noMipmap);
  9345. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9346. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9347. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9348. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9349. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9350. _this.resetTextureCache();
  9351. texture._width = ktx.pixelWidth;
  9352. texture._height = ktx.pixelHeight;
  9353. texture.isReady = true;
  9354. }, null, null, true, onError);
  9355. }
  9356. else if (isDDS) {
  9357. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9358. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9359. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  9360. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9361. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9362. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  9363. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  9364. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9365. }
  9366. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9367. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9368. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9369. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9370. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9371. _this.resetTextureCache();
  9372. texture._width = info.width;
  9373. texture._height = info.height;
  9374. texture.isReady = true;
  9375. }, null, null, true, onError);
  9376. }
  9377. else {
  9378. cascadeLoad(rootUrl, scene, function (imgs) {
  9379. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  9380. var height = width;
  9381. _this._prepareWorkingCanvas();
  9382. _this._workingCanvas.width = width;
  9383. _this._workingCanvas.height = height;
  9384. var faces = [
  9385. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9386. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9387. ];
  9388. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9389. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9390. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9391. for (var index = 0; index < faces.length; index++) {
  9392. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  9393. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  9394. }
  9395. if (!noMipmap) {
  9396. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9397. }
  9398. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9399. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9400. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9401. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9402. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9403. _this.resetTextureCache();
  9404. texture._width = width;
  9405. texture._height = height;
  9406. texture.isReady = true;
  9407. texture.onLoadedCallbacks.forEach(function (callback) {
  9408. callback();
  9409. });
  9410. if (onLoad) {
  9411. onLoad();
  9412. }
  9413. }, files, onError);
  9414. }
  9415. this._loadedTexturesCache.push(texture);
  9416. return texture;
  9417. };
  9418. Engine.prototype.updateTextureSize = function (texture, width, height) {
  9419. texture._width = width;
  9420. texture._height = height;
  9421. texture._size = width * height;
  9422. texture._baseWidth = width;
  9423. texture._baseHeight = height;
  9424. };
  9425. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError) {
  9426. var _this = this;
  9427. if (onLoad === void 0) { onLoad = null; }
  9428. if (onError === void 0) { onError = null; }
  9429. var gl = this._gl;
  9430. var texture = gl.createTexture();
  9431. scene._addPendingData(texture);
  9432. texture.isCube = true;
  9433. texture.references = 1;
  9434. texture.url = url;
  9435. var textureType = gl.UNSIGNED_BYTE;
  9436. if (type === Engine.TEXTURETYPE_FLOAT) {
  9437. textureType = gl.FLOAT;
  9438. }
  9439. var internalFormat = this._getInternalFormat(format);
  9440. var needConversion = false;
  9441. if (internalFormat === gl.RGB) {
  9442. internalFormat = gl.RGBA;
  9443. needConversion = true;
  9444. }
  9445. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9446. var width = size;
  9447. var height = width;
  9448. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  9449. texture._width = width;
  9450. texture._height = height;
  9451. var onerror = function () {
  9452. scene._removePendingData(texture);
  9453. if (onError) {
  9454. onError();
  9455. }
  9456. };
  9457. var internalCallback = function (data) {
  9458. var rgbeDataArrays = callback(data);
  9459. var facesIndex = [
  9460. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9461. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9462. ];
  9463. width = texture._width;
  9464. height = texture._height;
  9465. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  9466. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9467. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9468. if (mipmmapGenerator) {
  9469. var arrayTemp = [];
  9470. // Data are known to be in +X +Y +Z -X -Y -Z
  9471. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  9472. arrayTemp.push(rgbeDataArrays[0]); // +X
  9473. arrayTemp.push(rgbeDataArrays[3]); // -X
  9474. arrayTemp.push(rgbeDataArrays[1]); // +Y
  9475. arrayTemp.push(rgbeDataArrays[4]); // -Y
  9476. arrayTemp.push(rgbeDataArrays[2]); // +Z
  9477. arrayTemp.push(rgbeDataArrays[5]); // -Z
  9478. var mipData = mipmmapGenerator(arrayTemp);
  9479. // mipData is order in +X -X +Y -Y +Z -Z
  9480. var mipFaces = [0, 2, 4, 1, 3, 5];
  9481. for (var level = 0; level < mipData.length; level++) {
  9482. var mipSize = width >> level;
  9483. for (var mipIndex in mipFaces) {
  9484. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  9485. if (needConversion) {
  9486. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  9487. }
  9488. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  9489. }
  9490. }
  9491. }
  9492. else {
  9493. // Data are known to be in +X +Y +Z -X -Y -Z
  9494. for (var index = 0; index < facesIndex.length; index++) {
  9495. var faceData = rgbeDataArrays[index];
  9496. if (needConversion) {
  9497. faceData = _this._convertRGBtoRGBATextureData(faceData, width, height, type);
  9498. }
  9499. gl.texImage2D(facesIndex[index], 0, internalSizedFomat, width, height, 0, internalFormat, textureType, faceData);
  9500. }
  9501. if (!noMipmap && isPot) {
  9502. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9503. }
  9504. else {
  9505. noMipmap = true;
  9506. }
  9507. }
  9508. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  9509. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9510. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9511. }
  9512. else if (textureType === Engine.HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  9513. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9514. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9515. }
  9516. else {
  9517. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9518. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9519. }
  9520. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9521. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9522. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9523. texture.isReady = true;
  9524. _this.resetTextureCache();
  9525. scene._removePendingData(texture);
  9526. if (onLoad) {
  9527. onLoad();
  9528. }
  9529. };
  9530. BABYLON.Tools.LoadFile(url, function (data) {
  9531. internalCallback(data);
  9532. }, onerror, scene.database, true);
  9533. return texture;
  9534. };
  9535. ;
  9536. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  9537. // Create new RGBA data container.
  9538. var rgbaData;
  9539. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  9540. rgbaData = new Float32Array(width * height * 4);
  9541. }
  9542. else {
  9543. rgbaData = new Uint32Array(width * height * 4);
  9544. }
  9545. // Convert each pixel.
  9546. for (var x = 0; x < width; x++) {
  9547. for (var y = 0; y < height; y++) {
  9548. var index = (y * width + x) * 3;
  9549. var newIndex = (y * width + x) * 4;
  9550. // Map Old Value to new value.
  9551. rgbaData[newIndex + 0] = rgbData[index + 0];
  9552. rgbaData[newIndex + 1] = rgbData[index + 1];
  9553. rgbaData[newIndex + 2] = rgbData[index + 2];
  9554. // Add fully opaque alpha channel.
  9555. rgbaData[newIndex + 3] = 1;
  9556. }
  9557. }
  9558. return rgbaData;
  9559. };
  9560. Engine.prototype._releaseTexture = function (texture) {
  9561. var gl = this._gl;
  9562. if (texture._framebuffer) {
  9563. gl.deleteFramebuffer(texture._framebuffer);
  9564. }
  9565. if (texture._depthStencilBuffer) {
  9566. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9567. }
  9568. if (texture._MSAAFramebuffer) {
  9569. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9570. }
  9571. if (texture._MSAARenderBuffer) {
  9572. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9573. }
  9574. gl.deleteTexture(texture);
  9575. // Unbind channels
  9576. this.unbindAllTextures();
  9577. var index = this._loadedTexturesCache.indexOf(texture);
  9578. if (index !== -1) {
  9579. this._loadedTexturesCache.splice(index, 1);
  9580. }
  9581. };
  9582. Engine.prototype.setProgram = function (program) {
  9583. if (this._currentProgram !== program) {
  9584. this._gl.useProgram(program);
  9585. this._currentProgram = program;
  9586. }
  9587. };
  9588. Engine.prototype.bindSamplers = function (effect) {
  9589. this.setProgram(effect.getProgram());
  9590. var samplers = effect.getSamplers();
  9591. for (var index = 0; index < samplers.length; index++) {
  9592. var uniform = effect.getUniform(samplers[index]);
  9593. this._gl.uniform1i(uniform, index);
  9594. }
  9595. this._currentEffect = null;
  9596. };
  9597. Engine.prototype.activateTexture = function (texture) {
  9598. if (this._activeTexture !== texture) {
  9599. this._gl.activeTexture(texture);
  9600. this._activeTexture = texture;
  9601. }
  9602. };
  9603. Engine.prototype._bindTextureDirectly = function (target, texture) {
  9604. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  9605. this._gl.bindTexture(target, texture);
  9606. this._activeTexturesCache[this._activeTexture] = texture;
  9607. }
  9608. };
  9609. Engine.prototype._bindTexture = function (channel, texture) {
  9610. if (channel < 0) {
  9611. return;
  9612. }
  9613. this.activateTexture(this._gl.TEXTURE0 + channel);
  9614. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9615. };
  9616. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  9617. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  9618. };
  9619. Engine.prototype.unbindAllTextures = function () {
  9620. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  9621. this.activateTexture(this._gl["TEXTURE" + channel]);
  9622. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9623. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9624. }
  9625. };
  9626. Engine.prototype.setTexture = function (channel, uniform, texture) {
  9627. if (channel < 0) {
  9628. return;
  9629. }
  9630. this._gl.uniform1i(uniform, channel);
  9631. this._setTexture(channel, texture);
  9632. };
  9633. Engine.prototype._setTexture = function (channel, texture) {
  9634. // Not ready?
  9635. if (!texture || !texture.isReady()) {
  9636. if (this._activeTexturesCache[channel] != null) {
  9637. this.activateTexture(this._gl["TEXTURE" + channel]);
  9638. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9639. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9640. }
  9641. return;
  9642. }
  9643. // Video
  9644. var alreadyActivated = false;
  9645. if (texture.video) {
  9646. this.activateTexture(this._gl["TEXTURE" + channel]);
  9647. alreadyActivated = true;
  9648. texture.update();
  9649. }
  9650. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  9651. texture.delayLoad();
  9652. return;
  9653. }
  9654. var internalTexture = texture.getInternalTexture();
  9655. if (this._activeTexturesCache[channel] === internalTexture) {
  9656. return;
  9657. }
  9658. if (!alreadyActivated) {
  9659. this.activateTexture(this._gl["TEXTURE" + channel]);
  9660. }
  9661. if (internalTexture.isCube) {
  9662. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  9663. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  9664. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  9665. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  9666. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  9667. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  9668. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  9669. }
  9670. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  9671. }
  9672. else {
  9673. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  9674. if (internalTexture._cachedWrapU !== texture.wrapU) {
  9675. internalTexture._cachedWrapU = texture.wrapU;
  9676. switch (texture.wrapU) {
  9677. case BABYLON.Texture.WRAP_ADDRESSMODE:
  9678. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  9679. break;
  9680. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  9681. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  9682. break;
  9683. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  9684. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  9685. break;
  9686. }
  9687. }
  9688. if (internalTexture._cachedWrapV !== texture.wrapV) {
  9689. internalTexture._cachedWrapV = texture.wrapV;
  9690. switch (texture.wrapV) {
  9691. case BABYLON.Texture.WRAP_ADDRESSMODE:
  9692. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  9693. break;
  9694. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  9695. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  9696. break;
  9697. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  9698. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  9699. break;
  9700. }
  9701. }
  9702. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  9703. }
  9704. };
  9705. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  9706. if (channel < 0) {
  9707. return;
  9708. }
  9709. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  9710. this._textureUnits = new Int32Array(textures.length);
  9711. }
  9712. for (var i = 0; i < textures.length; i++) {
  9713. this._textureUnits[i] = channel + i;
  9714. }
  9715. this._gl.uniform1iv(uniform, this._textureUnits);
  9716. for (var index = 0; index < textures.length; index++) {
  9717. this._setTexture(channel + index, textures[index]);
  9718. }
  9719. };
  9720. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  9721. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  9722. var value = texture.anisotropicFilteringLevel;
  9723. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9724. value = 1;
  9725. }
  9726. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  9727. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  9728. texture._cachedAnisotropicFilteringLevel = value;
  9729. }
  9730. };
  9731. Engine.prototype.readPixels = function (x, y, width, height) {
  9732. var data = new Uint8Array(height * width * 4);
  9733. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  9734. return data;
  9735. };
  9736. /**
  9737. * Add an externaly attached data from its key.
  9738. * This method call will fail and return false, if such key already exists.
  9739. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  9740. * @param key the unique key that identifies the data
  9741. * @param data the data object to associate to the key for this Engine instance
  9742. * @return true if no such key were already present and the data was added successfully, false otherwise
  9743. */
  9744. Engine.prototype.addExternalData = function (key, data) {
  9745. if (!this._externalData) {
  9746. this._externalData = new BABYLON.StringDictionary();
  9747. }
  9748. return this._externalData.add(key, data);
  9749. };
  9750. /**
  9751. * Get an externaly attached data from its key
  9752. * @param key the unique key that identifies the data
  9753. * @return the associated data, if present (can be null), or undefined if not present
  9754. */
  9755. Engine.prototype.getExternalData = function (key) {
  9756. if (!this._externalData) {
  9757. this._externalData = new BABYLON.StringDictionary();
  9758. }
  9759. return this._externalData.get(key);
  9760. };
  9761. /**
  9762. * Get an externaly attached data from its key, create it using a factory if it's not already present
  9763. * @param key the unique key that identifies the data
  9764. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  9765. * @return the associated data, can be null if the factory returned null.
  9766. */
  9767. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  9768. if (!this._externalData) {
  9769. this._externalData = new BABYLON.StringDictionary();
  9770. }
  9771. return this._externalData.getOrAddWithFactory(key, factory);
  9772. };
  9773. /**
  9774. * Remove an externaly attached data from the Engine instance
  9775. * @param key the unique key that identifies the data
  9776. * @return true if the data was successfully removed, false if it doesn't exist
  9777. */
  9778. Engine.prototype.removeExternalData = function (key) {
  9779. if (!this._externalData) {
  9780. this._externalData = new BABYLON.StringDictionary();
  9781. }
  9782. return this._externalData.remove(key);
  9783. };
  9784. Engine.prototype.releaseInternalTexture = function (texture) {
  9785. if (!texture) {
  9786. return;
  9787. }
  9788. texture.references--;
  9789. // Final reference ?
  9790. if (texture.references === 0) {
  9791. var texturesCache = this.getLoadedTexturesCache();
  9792. var index = texturesCache.indexOf(texture);
  9793. if (index > -1) {
  9794. texturesCache.splice(index, 1);
  9795. }
  9796. this._releaseTexture(texture);
  9797. }
  9798. };
  9799. Engine.prototype.unbindAllAttributes = function () {
  9800. if (this._mustWipeVertexAttributes) {
  9801. this._mustWipeVertexAttributes = false;
  9802. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9803. this._gl.disableVertexAttribArray(i);
  9804. this._vertexAttribArraysEnabled[i] = false;
  9805. this._currentBufferPointers[i] = null;
  9806. }
  9807. return;
  9808. }
  9809. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  9810. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  9811. continue;
  9812. }
  9813. this._gl.disableVertexAttribArray(i);
  9814. this._vertexAttribArraysEnabled[i] = false;
  9815. this._currentBufferPointers[i] = null;
  9816. }
  9817. };
  9818. Engine.prototype.releaseEffects = function () {
  9819. for (var name in this._compiledEffects) {
  9820. this._gl.deleteProgram(this._compiledEffects[name]._program);
  9821. }
  9822. this._compiledEffects = {};
  9823. };
  9824. // Dispose
  9825. Engine.prototype.dispose = function () {
  9826. this.hideLoadingUI();
  9827. this.stopRenderLoop();
  9828. // Release scenes
  9829. while (this.scenes.length) {
  9830. this.scenes[0].dispose();
  9831. }
  9832. // Release audio engine
  9833. Engine.audioEngine.dispose();
  9834. // Release effects
  9835. this.releaseEffects();
  9836. // Unbind
  9837. this.unbindAllAttributes();
  9838. this._gl = null;
  9839. //WebVR
  9840. this.disableVR();
  9841. // Events
  9842. window.removeEventListener("blur", this._onBlur);
  9843. window.removeEventListener("focus", this._onFocus);
  9844. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  9845. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  9846. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  9847. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  9848. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  9849. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  9850. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  9851. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  9852. // Remove from Instances
  9853. var index = Engine.Instances.indexOf(this);
  9854. if (index >= 0) {
  9855. Engine.Instances.splice(index, 1);
  9856. }
  9857. };
  9858. // Loading screen
  9859. Engine.prototype.displayLoadingUI = function () {
  9860. this.loadingScreen.displayLoadingUI();
  9861. };
  9862. Engine.prototype.hideLoadingUI = function () {
  9863. this.loadingScreen.hideLoadingUI();
  9864. };
  9865. Object.defineProperty(Engine.prototype, "loadingScreen", {
  9866. get: function () {
  9867. if (!this._loadingScreen)
  9868. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  9869. return this._loadingScreen;
  9870. },
  9871. set: function (loadingScreen) {
  9872. this._loadingScreen = loadingScreen;
  9873. },
  9874. enumerable: true,
  9875. configurable: true
  9876. });
  9877. Object.defineProperty(Engine.prototype, "loadingUIText", {
  9878. set: function (text) {
  9879. this.loadingScreen.loadingUIText = text;
  9880. },
  9881. enumerable: true,
  9882. configurable: true
  9883. });
  9884. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  9885. set: function (color) {
  9886. this.loadingScreen.loadingUIBackgroundColor = color;
  9887. },
  9888. enumerable: true,
  9889. configurable: true
  9890. });
  9891. Engine.prototype.attachContextLostEvent = function (callback) {
  9892. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  9893. };
  9894. Engine.prototype.attachContextRestoredEvent = function (callback) {
  9895. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  9896. };
  9897. Engine.prototype.getVertexShaderSource = function (program) {
  9898. var shaders = this._gl.getAttachedShaders(program);
  9899. return this._gl.getShaderSource(shaders[0]);
  9900. };
  9901. Engine.prototype.getFragmentShaderSource = function (program) {
  9902. var shaders = this._gl.getAttachedShaders(program);
  9903. return this._gl.getShaderSource(shaders[1]);
  9904. };
  9905. // FPS
  9906. Engine.prototype.getFps = function () {
  9907. return this.fps;
  9908. };
  9909. Engine.prototype.getDeltaTime = function () {
  9910. return this.deltaTime;
  9911. };
  9912. Engine.prototype._measureFps = function () {
  9913. this.previousFramesDuration.push(BABYLON.Tools.Now);
  9914. var length = this.previousFramesDuration.length;
  9915. if (length >= 2) {
  9916. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  9917. }
  9918. if (length >= this.fpsRange) {
  9919. if (length > this.fpsRange) {
  9920. this.previousFramesDuration.splice(0, 1);
  9921. length = this.previousFramesDuration.length;
  9922. }
  9923. var sum = 0;
  9924. for (var id = 0; id < length - 1; id++) {
  9925. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  9926. }
  9927. this.fps = 1000.0 / (sum / (length - 1));
  9928. }
  9929. };
  9930. Engine.prototype._canRenderToFloatFramebuffer = function () {
  9931. if (this._webGLVersion > 1) {
  9932. return this._caps.colorBufferFloat;
  9933. }
  9934. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  9935. };
  9936. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  9937. if (this._webGLVersion > 1) {
  9938. return this._caps.colorBufferFloat;
  9939. }
  9940. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  9941. };
  9942. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  9943. Engine.prototype._canRenderToFramebuffer = function (type) {
  9944. var gl = this._gl;
  9945. //clear existing errors
  9946. while (gl.getError() !== gl.NO_ERROR) { }
  9947. var successful = true;
  9948. var texture = gl.createTexture();
  9949. gl.bindTexture(gl.TEXTURE_2D, texture);
  9950. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9951. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9952. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9953. var fb = gl.createFramebuffer();
  9954. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  9955. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9956. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  9957. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  9958. successful = successful && (gl.getError() === gl.NO_ERROR);
  9959. //try render by clearing frame buffer's color buffer
  9960. if (successful) {
  9961. gl.clear(gl.COLOR_BUFFER_BIT);
  9962. successful = successful && (gl.getError() === gl.NO_ERROR);
  9963. }
  9964. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  9965. if (successful) {
  9966. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  9967. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9968. var readFormat = gl.RGBA;
  9969. var readType = gl.UNSIGNED_BYTE;
  9970. var buffer = new Uint8Array(4);
  9971. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  9972. successful = successful && (gl.getError() === gl.NO_ERROR);
  9973. }
  9974. //clean up
  9975. gl.deleteTexture(texture);
  9976. gl.deleteFramebuffer(fb);
  9977. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9978. //clear accumulated errors
  9979. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  9980. return successful;
  9981. };
  9982. Engine.prototype._getWebGLTextureType = function (type) {
  9983. if (type === Engine.TEXTURETYPE_FLOAT) {
  9984. return this._gl.FLOAT;
  9985. }
  9986. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  9987. // Add Half Float Constant.
  9988. return Engine.HALF_FLOAT_OES;
  9989. }
  9990. return this._gl.UNSIGNED_BYTE;
  9991. };
  9992. ;
  9993. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  9994. if (this._webGLVersion === 1) {
  9995. return this._gl.RGBA;
  9996. }
  9997. if (type === Engine.TEXTURETYPE_FLOAT) {
  9998. return Engine.RGBA32F;
  9999. }
  10000. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  10001. return Engine.RGBA16F;
  10002. }
  10003. return this._gl.RGBA;
  10004. };
  10005. ;
  10006. // Statics
  10007. Engine.isSupported = function () {
  10008. try {
  10009. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  10010. if (navigator.isCocoonJS) {
  10011. return true;
  10012. }
  10013. var tempcanvas = document.createElement("canvas");
  10014. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  10015. return gl != null && !!window.WebGLRenderingContext;
  10016. }
  10017. catch (e) {
  10018. return false;
  10019. }
  10020. };
  10021. return Engine;
  10022. }());
  10023. Engine.Instances = new Array();
  10024. // Const statics
  10025. Engine._ALPHA_DISABLE = 0;
  10026. Engine._ALPHA_ADD = 1;
  10027. Engine._ALPHA_COMBINE = 2;
  10028. Engine._ALPHA_SUBTRACT = 3;
  10029. Engine._ALPHA_MULTIPLY = 4;
  10030. Engine._ALPHA_MAXIMIZED = 5;
  10031. Engine._ALPHA_ONEONE = 6;
  10032. Engine._ALPHA_PREMULTIPLIED = 7;
  10033. Engine._DELAYLOADSTATE_NONE = 0;
  10034. Engine._DELAYLOADSTATE_LOADED = 1;
  10035. Engine._DELAYLOADSTATE_LOADING = 2;
  10036. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  10037. Engine._TEXTUREFORMAT_ALPHA = 0;
  10038. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  10039. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  10040. Engine._TEXTUREFORMAT_RGB = 4;
  10041. Engine._TEXTUREFORMAT_RGBA = 5;
  10042. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  10043. Engine._TEXTURETYPE_FLOAT = 1;
  10044. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  10045. // Depht or Stencil test Constants.
  10046. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  10047. Engine._ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  10048. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  10049. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  10050. Engine._LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  10051. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  10052. Engine._GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  10053. Engine._NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  10054. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  10055. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  10056. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  10057. // Stencil Actions Constants.
  10058. Engine._KEEP = 0x1E00;
  10059. Engine._REPLACE = 0x1E01;
  10060. Engine._INCR = 0x1E02;
  10061. Engine._DECR = 0x1E03;
  10062. Engine._INVERT = 0x150A;
  10063. Engine._INCR_WRAP = 0x8507;
  10064. Engine._DECR_WRAP = 0x8508;
  10065. // Updatable statics so stick with vars here
  10066. Engine.CollisionsEpsilon = 0.001;
  10067. Engine.CodeRepository = "src/";
  10068. Engine.ShadersRepository = "src/Shaders/";
  10069. BABYLON.Engine = Engine;
  10070. })(BABYLON || (BABYLON = {}));
  10071. //# sourceMappingURL=babylon.engine.js.map
  10072. /// <reference path="Tools\babylon.decorators.ts" />
  10073. var BABYLON;
  10074. (function (BABYLON) {
  10075. /**
  10076. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10077. */
  10078. var Node = (function () {
  10079. /**
  10080. * @constructor
  10081. * @param {string} name - the name and id to be given to this node
  10082. * @param {BABYLON.Scene} the scene this node will be added to
  10083. */
  10084. function Node(name, scene) {
  10085. this.state = "";
  10086. this.metadata = null;
  10087. this.doNotSerialize = false;
  10088. this.animations = new Array();
  10089. this._ranges = {};
  10090. this._childrenFlag = -1;
  10091. this._isEnabled = true;
  10092. this._isReady = true;
  10093. this._currentRenderId = -1;
  10094. this._parentRenderId = -1;
  10095. /**
  10096. * An event triggered when the mesh is disposed.
  10097. * @type {BABYLON.Observable}
  10098. */
  10099. this.onDisposeObservable = new BABYLON.Observable();
  10100. this.name = name;
  10101. this.id = name;
  10102. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10103. this._initCache();
  10104. }
  10105. Object.defineProperty(Node.prototype, "parent", {
  10106. get: function () {
  10107. return this._parentNode;
  10108. },
  10109. set: function (parent) {
  10110. if (this._parentNode === parent) {
  10111. return;
  10112. }
  10113. if (this._parentNode) {
  10114. var index = this._parentNode._children.indexOf(this);
  10115. if (index !== -1) {
  10116. this._parentNode._children.splice(index, 1);
  10117. }
  10118. }
  10119. this._parentNode = parent;
  10120. if (this._parentNode) {
  10121. if (!this._parentNode._children) {
  10122. this._parentNode._children = new Array();
  10123. }
  10124. this._parentNode._children.push(this);
  10125. }
  10126. },
  10127. enumerable: true,
  10128. configurable: true
  10129. });
  10130. Node.prototype.getClassName = function () {
  10131. return "Node";
  10132. };
  10133. Object.defineProperty(Node.prototype, "onDispose", {
  10134. set: function (callback) {
  10135. if (this._onDisposeObserver) {
  10136. this.onDisposeObservable.remove(this._onDisposeObserver);
  10137. }
  10138. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10139. },
  10140. enumerable: true,
  10141. configurable: true
  10142. });
  10143. Node.prototype.getScene = function () {
  10144. return this._scene;
  10145. };
  10146. Node.prototype.getEngine = function () {
  10147. return this._scene.getEngine();
  10148. };
  10149. // override it in derived class
  10150. Node.prototype.getWorldMatrix = function () {
  10151. return BABYLON.Matrix.Identity();
  10152. };
  10153. // override it in derived class if you add new variables to the cache
  10154. // and call the parent class method
  10155. Node.prototype._initCache = function () {
  10156. this._cache = {};
  10157. this._cache.parent = undefined;
  10158. };
  10159. Node.prototype.updateCache = function (force) {
  10160. if (!force && this.isSynchronized())
  10161. return;
  10162. this._cache.parent = this.parent;
  10163. this._updateCache();
  10164. };
  10165. // override it in derived class if you add new variables to the cache
  10166. // and call the parent class method if !ignoreParentClass
  10167. Node.prototype._updateCache = function (ignoreParentClass) {
  10168. };
  10169. // override it in derived class if you add new variables to the cache
  10170. Node.prototype._isSynchronized = function () {
  10171. return true;
  10172. };
  10173. Node.prototype._markSyncedWithParent = function () {
  10174. this._parentRenderId = this.parent._currentRenderId;
  10175. };
  10176. Node.prototype.isSynchronizedWithParent = function () {
  10177. if (!this.parent) {
  10178. return true;
  10179. }
  10180. if (this._parentRenderId !== this.parent._currentRenderId) {
  10181. return false;
  10182. }
  10183. return this.parent.isSynchronized();
  10184. };
  10185. Node.prototype.isSynchronized = function (updateCache) {
  10186. var check = this.hasNewParent();
  10187. check = check || !this.isSynchronizedWithParent();
  10188. check = check || !this._isSynchronized();
  10189. if (updateCache)
  10190. this.updateCache(true);
  10191. return !check;
  10192. };
  10193. Node.prototype.hasNewParent = function (update) {
  10194. if (this._cache.parent === this.parent)
  10195. return false;
  10196. if (update)
  10197. this._cache.parent = this.parent;
  10198. return true;
  10199. };
  10200. /**
  10201. * Is this node ready to be used/rendered
  10202. * @return {boolean} is it ready
  10203. */
  10204. Node.prototype.isReady = function () {
  10205. return this._isReady;
  10206. };
  10207. /**
  10208. * Is this node enabled.
  10209. * If the node has a parent and is enabled, the parent will be inspected as well.
  10210. * @return {boolean} whether this node (and its parent) is enabled.
  10211. * @see setEnabled
  10212. */
  10213. Node.prototype.isEnabled = function () {
  10214. if (!this._isEnabled) {
  10215. return false;
  10216. }
  10217. if (this.parent) {
  10218. return this.parent.isEnabled();
  10219. }
  10220. return true;
  10221. };
  10222. /**
  10223. * Set the enabled state of this node.
  10224. * @param {boolean} value - the new enabled state
  10225. * @see isEnabled
  10226. */
  10227. Node.prototype.setEnabled = function (value) {
  10228. this._isEnabled = value;
  10229. };
  10230. /**
  10231. * Is this node a descendant of the given node.
  10232. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10233. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10234. * @see parent
  10235. */
  10236. Node.prototype.isDescendantOf = function (ancestor) {
  10237. if (this.parent) {
  10238. if (this.parent === ancestor) {
  10239. return true;
  10240. }
  10241. return this.parent.isDescendantOf(ancestor);
  10242. }
  10243. return false;
  10244. };
  10245. /**
  10246. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10247. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10248. * @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.
  10249. * @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.
  10250. */
  10251. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10252. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10253. if (!this._children) {
  10254. return;
  10255. }
  10256. for (var index = 0; index < this._children.length; index++) {
  10257. var item = this._children[index];
  10258. if (!predicate || predicate(item)) {
  10259. results.push(item);
  10260. }
  10261. if (!directDescendantsOnly) {
  10262. item._getDescendants(results, false, predicate);
  10263. }
  10264. }
  10265. };
  10266. /**
  10267. * Will return all nodes that have this node as ascendant.
  10268. * @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.
  10269. * @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.
  10270. * @return {BABYLON.Node[]} all children nodes of all types.
  10271. */
  10272. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10273. var results = [];
  10274. this._getDescendants(results, directDescendantsOnly, predicate);
  10275. return results;
  10276. };
  10277. /**
  10278. * Get all child-meshes of this node.
  10279. */
  10280. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10281. var results = [];
  10282. this._getDescendants(results, directDecendantsOnly, function (node) {
  10283. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10284. });
  10285. return results;
  10286. };
  10287. /**
  10288. * Get all direct children of this node.
  10289. */
  10290. Node.prototype.getChildren = function (predicate) {
  10291. return this.getDescendants(true, predicate);
  10292. };
  10293. Node.prototype._setReady = function (state) {
  10294. if (state === this._isReady) {
  10295. return;
  10296. }
  10297. if (!state) {
  10298. this._isReady = false;
  10299. return;
  10300. }
  10301. this._isReady = true;
  10302. if (this.onReady) {
  10303. this.onReady(this);
  10304. }
  10305. };
  10306. Node.prototype.getAnimationByName = function (name) {
  10307. for (var i = 0; i < this.animations.length; i++) {
  10308. var animation = this.animations[i];
  10309. if (animation.name === name) {
  10310. return animation;
  10311. }
  10312. }
  10313. return null;
  10314. };
  10315. Node.prototype.createAnimationRange = function (name, from, to) {
  10316. // check name not already in use
  10317. if (!this._ranges[name]) {
  10318. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  10319. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10320. if (this.animations[i]) {
  10321. this.animations[i].createRange(name, from, to);
  10322. }
  10323. }
  10324. }
  10325. };
  10326. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  10327. if (deleteFrames === void 0) { deleteFrames = true; }
  10328. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10329. if (this.animations[i]) {
  10330. this.animations[i].deleteRange(name, deleteFrames);
  10331. }
  10332. }
  10333. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  10334. };
  10335. Node.prototype.getAnimationRange = function (name) {
  10336. return this._ranges[name];
  10337. };
  10338. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  10339. var range = this.getAnimationRange(name);
  10340. if (!range) {
  10341. return null;
  10342. }
  10343. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  10344. };
  10345. Node.prototype.serializeAnimationRanges = function () {
  10346. var serializationRanges = [];
  10347. for (var name in this._ranges) {
  10348. var range = {};
  10349. range.name = name;
  10350. range.from = this._ranges[name].from;
  10351. range.to = this._ranges[name].to;
  10352. serializationRanges.push(range);
  10353. }
  10354. return serializationRanges;
  10355. };
  10356. Node.prototype.dispose = function () {
  10357. this.parent = null;
  10358. // Callback
  10359. this.onDisposeObservable.notifyObservers(this);
  10360. this.onDisposeObservable.clear();
  10361. };
  10362. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  10363. if (parsedNode.ranges) {
  10364. for (var index = 0; index < parsedNode.ranges.length; index++) {
  10365. var data = parsedNode.ranges[index];
  10366. node.createAnimationRange(data.name, data.from, data.to);
  10367. }
  10368. }
  10369. };
  10370. return Node;
  10371. }());
  10372. __decorate([
  10373. BABYLON.serialize()
  10374. ], Node.prototype, "name", void 0);
  10375. __decorate([
  10376. BABYLON.serialize()
  10377. ], Node.prototype, "id", void 0);
  10378. __decorate([
  10379. BABYLON.serialize()
  10380. ], Node.prototype, "uniqueId", void 0);
  10381. __decorate([
  10382. BABYLON.serialize()
  10383. ], Node.prototype, "state", void 0);
  10384. __decorate([
  10385. BABYLON.serialize()
  10386. ], Node.prototype, "metadata", void 0);
  10387. BABYLON.Node = Node;
  10388. })(BABYLON || (BABYLON = {}));
  10389. //# sourceMappingURL=babylon.node.js.map
  10390. var BABYLON;
  10391. (function (BABYLON) {
  10392. var BoundingSphere = (function () {
  10393. function BoundingSphere(minimum, maximum) {
  10394. this.minimum = minimum;
  10395. this.maximum = maximum;
  10396. this._tempRadiusVector = BABYLON.Vector3.Zero();
  10397. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  10398. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  10399. this.radius = distance * 0.5;
  10400. this.centerWorld = BABYLON.Vector3.Zero();
  10401. this._update(BABYLON.Matrix.Identity());
  10402. }
  10403. // Methods
  10404. BoundingSphere.prototype._update = function (world) {
  10405. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  10406. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  10407. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  10408. };
  10409. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  10410. for (var i = 0; i < 6; i++) {
  10411. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  10412. return false;
  10413. }
  10414. return true;
  10415. };
  10416. BoundingSphere.prototype.intersectsPoint = function (point) {
  10417. var x = this.centerWorld.x - point.x;
  10418. var y = this.centerWorld.y - point.y;
  10419. var z = this.centerWorld.z - point.z;
  10420. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10421. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  10422. return false;
  10423. return true;
  10424. };
  10425. // Statics
  10426. BoundingSphere.Intersects = function (sphere0, sphere1) {
  10427. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  10428. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  10429. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  10430. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10431. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  10432. return false;
  10433. return true;
  10434. };
  10435. return BoundingSphere;
  10436. }());
  10437. BABYLON.BoundingSphere = BoundingSphere;
  10438. })(BABYLON || (BABYLON = {}));
  10439. //# sourceMappingURL=babylon.boundingSphere.js.map
  10440. var BABYLON;
  10441. (function (BABYLON) {
  10442. var BoundingBox = (function () {
  10443. function BoundingBox(minimum, maximum) {
  10444. this.minimum = minimum;
  10445. this.maximum = maximum;
  10446. this.vectors = new Array();
  10447. this.vectorsWorld = new Array();
  10448. // Bounding vectors
  10449. this.vectors.push(this.minimum.clone());
  10450. this.vectors.push(this.maximum.clone());
  10451. this.vectors.push(this.minimum.clone());
  10452. this.vectors[2].x = this.maximum.x;
  10453. this.vectors.push(this.minimum.clone());
  10454. this.vectors[3].y = this.maximum.y;
  10455. this.vectors.push(this.minimum.clone());
  10456. this.vectors[4].z = this.maximum.z;
  10457. this.vectors.push(this.maximum.clone());
  10458. this.vectors[5].z = this.minimum.z;
  10459. this.vectors.push(this.maximum.clone());
  10460. this.vectors[6].x = this.minimum.x;
  10461. this.vectors.push(this.maximum.clone());
  10462. this.vectors[7].y = this.minimum.y;
  10463. // OBB
  10464. this.center = this.maximum.add(this.minimum).scale(0.5);
  10465. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  10466. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  10467. // World
  10468. for (var index = 0; index < this.vectors.length; index++) {
  10469. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  10470. }
  10471. this.minimumWorld = BABYLON.Vector3.Zero();
  10472. this.maximumWorld = BABYLON.Vector3.Zero();
  10473. this.centerWorld = BABYLON.Vector3.Zero();
  10474. this.extendSizeWorld = BABYLON.Vector3.Zero();
  10475. this._update(BABYLON.Matrix.Identity());
  10476. }
  10477. // Methods
  10478. BoundingBox.prototype.getWorldMatrix = function () {
  10479. return this._worldMatrix;
  10480. };
  10481. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  10482. this._worldMatrix.copyFrom(matrix);
  10483. return this;
  10484. };
  10485. BoundingBox.prototype._update = function (world) {
  10486. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  10487. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  10488. for (var index = 0; index < this.vectors.length; index++) {
  10489. var v = this.vectorsWorld[index];
  10490. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  10491. if (v.x < this.minimumWorld.x)
  10492. this.minimumWorld.x = v.x;
  10493. if (v.y < this.minimumWorld.y)
  10494. this.minimumWorld.y = v.y;
  10495. if (v.z < this.minimumWorld.z)
  10496. this.minimumWorld.z = v.z;
  10497. if (v.x > this.maximumWorld.x)
  10498. this.maximumWorld.x = v.x;
  10499. if (v.y > this.maximumWorld.y)
  10500. this.maximumWorld.y = v.y;
  10501. if (v.z > this.maximumWorld.z)
  10502. this.maximumWorld.z = v.z;
  10503. }
  10504. // Extend
  10505. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  10506. this.extendSizeWorld.scaleInPlace(0.5);
  10507. // OBB
  10508. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  10509. this.centerWorld.scaleInPlace(0.5);
  10510. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  10511. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  10512. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  10513. this._worldMatrix = world;
  10514. };
  10515. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  10516. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  10517. };
  10518. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10519. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  10520. };
  10521. BoundingBox.prototype.intersectsPoint = function (point) {
  10522. var delta = -BABYLON.Epsilon;
  10523. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  10524. return false;
  10525. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  10526. return false;
  10527. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  10528. return false;
  10529. return true;
  10530. };
  10531. BoundingBox.prototype.intersectsSphere = function (sphere) {
  10532. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  10533. };
  10534. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  10535. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  10536. return false;
  10537. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  10538. return false;
  10539. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  10540. return false;
  10541. return true;
  10542. };
  10543. // Statics
  10544. BoundingBox.Intersects = function (box0, box1) {
  10545. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  10546. return false;
  10547. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  10548. return false;
  10549. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  10550. return false;
  10551. return true;
  10552. };
  10553. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  10554. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  10555. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  10556. return (num <= (sphereRadius * sphereRadius));
  10557. };
  10558. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  10559. for (var p = 0; p < 6; p++) {
  10560. for (var i = 0; i < 8; i++) {
  10561. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10562. return false;
  10563. }
  10564. }
  10565. }
  10566. return true;
  10567. };
  10568. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  10569. for (var p = 0; p < 6; p++) {
  10570. var inCount = 8;
  10571. for (var i = 0; i < 8; i++) {
  10572. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10573. --inCount;
  10574. }
  10575. else {
  10576. break;
  10577. }
  10578. }
  10579. if (inCount === 0)
  10580. return false;
  10581. }
  10582. return true;
  10583. };
  10584. return BoundingBox;
  10585. }());
  10586. BABYLON.BoundingBox = BoundingBox;
  10587. })(BABYLON || (BABYLON = {}));
  10588. //# sourceMappingURL=babylon.boundingBox.js.map
  10589. var BABYLON;
  10590. (function (BABYLON) {
  10591. var computeBoxExtents = function (axis, box) {
  10592. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  10593. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  10594. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  10595. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  10596. var r = r0 + r1 + r2;
  10597. return {
  10598. min: p - r,
  10599. max: p + r
  10600. };
  10601. };
  10602. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  10603. var axisOverlap = function (axis, box0, box1) {
  10604. var result0 = computeBoxExtents(axis, box0);
  10605. var result1 = computeBoxExtents(axis, box1);
  10606. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  10607. };
  10608. var BoundingInfo = (function () {
  10609. function BoundingInfo(minimum, maximum) {
  10610. this.minimum = minimum;
  10611. this.maximum = maximum;
  10612. this._isLocked = false;
  10613. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  10614. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  10615. }
  10616. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  10617. get: function () {
  10618. return this._isLocked;
  10619. },
  10620. set: function (value) {
  10621. this._isLocked = value;
  10622. },
  10623. enumerable: true,
  10624. configurable: true
  10625. });
  10626. // Methods
  10627. BoundingInfo.prototype.update = function (world) {
  10628. if (this._isLocked) {
  10629. return;
  10630. }
  10631. this.boundingBox._update(world);
  10632. this.boundingSphere._update(world);
  10633. };
  10634. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  10635. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  10636. return false;
  10637. return this.boundingBox.isInFrustum(frustumPlanes);
  10638. };
  10639. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10640. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  10641. };
  10642. BoundingInfo.prototype._checkCollision = function (collider) {
  10643. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  10644. };
  10645. BoundingInfo.prototype.intersectsPoint = function (point) {
  10646. if (!this.boundingSphere.centerWorld) {
  10647. return false;
  10648. }
  10649. if (!this.boundingSphere.intersectsPoint(point)) {
  10650. return false;
  10651. }
  10652. if (!this.boundingBox.intersectsPoint(point)) {
  10653. return false;
  10654. }
  10655. return true;
  10656. };
  10657. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  10658. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  10659. return false;
  10660. }
  10661. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  10662. return false;
  10663. }
  10664. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  10665. return false;
  10666. }
  10667. if (!precise) {
  10668. return true;
  10669. }
  10670. var box0 = this.boundingBox;
  10671. var box1 = boundingInfo.boundingBox;
  10672. if (!axisOverlap(box0.directions[0], box0, box1))
  10673. return false;
  10674. if (!axisOverlap(box0.directions[1], box0, box1))
  10675. return false;
  10676. if (!axisOverlap(box0.directions[2], box0, box1))
  10677. return false;
  10678. if (!axisOverlap(box1.directions[0], box0, box1))
  10679. return false;
  10680. if (!axisOverlap(box1.directions[1], box0, box1))
  10681. return false;
  10682. if (!axisOverlap(box1.directions[2], box0, box1))
  10683. return false;
  10684. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  10685. return false;
  10686. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  10687. return false;
  10688. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  10689. return false;
  10690. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  10691. return false;
  10692. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  10693. return false;
  10694. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  10695. return false;
  10696. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  10697. return false;
  10698. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  10699. return false;
  10700. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  10701. return false;
  10702. return true;
  10703. };
  10704. return BoundingInfo;
  10705. }());
  10706. BABYLON.BoundingInfo = BoundingInfo;
  10707. })(BABYLON || (BABYLON = {}));
  10708. //# sourceMappingURL=babylon.boundingInfo.js.map
  10709. var BABYLON;
  10710. (function (BABYLON) {
  10711. var AbstractMesh = (function (_super) {
  10712. __extends(AbstractMesh, _super);
  10713. // Constructor
  10714. function AbstractMesh(name, scene) {
  10715. var _this = _super.call(this, name, scene) || this;
  10716. _this._facetNb = 0; // facet number
  10717. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  10718. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  10719. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  10720. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  10721. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  10722. _this._subDiv = {
  10723. max: 1,
  10724. X: 1,
  10725. Y: 1,
  10726. Z: 1
  10727. };
  10728. // Events
  10729. /**
  10730. * An event triggered when this mesh collides with another one
  10731. * @type {BABYLON.Observable}
  10732. */
  10733. _this.onCollideObservable = new BABYLON.Observable();
  10734. /**
  10735. * An event triggered when the collision's position changes
  10736. * @type {BABYLON.Observable}
  10737. */
  10738. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  10739. /**
  10740. * An event triggered after the world matrix is updated
  10741. * @type {BABYLON.Observable}
  10742. */
  10743. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  10744. // Properties
  10745. _this.definedFacingForward = true; // orientation for POV movement & rotation
  10746. _this.position = new BABYLON.Vector3(0.0, 0.0, 0.0);
  10747. _this._rotation = new BABYLON.Vector3(0.0, 0.0, 0.0);
  10748. _this._scaling = new BABYLON.Vector3(1.0, 1.0, 1.0);
  10749. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10750. _this.visibility = 1.0;
  10751. _this.alphaIndex = Number.MAX_VALUE;
  10752. _this.infiniteDistance = false;
  10753. _this.isVisible = true;
  10754. _this.isPickable = true;
  10755. _this.showBoundingBox = false;
  10756. _this.showSubMeshesBoundingBox = false;
  10757. _this.isBlocker = false;
  10758. _this.renderingGroupId = 0;
  10759. _this._receiveShadows = false;
  10760. _this.renderOutline = false;
  10761. _this.outlineColor = BABYLON.Color3.Red();
  10762. _this.outlineWidth = 0.02;
  10763. _this.renderOverlay = false;
  10764. _this.overlayColor = BABYLON.Color3.Red();
  10765. _this.overlayAlpha = 0.5;
  10766. _this._hasVertexAlpha = false;
  10767. _this._useVertexColors = true;
  10768. _this._computeBonesUsingShaders = true;
  10769. _this._numBoneInfluencers = 4;
  10770. _this._applyFog = true;
  10771. _this.scalingDeterminant = 1;
  10772. _this.useOctreeForRenderingSelection = true;
  10773. _this.useOctreeForPicking = true;
  10774. _this.useOctreeForCollisions = true;
  10775. _this.layerMask = 0x0FFFFFFF;
  10776. /**
  10777. * True if the mesh must be rendered in any case.
  10778. */
  10779. _this.alwaysSelectAsActiveMesh = false;
  10780. // Collisions
  10781. _this._checkCollisions = false;
  10782. _this._collisionMask = -1;
  10783. _this._collisionGroup = -1;
  10784. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10785. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10786. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10787. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10788. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10789. // Edges
  10790. _this.edgesWidth = 1;
  10791. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  10792. // Cache
  10793. _this._localWorld = BABYLON.Matrix.Zero();
  10794. _this._worldMatrix = BABYLON.Matrix.Zero();
  10795. _this._absolutePosition = BABYLON.Vector3.Zero();
  10796. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10797. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10798. _this._isDirty = false;
  10799. _this._pivotMatrix = BABYLON.Matrix.Identity();
  10800. _this._isDisposed = false;
  10801. _this._renderId = 0;
  10802. _this._intersectionsInProgress = new Array();
  10803. _this._isWorldMatrixFrozen = false;
  10804. _this._unIndexed = false;
  10805. _this._lightSources = new Array();
  10806. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10807. if (collidedMesh === void 0) { collidedMesh = null; }
  10808. //TODO move this to the collision coordinator!
  10809. if (_this.getScene().workerCollisions)
  10810. newPosition.multiplyInPlace(_this._collider.radius);
  10811. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  10812. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10813. _this.position.addInPlace(_this._diffPositionForCollisions);
  10814. }
  10815. if (collidedMesh) {
  10816. _this.onCollideObservable.notifyObservers(collidedMesh);
  10817. }
  10818. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  10819. };
  10820. _this.getScene().addMesh(_this);
  10821. _this._resyncLightSources();
  10822. return _this;
  10823. }
  10824. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10825. get: function () {
  10826. return AbstractMesh._BILLBOARDMODE_NONE;
  10827. },
  10828. enumerable: true,
  10829. configurable: true
  10830. });
  10831. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10832. get: function () {
  10833. return AbstractMesh._BILLBOARDMODE_X;
  10834. },
  10835. enumerable: true,
  10836. configurable: true
  10837. });
  10838. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10839. get: function () {
  10840. return AbstractMesh._BILLBOARDMODE_Y;
  10841. },
  10842. enumerable: true,
  10843. configurable: true
  10844. });
  10845. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10846. get: function () {
  10847. return AbstractMesh._BILLBOARDMODE_Z;
  10848. },
  10849. enumerable: true,
  10850. configurable: true
  10851. });
  10852. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10853. get: function () {
  10854. return AbstractMesh._BILLBOARDMODE_ALL;
  10855. },
  10856. enumerable: true,
  10857. configurable: true
  10858. });
  10859. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  10860. /**
  10861. * Read-only : the number of facets in the mesh
  10862. */
  10863. get: function () {
  10864. return this._facetNb;
  10865. },
  10866. enumerable: true,
  10867. configurable: true
  10868. });
  10869. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  10870. /**
  10871. * The number (integer) of subdivisions per axis in the partioning space
  10872. */
  10873. get: function () {
  10874. return this._partitioningSubdivisions;
  10875. },
  10876. set: function (nb) {
  10877. this._partitioningSubdivisions = nb;
  10878. },
  10879. enumerable: true,
  10880. configurable: true
  10881. });
  10882. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  10883. /**
  10884. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  10885. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  10886. */
  10887. get: function () {
  10888. return this._partitioningBBoxRatio;
  10889. },
  10890. set: function (ratio) {
  10891. this._partitioningBBoxRatio = ratio;
  10892. },
  10893. enumerable: true,
  10894. configurable: true
  10895. });
  10896. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  10897. /**
  10898. * Read-only boolean : is the feature facetData enabled ?
  10899. */
  10900. get: function () {
  10901. return this._facetDataEnabled;
  10902. },
  10903. enumerable: true,
  10904. configurable: true
  10905. });
  10906. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  10907. set: function (callback) {
  10908. if (this._onCollideObserver) {
  10909. this.onCollideObservable.remove(this._onCollideObserver);
  10910. }
  10911. this._onCollideObserver = this.onCollideObservable.add(callback);
  10912. },
  10913. enumerable: true,
  10914. configurable: true
  10915. });
  10916. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  10917. set: function (callback) {
  10918. if (this._onCollisionPositionChangeObserver) {
  10919. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  10920. }
  10921. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  10922. },
  10923. enumerable: true,
  10924. configurable: true
  10925. });
  10926. Object.defineProperty(AbstractMesh.prototype, "material", {
  10927. get: function () {
  10928. return this._material;
  10929. },
  10930. set: function (value) {
  10931. if (this._material === value) {
  10932. return;
  10933. }
  10934. this._material = value;
  10935. if (!this.subMeshes) {
  10936. return;
  10937. }
  10938. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  10939. var subMesh = _a[_i];
  10940. subMesh.setEffect(null);
  10941. }
  10942. },
  10943. enumerable: true,
  10944. configurable: true
  10945. });
  10946. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  10947. get: function () {
  10948. return this._receiveShadows;
  10949. },
  10950. set: function (value) {
  10951. if (this._receiveShadows === value) {
  10952. return;
  10953. }
  10954. this._receiveShadows = value;
  10955. this._markSubMeshesAsLightDirty();
  10956. },
  10957. enumerable: true,
  10958. configurable: true
  10959. });
  10960. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  10961. get: function () {
  10962. return this._hasVertexAlpha;
  10963. },
  10964. set: function (value) {
  10965. if (this._hasVertexAlpha === value) {
  10966. return;
  10967. }
  10968. this._hasVertexAlpha = value;
  10969. this._markSubMeshesAsAttributesDirty();
  10970. },
  10971. enumerable: true,
  10972. configurable: true
  10973. });
  10974. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  10975. get: function () {
  10976. return this._useVertexColors;
  10977. },
  10978. set: function (value) {
  10979. if (this._useVertexColors === value) {
  10980. return;
  10981. }
  10982. this._useVertexColors = value;
  10983. this._markSubMeshesAsAttributesDirty();
  10984. },
  10985. enumerable: true,
  10986. configurable: true
  10987. });
  10988. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  10989. get: function () {
  10990. return this._computeBonesUsingShaders;
  10991. },
  10992. set: function (value) {
  10993. if (this._computeBonesUsingShaders === value) {
  10994. return;
  10995. }
  10996. this._computeBonesUsingShaders = value;
  10997. this._markSubMeshesAsAttributesDirty();
  10998. },
  10999. enumerable: true,
  11000. configurable: true
  11001. });
  11002. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  11003. get: function () {
  11004. return this._numBoneInfluencers;
  11005. },
  11006. set: function (value) {
  11007. if (this._numBoneInfluencers === value) {
  11008. return;
  11009. }
  11010. this._numBoneInfluencers = value;
  11011. this._markSubMeshesAsAttributesDirty();
  11012. },
  11013. enumerable: true,
  11014. configurable: true
  11015. });
  11016. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  11017. get: function () {
  11018. return this._applyFog;
  11019. },
  11020. set: function (value) {
  11021. if (this._applyFog === value) {
  11022. return;
  11023. }
  11024. this._applyFog = value;
  11025. this._markSubMeshesAsMiscDirty();
  11026. },
  11027. enumerable: true,
  11028. configurable: true
  11029. });
  11030. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  11031. get: function () {
  11032. return this._collisionMask;
  11033. },
  11034. set: function (mask) {
  11035. this._collisionMask = !isNaN(mask) ? mask : -1;
  11036. },
  11037. enumerable: true,
  11038. configurable: true
  11039. });
  11040. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  11041. get: function () {
  11042. return this._collisionGroup;
  11043. },
  11044. set: function (mask) {
  11045. this._collisionGroup = !isNaN(mask) ? mask : -1;
  11046. },
  11047. enumerable: true,
  11048. configurable: true
  11049. });
  11050. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  11051. get: function () {
  11052. return this._skeleton;
  11053. },
  11054. set: function (value) {
  11055. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  11056. this._skeleton._unregisterMeshWithPoseMatrix(this);
  11057. }
  11058. if (value && value.needInitialSkinMatrix) {
  11059. value._registerMeshWithPoseMatrix(this);
  11060. }
  11061. this._skeleton = value;
  11062. if (!this._skeleton) {
  11063. this._bonesTransformMatrices = null;
  11064. }
  11065. this._markSubMeshesAsAttributesDirty();
  11066. },
  11067. enumerable: true,
  11068. configurable: true
  11069. });
  11070. /**
  11071. * Returns the string "AbstractMesh"
  11072. */
  11073. AbstractMesh.prototype.getClassName = function () {
  11074. return "AbstractMesh";
  11075. };
  11076. /**
  11077. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11078. */
  11079. AbstractMesh.prototype.toString = function (fullDetails) {
  11080. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  11081. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  11082. if (this._skeleton) {
  11083. ret += ", skeleton: " + this._skeleton.name;
  11084. }
  11085. if (fullDetails) {
  11086. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  11087. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  11088. }
  11089. return ret;
  11090. };
  11091. AbstractMesh.prototype._resyncLightSources = function () {
  11092. this._lightSources.length = 0;
  11093. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  11094. var light = _a[_i];
  11095. if (!light.isEnabled()) {
  11096. continue;
  11097. }
  11098. if (light.canAffectMesh(this)) {
  11099. this._lightSources.push(light);
  11100. }
  11101. }
  11102. this._markSubMeshesAsLightDirty();
  11103. };
  11104. AbstractMesh.prototype._resyncLighSource = function (light) {
  11105. var isIn = light.isEnabled() && light.canAffectMesh(this);
  11106. var index = this._lightSources.indexOf(light);
  11107. if (index === -1) {
  11108. if (!isIn) {
  11109. return;
  11110. }
  11111. this._lightSources.push(light);
  11112. }
  11113. else {
  11114. if (isIn) {
  11115. return;
  11116. }
  11117. this._lightSources.splice(index, 1);
  11118. }
  11119. this._markSubMeshesAsLightDirty();
  11120. };
  11121. AbstractMesh.prototype._removeLightSource = function (light) {
  11122. var index = this._lightSources.indexOf(light);
  11123. if (index === -1) {
  11124. return;
  11125. }
  11126. this._lightSources.splice(index, 1);
  11127. };
  11128. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  11129. if (!this.subMeshes) {
  11130. return;
  11131. }
  11132. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11133. var subMesh = _a[_i];
  11134. if (subMesh._materialDefines) {
  11135. func(subMesh._materialDefines);
  11136. }
  11137. }
  11138. };
  11139. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  11140. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  11141. };
  11142. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  11143. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  11144. };
  11145. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  11146. if (!this.subMeshes) {
  11147. return;
  11148. }
  11149. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11150. var subMesh = _a[_i];
  11151. var material = subMesh.getMaterial();
  11152. if (material) {
  11153. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  11154. }
  11155. }
  11156. };
  11157. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  11158. /**
  11159. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  11160. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  11161. * Default : (0.0, 0.0, 0.0)
  11162. */
  11163. get: function () {
  11164. return this._rotation;
  11165. },
  11166. set: function (newRotation) {
  11167. this._rotation = newRotation;
  11168. },
  11169. enumerable: true,
  11170. configurable: true
  11171. });
  11172. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  11173. /**
  11174. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  11175. * Default : (1.0, 1.0, 1.0)
  11176. */
  11177. get: function () {
  11178. return this._scaling;
  11179. },
  11180. set: function (newScaling) {
  11181. this._scaling = newScaling;
  11182. if (this.physicsImpostor) {
  11183. this.physicsImpostor.forceUpdate();
  11184. }
  11185. },
  11186. enumerable: true,
  11187. configurable: true
  11188. });
  11189. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  11190. /**
  11191. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  11192. * It's null by default.
  11193. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  11194. */
  11195. get: function () {
  11196. return this._rotationQuaternion;
  11197. },
  11198. set: function (quaternion) {
  11199. this._rotationQuaternion = quaternion;
  11200. //reset the rotation vector.
  11201. if (quaternion && this.rotation.length()) {
  11202. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  11203. }
  11204. },
  11205. enumerable: true,
  11206. configurable: true
  11207. });
  11208. // Methods
  11209. /**
  11210. * Copies the paramater passed Matrix into the mesh Pose matrix.
  11211. * Returns the AbstractMesh.
  11212. */
  11213. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  11214. this._poseMatrix.copyFrom(matrix);
  11215. return this;
  11216. };
  11217. /**
  11218. * Returns the mesh Pose matrix.
  11219. * Returned object : Matrix
  11220. */
  11221. AbstractMesh.prototype.getPoseMatrix = function () {
  11222. return this._poseMatrix;
  11223. };
  11224. /**
  11225. * Disables the mesh edger rendering mode.
  11226. * Returns the AbstractMesh.
  11227. */
  11228. AbstractMesh.prototype.disableEdgesRendering = function () {
  11229. if (this._edgesRenderer !== undefined) {
  11230. this._edgesRenderer.dispose();
  11231. this._edgesRenderer = undefined;
  11232. }
  11233. return this;
  11234. };
  11235. /**
  11236. * Enables the edge rendering mode on the mesh.
  11237. * This mode makes the mesh edges visible.
  11238. * Returns the AbstractMesh.
  11239. */
  11240. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  11241. if (epsilon === void 0) { epsilon = 0.95; }
  11242. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  11243. this.disableEdgesRendering();
  11244. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  11245. return this;
  11246. };
  11247. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  11248. /**
  11249. * Returns true if the mesh is blocked. Used by the class Mesh.
  11250. * Returns the boolean `false` by default.
  11251. */
  11252. get: function () {
  11253. return false;
  11254. },
  11255. enumerable: true,
  11256. configurable: true
  11257. });
  11258. /**
  11259. * Returns the mesh itself by default, used by the class Mesh.
  11260. * Returned type : AbstractMesh
  11261. */
  11262. AbstractMesh.prototype.getLOD = function (camera) {
  11263. return this;
  11264. };
  11265. /**
  11266. * Returns 0 by default, used by the class Mesh.
  11267. * Returns an integer.
  11268. */
  11269. AbstractMesh.prototype.getTotalVertices = function () {
  11270. return 0;
  11271. };
  11272. /**
  11273. * Returns null by default, used by the class Mesh.
  11274. * Returned type : integer array
  11275. */
  11276. AbstractMesh.prototype.getIndices = function () {
  11277. return null;
  11278. };
  11279. /**
  11280. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  11281. * Returned type : float array or Float32Array
  11282. */
  11283. AbstractMesh.prototype.getVerticesData = function (kind) {
  11284. return null;
  11285. };
  11286. /**
  11287. * Sets the vertex data of the mesh geometry for the requested `kind`.
  11288. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  11289. * The `data` are either a numeric array either a Float32Array.
  11290. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  11291. * 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).
  11292. * Note that a new underlying VertexBuffer object is created each call.
  11293. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  11294. *
  11295. * Possible `kind` values :
  11296. * - BABYLON.VertexBuffer.PositionKind
  11297. * - BABYLON.VertexBuffer.UVKind
  11298. * - BABYLON.VertexBuffer.UV2Kind
  11299. * - BABYLON.VertexBuffer.UV3Kind
  11300. * - BABYLON.VertexBuffer.UV4Kind
  11301. * - BABYLON.VertexBuffer.UV5Kind
  11302. * - BABYLON.VertexBuffer.UV6Kind
  11303. * - BABYLON.VertexBuffer.ColorKind
  11304. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11305. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11306. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11307. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11308. *
  11309. * Returns the Mesh.
  11310. */
  11311. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11312. return null;
  11313. };
  11314. /**
  11315. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  11316. * If the mesh has no geometry, it is simply returned as it is.
  11317. * The `data` are either a numeric array either a Float32Array.
  11318. * No new underlying VertexBuffer object is created.
  11319. * 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.
  11320. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  11321. *
  11322. * Possible `kind` values :
  11323. * - BABYLON.VertexBuffer.PositionKind
  11324. * - BABYLON.VertexBuffer.UVKind
  11325. * - BABYLON.VertexBuffer.UV2Kind
  11326. * - BABYLON.VertexBuffer.UV3Kind
  11327. * - BABYLON.VertexBuffer.UV4Kind
  11328. * - BABYLON.VertexBuffer.UV5Kind
  11329. * - BABYLON.VertexBuffer.UV6Kind
  11330. * - BABYLON.VertexBuffer.ColorKind
  11331. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11332. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11333. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11334. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11335. *
  11336. * Returns the Mesh.
  11337. */
  11338. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11339. return null;
  11340. };
  11341. /**
  11342. * Sets the mesh indices.
  11343. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  11344. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  11345. * This method creates a new index buffer each call.
  11346. * Returns the Mesh.
  11347. */
  11348. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  11349. return null;
  11350. };
  11351. /** Returns false by default, used by the class Mesh.
  11352. * Returns a boolean
  11353. */
  11354. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  11355. return false;
  11356. };
  11357. /**
  11358. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  11359. * Returns a BoundingInfo
  11360. */
  11361. AbstractMesh.prototype.getBoundingInfo = function () {
  11362. if (this._masterMesh) {
  11363. return this._masterMesh.getBoundingInfo();
  11364. }
  11365. if (!this._boundingInfo) {
  11366. this._updateBoundingInfo();
  11367. }
  11368. return this._boundingInfo;
  11369. };
  11370. /**
  11371. * Sets a mesh new object BoundingInfo.
  11372. * Returns the AbstractMesh.
  11373. */
  11374. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  11375. this._boundingInfo = boundingInfo;
  11376. return this;
  11377. };
  11378. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  11379. get: function () {
  11380. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  11381. },
  11382. enumerable: true,
  11383. configurable: true
  11384. });
  11385. AbstractMesh.prototype._preActivate = function () {
  11386. };
  11387. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  11388. };
  11389. AbstractMesh.prototype._activate = function (renderId) {
  11390. this._renderId = renderId;
  11391. };
  11392. /**
  11393. * Returns the last update of the World matrix
  11394. * Returns a Matrix.
  11395. */
  11396. AbstractMesh.prototype.getWorldMatrix = function () {
  11397. if (this._masterMesh) {
  11398. return this._masterMesh.getWorldMatrix();
  11399. }
  11400. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  11401. this.computeWorldMatrix();
  11402. }
  11403. return this._worldMatrix;
  11404. };
  11405. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  11406. /**
  11407. * Returns directly the last state of the mesh World matrix.
  11408. * A Matrix is returned.
  11409. */
  11410. get: function () {
  11411. return this._worldMatrix;
  11412. },
  11413. enumerable: true,
  11414. configurable: true
  11415. });
  11416. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  11417. /**
  11418. * Returns the current mesh absolute position.
  11419. * Retuns a Vector3.
  11420. */
  11421. get: function () {
  11422. return this._absolutePosition;
  11423. },
  11424. enumerable: true,
  11425. configurable: true
  11426. });
  11427. /**
  11428. * Prevents the World matrix to be computed any longer.
  11429. * Returns the AbstractMesh.
  11430. */
  11431. AbstractMesh.prototype.freezeWorldMatrix = function () {
  11432. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  11433. this.computeWorldMatrix(true);
  11434. this._isWorldMatrixFrozen = true;
  11435. return this;
  11436. };
  11437. /**
  11438. * Allows back the World matrix computation.
  11439. * Returns the AbstractMesh.
  11440. */
  11441. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  11442. this._isWorldMatrixFrozen = false;
  11443. this.computeWorldMatrix(true);
  11444. return this;
  11445. };
  11446. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  11447. /**
  11448. * True if the World matrix has been frozen.
  11449. * Returns a boolean.
  11450. */
  11451. get: function () {
  11452. return this._isWorldMatrixFrozen;
  11453. },
  11454. enumerable: true,
  11455. configurable: true
  11456. });
  11457. /**
  11458. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  11459. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11460. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  11461. * The passed axis is also normalized.
  11462. * Returns the AbstractMesh.
  11463. */
  11464. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  11465. axis.normalize();
  11466. if (!this.rotationQuaternion) {
  11467. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11468. this.rotation = BABYLON.Vector3.Zero();
  11469. }
  11470. var rotationQuaternion;
  11471. if (!space || space === BABYLON.Space.LOCAL) {
  11472. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11473. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  11474. }
  11475. else {
  11476. if (this.parent) {
  11477. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11478. invertParentWorldMatrix.invert();
  11479. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  11480. }
  11481. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11482. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  11483. }
  11484. return this;
  11485. };
  11486. /**
  11487. * Translates the mesh along the axis vector for the passed distance in the given space.
  11488. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11489. * Returns the AbstractMesh.
  11490. */
  11491. AbstractMesh.prototype.translate = function (axis, distance, space) {
  11492. var displacementVector = axis.scale(distance);
  11493. if (!space || space === BABYLON.Space.LOCAL) {
  11494. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  11495. this.setPositionWithLocalVector(tempV3);
  11496. }
  11497. else {
  11498. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  11499. }
  11500. return this;
  11501. };
  11502. /**
  11503. * Adds a rotation step to the mesh current rotation.
  11504. * x, y, z are Euler angles expressed in radians.
  11505. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  11506. * This means this rotation is made in the mesh local space only.
  11507. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  11508. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  11509. * ```javascript
  11510. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  11511. * ```
  11512. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  11513. * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.
  11514. * Returns the AbstractMesh.
  11515. */
  11516. AbstractMesh.prototype.addRotation = function (x, y, z) {
  11517. var rotationQuaternion;
  11518. if (this.rotationQuaternion) {
  11519. rotationQuaternion = this.rotationQuaternion;
  11520. }
  11521. else {
  11522. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  11523. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  11524. }
  11525. var accumulation = BABYLON.Tmp.Quaternion[0];
  11526. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  11527. rotationQuaternion.multiplyInPlace(accumulation);
  11528. if (!this.rotationQuaternion) {
  11529. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  11530. }
  11531. return this;
  11532. };
  11533. /**
  11534. * Retuns the mesh absolute position in the World.
  11535. * Returns a Vector3.
  11536. */
  11537. AbstractMesh.prototype.getAbsolutePosition = function () {
  11538. this.computeWorldMatrix();
  11539. return this._absolutePosition;
  11540. };
  11541. /**
  11542. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  11543. * Returns the AbstractMesh.
  11544. */
  11545. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  11546. if (!absolutePosition) {
  11547. return;
  11548. }
  11549. var absolutePositionX;
  11550. var absolutePositionY;
  11551. var absolutePositionZ;
  11552. if (absolutePosition.x === undefined) {
  11553. if (arguments.length < 3) {
  11554. return;
  11555. }
  11556. absolutePositionX = arguments[0];
  11557. absolutePositionY = arguments[1];
  11558. absolutePositionZ = arguments[2];
  11559. }
  11560. else {
  11561. absolutePositionX = absolutePosition.x;
  11562. absolutePositionY = absolutePosition.y;
  11563. absolutePositionZ = absolutePosition.z;
  11564. }
  11565. if (this.parent) {
  11566. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11567. invertParentWorldMatrix.invert();
  11568. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  11569. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  11570. }
  11571. else {
  11572. this.position.x = absolutePositionX;
  11573. this.position.y = absolutePositionY;
  11574. this.position.z = absolutePositionZ;
  11575. }
  11576. return this;
  11577. };
  11578. // ================================== Point of View Movement =================================
  11579. /**
  11580. * Perform relative position change from the point of view of behind the front of the mesh.
  11581. * This is performed taking into account the meshes current rotation, so you do not have to care.
  11582. * Supports definition of mesh facing forward or backward.
  11583. * @param {number} amountRight
  11584. * @param {number} amountUp
  11585. * @param {number} amountForward
  11586. *
  11587. * Returns the AbstractMesh.
  11588. */
  11589. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  11590. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  11591. return this;
  11592. };
  11593. /**
  11594. * Calculate relative position change from the point of view of behind the front of the mesh.
  11595. * This is performed taking into account the meshes current rotation, so you do not have to care.
  11596. * Supports definition of mesh facing forward or backward.
  11597. * @param {number} amountRight
  11598. * @param {number} amountUp
  11599. * @param {number} amountForward
  11600. *
  11601. * Returns a new Vector3.
  11602. */
  11603. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  11604. var rotMatrix = new BABYLON.Matrix();
  11605. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11606. rotQuaternion.toRotationMatrix(rotMatrix);
  11607. var translationDelta = BABYLON.Vector3.Zero();
  11608. var defForwardMult = this.definedFacingForward ? -1 : 1;
  11609. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  11610. return translationDelta;
  11611. };
  11612. // ================================== Point of View Rotation =================================
  11613. /**
  11614. * Perform relative rotation change from the point of view of behind the front of the mesh.
  11615. * Supports definition of mesh facing forward or backward.
  11616. * @param {number} flipBack
  11617. * @param {number} twirlClockwise
  11618. * @param {number} tiltRight
  11619. *
  11620. * Returns the AbstractMesh.
  11621. */
  11622. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  11623. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  11624. return this;
  11625. };
  11626. /**
  11627. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  11628. * Supports definition of mesh facing forward or backward.
  11629. * @param {number} flipBack
  11630. * @param {number} twirlClockwise
  11631. * @param {number} tiltRight
  11632. *
  11633. * Returns a new Vector3.
  11634. */
  11635. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  11636. var defForwardMult = this.definedFacingForward ? 1 : -1;
  11637. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  11638. };
  11639. /**
  11640. * Sets a new pivot matrix to the mesh.
  11641. * Returns the AbstractMesh.
  11642. */
  11643. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  11644. this._pivotMatrix = matrix;
  11645. this._cache.pivotMatrixUpdated = true;
  11646. return this;
  11647. };
  11648. /**
  11649. * Returns the mesh pivot matrix.
  11650. * Default : Identity.
  11651. * A Matrix is returned.
  11652. */
  11653. AbstractMesh.prototype.getPivotMatrix = function () {
  11654. return this._pivotMatrix;
  11655. };
  11656. AbstractMesh.prototype._isSynchronized = function () {
  11657. if (this._isDirty) {
  11658. return false;
  11659. }
  11660. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  11661. return false;
  11662. if (this._cache.pivotMatrixUpdated) {
  11663. return false;
  11664. }
  11665. if (this.infiniteDistance) {
  11666. return false;
  11667. }
  11668. if (!this._cache.position.equals(this.position))
  11669. return false;
  11670. if (this.rotationQuaternion) {
  11671. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  11672. return false;
  11673. }
  11674. if (!this._cache.rotation.equals(this.rotation))
  11675. return false;
  11676. if (!this._cache.scaling.equals(this.scaling))
  11677. return false;
  11678. return true;
  11679. };
  11680. AbstractMesh.prototype._initCache = function () {
  11681. _super.prototype._initCache.call(this);
  11682. this._cache.localMatrixUpdated = false;
  11683. this._cache.position = BABYLON.Vector3.Zero();
  11684. this._cache.scaling = BABYLON.Vector3.Zero();
  11685. this._cache.rotation = BABYLON.Vector3.Zero();
  11686. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  11687. this._cache.billboardMode = -1;
  11688. };
  11689. AbstractMesh.prototype.markAsDirty = function (property) {
  11690. if (property === "rotation") {
  11691. this.rotationQuaternion = null;
  11692. }
  11693. this._currentRenderId = Number.MAX_VALUE;
  11694. this._isDirty = true;
  11695. return this;
  11696. };
  11697. /**
  11698. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  11699. * Returns the AbstractMesh.
  11700. */
  11701. AbstractMesh.prototype._updateBoundingInfo = function () {
  11702. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  11703. this._boundingInfo.update(this.worldMatrixFromCache);
  11704. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  11705. return this;
  11706. };
  11707. /**
  11708. * Update a mesh's children BoundingInfo objects only.
  11709. * Returns the AbstractMesh.
  11710. */
  11711. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  11712. if (!this.subMeshes) {
  11713. return;
  11714. }
  11715. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  11716. var subMesh = this.subMeshes[subIndex];
  11717. if (!subMesh.IsGlobal) {
  11718. subMesh.updateBoundingInfo(matrix);
  11719. }
  11720. }
  11721. return this;
  11722. };
  11723. /**
  11724. * Computes the mesh World matrix and returns it.
  11725. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  11726. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  11727. * If the parameter `force`is set to `true`, the actual computation is done.
  11728. * Returns the mesh World Matrix.
  11729. */
  11730. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  11731. if (this._isWorldMatrixFrozen) {
  11732. return this._worldMatrix;
  11733. }
  11734. if (!force && this.isSynchronized(true)) {
  11735. this._currentRenderId = this.getScene().getRenderId();
  11736. return this._worldMatrix;
  11737. }
  11738. this._cache.position.copyFrom(this.position);
  11739. this._cache.scaling.copyFrom(this.scaling);
  11740. this._cache.pivotMatrixUpdated = false;
  11741. this._cache.billboardMode = this.billboardMode;
  11742. this._currentRenderId = this.getScene().getRenderId();
  11743. this._isDirty = false;
  11744. // Scaling
  11745. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  11746. // Rotation
  11747. //rotate, if quaternion is set and rotation was used
  11748. if (this.rotationQuaternion) {
  11749. var len = this.rotation.length();
  11750. if (len) {
  11751. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  11752. this.rotation.copyFromFloats(0, 0, 0);
  11753. }
  11754. }
  11755. if (this.rotationQuaternion) {
  11756. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  11757. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  11758. }
  11759. else {
  11760. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  11761. this._cache.rotation.copyFrom(this.rotation);
  11762. }
  11763. // Translation
  11764. if (this.infiniteDistance && !this.parent) {
  11765. var camera = this.getScene().activeCamera;
  11766. if (camera) {
  11767. var cameraWorldMatrix = camera.getWorldMatrix();
  11768. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  11769. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  11770. }
  11771. }
  11772. else {
  11773. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  11774. }
  11775. // Composing transformations
  11776. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  11777. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  11778. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  11779. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  11780. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  11781. // Need to decompose each rotation here
  11782. var currentPosition = BABYLON.Tmp.Vector3[3];
  11783. if (this.parent && this.parent.getWorldMatrix) {
  11784. if (this._meshToBoneReferal) {
  11785. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11786. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  11787. }
  11788. else {
  11789. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  11790. }
  11791. }
  11792. else {
  11793. currentPosition.copyFrom(this.position);
  11794. }
  11795. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  11796. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  11797. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  11798. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  11799. }
  11800. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  11801. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  11802. }
  11803. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  11804. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  11805. }
  11806. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  11807. }
  11808. else {
  11809. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  11810. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  11811. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  11812. }
  11813. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  11814. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  11815. }
  11816. // Local world
  11817. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  11818. // Parent
  11819. if (this.parent && this.parent.getWorldMatrix) {
  11820. this._markSyncedWithParent();
  11821. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  11822. if (this._meshToBoneReferal) {
  11823. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11824. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  11825. }
  11826. else {
  11827. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  11828. }
  11829. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  11830. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  11831. this._worldMatrix.copyFrom(this._localWorld);
  11832. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  11833. }
  11834. else {
  11835. if (this._meshToBoneReferal) {
  11836. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11837. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  11838. }
  11839. else {
  11840. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  11841. }
  11842. }
  11843. }
  11844. else {
  11845. this._worldMatrix.copyFrom(this._localWorld);
  11846. }
  11847. // Bounding info
  11848. this._updateBoundingInfo();
  11849. // Absolute position
  11850. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  11851. // Callbacks
  11852. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  11853. if (!this._poseMatrix) {
  11854. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  11855. }
  11856. return this._worldMatrix;
  11857. };
  11858. /**
  11859. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  11860. * @param func: callback function to add
  11861. *
  11862. * Returns the AbstractMesh.
  11863. */
  11864. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  11865. this.onAfterWorldMatrixUpdateObservable.add(func);
  11866. return this;
  11867. };
  11868. /**
  11869. * Removes a registered callback function.
  11870. * Returns the AbstractMesh.
  11871. */
  11872. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  11873. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  11874. return this;
  11875. };
  11876. /**
  11877. * Sets the mesh position in its local space.
  11878. * Returns the AbstractMesh.
  11879. */
  11880. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  11881. this.computeWorldMatrix();
  11882. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  11883. return this;
  11884. };
  11885. /**
  11886. * Returns the mesh position in the local space from the current World matrix values.
  11887. * Returns a new Vector3.
  11888. */
  11889. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  11890. this.computeWorldMatrix();
  11891. var invLocalWorldMatrix = this._localWorld.clone();
  11892. invLocalWorldMatrix.invert();
  11893. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  11894. };
  11895. /**
  11896. * Translates the mesh along the passed Vector3 in its local space.
  11897. * Returns the AbstractMesh.
  11898. */
  11899. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  11900. this.computeWorldMatrix(true);
  11901. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  11902. return this;
  11903. };
  11904. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  11905. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  11906. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  11907. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  11908. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  11909. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  11910. /// <returns>Mesh oriented towards targetMesh</returns>
  11911. if (yawCor === void 0) { yawCor = 0; }
  11912. if (pitchCor === void 0) { pitchCor = 0; }
  11913. if (rollCor === void 0) { rollCor = 0; }
  11914. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  11915. var dv = AbstractMesh._lookAtVectorCache;
  11916. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  11917. targetPoint.subtractToRef(pos, dv);
  11918. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  11919. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  11920. var pitch = Math.atan2(dv.y, len);
  11921. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  11922. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  11923. return this;
  11924. };
  11925. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  11926. this._meshToBoneReferal = affectedMesh;
  11927. this.parent = bone;
  11928. if (bone.getWorldMatrix().determinant() < 0) {
  11929. this.scalingDeterminant *= -1;
  11930. }
  11931. return this;
  11932. };
  11933. AbstractMesh.prototype.detachFromBone = function () {
  11934. if (this.parent.getWorldMatrix().determinant() < 0) {
  11935. this.scalingDeterminant *= -1;
  11936. }
  11937. this._meshToBoneReferal = null;
  11938. this.parent = null;
  11939. return this;
  11940. };
  11941. /**
  11942. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  11943. * A mesh is in the frustum if its bounding box intersects the frustum.
  11944. * Boolean returned.
  11945. */
  11946. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  11947. return this._boundingInfo.isInFrustum(frustumPlanes);
  11948. };
  11949. /**
  11950. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  11951. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  11952. * Boolean returned.
  11953. */
  11954. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11955. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  11956. ;
  11957. };
  11958. /**
  11959. * True if the mesh intersects another mesh or a SolidParticle object.
  11960. * Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  11961. * Returns a boolean.
  11962. */
  11963. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  11964. if (!this._boundingInfo || !mesh._boundingInfo) {
  11965. return false;
  11966. }
  11967. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  11968. };
  11969. /**
  11970. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  11971. * Returns a boolean.
  11972. */
  11973. AbstractMesh.prototype.intersectsPoint = function (point) {
  11974. if (!this._boundingInfo) {
  11975. return false;
  11976. }
  11977. return this._boundingInfo.intersectsPoint(point);
  11978. };
  11979. AbstractMesh.prototype.getPhysicsImpostor = function () {
  11980. return this.physicsImpostor;
  11981. };
  11982. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  11983. if (!camera) {
  11984. camera = this.getScene().activeCamera;
  11985. }
  11986. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  11987. };
  11988. /**
  11989. * Returns the distance from the mesh to the active camera.
  11990. * Returns a float.
  11991. */
  11992. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  11993. if (!camera) {
  11994. camera = this.getScene().activeCamera;
  11995. }
  11996. return this.absolutePosition.subtract(camera.position).length();
  11997. };
  11998. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  11999. if (!this.physicsImpostor) {
  12000. return;
  12001. }
  12002. this.physicsImpostor.applyImpulse(force, contactPoint);
  12003. return this;
  12004. };
  12005. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  12006. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  12007. return;
  12008. }
  12009. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  12010. mainPivot: pivot1,
  12011. connectedPivot: pivot2,
  12012. nativeParams: options
  12013. });
  12014. return this;
  12015. };
  12016. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  12017. // Collisions
  12018. /**
  12019. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  12020. * Default `false`.
  12021. */
  12022. get: function () {
  12023. return this._checkCollisions;
  12024. },
  12025. set: function (collisionEnabled) {
  12026. this._checkCollisions = collisionEnabled;
  12027. if (this.getScene().workerCollisions) {
  12028. this.getScene().collisionCoordinator.onMeshUpdated(this);
  12029. }
  12030. },
  12031. enumerable: true,
  12032. configurable: true
  12033. });
  12034. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  12035. var globalPosition = this.getAbsolutePosition();
  12036. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  12037. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  12038. if (!this._collider) {
  12039. this._collider = new BABYLON.Collider();
  12040. }
  12041. this._collider.radius = this.ellipsoid;
  12042. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  12043. return this;
  12044. };
  12045. // Submeshes octree
  12046. /**
  12047. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  12048. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  12049. * Returns an Octree of submeshes.
  12050. */
  12051. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  12052. if (maxCapacity === void 0) { maxCapacity = 64; }
  12053. if (maxDepth === void 0) { maxDepth = 2; }
  12054. if (!this._submeshesOctree) {
  12055. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  12056. }
  12057. this.computeWorldMatrix(true);
  12058. // Update octree
  12059. var bbox = this.getBoundingInfo().boundingBox;
  12060. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  12061. return this._submeshesOctree;
  12062. };
  12063. // Collisions
  12064. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  12065. this._generatePointsArray();
  12066. // Transformation
  12067. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  12068. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  12069. subMesh._lastColliderWorldVertices = [];
  12070. subMesh._trianglePlanes = [];
  12071. var start = subMesh.verticesStart;
  12072. var end = (subMesh.verticesStart + subMesh.verticesCount);
  12073. for (var i = start; i < end; i++) {
  12074. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  12075. }
  12076. }
  12077. // Collide
  12078. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  12079. if (collider.collisionFound) {
  12080. collider.collidedMesh = this;
  12081. }
  12082. return this;
  12083. };
  12084. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  12085. var subMeshes;
  12086. var len;
  12087. // Octrees
  12088. if (this._submeshesOctree && this.useOctreeForCollisions) {
  12089. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  12090. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  12091. len = intersections.length;
  12092. subMeshes = intersections.data;
  12093. }
  12094. else {
  12095. subMeshes = this.subMeshes;
  12096. len = subMeshes.length;
  12097. }
  12098. for (var index = 0; index < len; index++) {
  12099. var subMesh = subMeshes[index];
  12100. // Bounding test
  12101. if (len > 1 && !subMesh._checkCollision(collider))
  12102. continue;
  12103. this._collideForSubMesh(subMesh, transformMatrix, collider);
  12104. }
  12105. return this;
  12106. };
  12107. AbstractMesh.prototype._checkCollision = function (collider) {
  12108. // Bounding box test
  12109. if (!this._boundingInfo._checkCollision(collider))
  12110. return this;
  12111. // Transformation matrix
  12112. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  12113. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  12114. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  12115. return this;
  12116. };
  12117. // Picking
  12118. AbstractMesh.prototype._generatePointsArray = function () {
  12119. return false;
  12120. };
  12121. /**
  12122. * Checks if the passed Ray intersects with the mesh.
  12123. * Returns an object PickingInfo.
  12124. */
  12125. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  12126. var pickingInfo = new BABYLON.PickingInfo();
  12127. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  12128. return pickingInfo;
  12129. }
  12130. if (!this._generatePointsArray()) {
  12131. return pickingInfo;
  12132. }
  12133. var intersectInfo = null;
  12134. // Octrees
  12135. var subMeshes;
  12136. var len;
  12137. if (this._submeshesOctree && this.useOctreeForPicking) {
  12138. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  12139. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  12140. len = intersections.length;
  12141. subMeshes = intersections.data;
  12142. }
  12143. else {
  12144. subMeshes = this.subMeshes;
  12145. len = subMeshes.length;
  12146. }
  12147. for (var index = 0; index < len; index++) {
  12148. var subMesh = subMeshes[index];
  12149. // Bounding test
  12150. if (len > 1 && !subMesh.canIntersects(ray))
  12151. continue;
  12152. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  12153. if (currentIntersectInfo) {
  12154. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12155. intersectInfo = currentIntersectInfo;
  12156. intersectInfo.subMeshId = index;
  12157. if (fastCheck) {
  12158. break;
  12159. }
  12160. }
  12161. }
  12162. }
  12163. if (intersectInfo) {
  12164. // Get picked point
  12165. var world = this.getWorldMatrix();
  12166. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  12167. var direction = ray.direction.clone();
  12168. direction = direction.scale(intersectInfo.distance);
  12169. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  12170. var pickedPoint = worldOrigin.add(worldDirection);
  12171. // Return result
  12172. pickingInfo.hit = true;
  12173. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  12174. pickingInfo.pickedPoint = pickedPoint;
  12175. pickingInfo.pickedMesh = this;
  12176. pickingInfo.bu = intersectInfo.bu;
  12177. pickingInfo.bv = intersectInfo.bv;
  12178. pickingInfo.faceId = intersectInfo.faceId;
  12179. pickingInfo.subMeshId = intersectInfo.subMeshId;
  12180. return pickingInfo;
  12181. }
  12182. return pickingInfo;
  12183. };
  12184. /**
  12185. * Clones the mesh, used by the class Mesh.
  12186. * Just returns `null` for an AbstractMesh.
  12187. */
  12188. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12189. return null;
  12190. };
  12191. /**
  12192. * Disposes all the mesh submeshes.
  12193. * Returns the AbstractMesh.
  12194. */
  12195. AbstractMesh.prototype.releaseSubMeshes = function () {
  12196. if (this.subMeshes) {
  12197. while (this.subMeshes.length) {
  12198. this.subMeshes[0].dispose();
  12199. }
  12200. }
  12201. else {
  12202. this.subMeshes = new Array();
  12203. }
  12204. return this;
  12205. };
  12206. /**
  12207. * Disposes the AbstractMesh.
  12208. * Some internal references are kept for further use.
  12209. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  12210. * Returns nothing.
  12211. */
  12212. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  12213. var _this = this;
  12214. var index;
  12215. // Action manager
  12216. if (this.actionManager) {
  12217. this.actionManager.dispose();
  12218. this.actionManager = null;
  12219. }
  12220. // Skeleton
  12221. this.skeleton = null;
  12222. // Animations
  12223. this.getScene().stopAnimation(this);
  12224. // Physics
  12225. if (this.physicsImpostor) {
  12226. this.physicsImpostor.dispose();
  12227. }
  12228. // Intersections in progress
  12229. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  12230. var other = this._intersectionsInProgress[index];
  12231. var pos = other._intersectionsInProgress.indexOf(this);
  12232. other._intersectionsInProgress.splice(pos, 1);
  12233. }
  12234. this._intersectionsInProgress = [];
  12235. // Lights
  12236. var lights = this.getScene().lights;
  12237. lights.forEach(function (light) {
  12238. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  12239. if (meshIndex !== -1) {
  12240. light.includedOnlyMeshes.splice(meshIndex, 1);
  12241. }
  12242. meshIndex = light.excludedMeshes.indexOf(_this);
  12243. if (meshIndex !== -1) {
  12244. light.excludedMeshes.splice(meshIndex, 1);
  12245. }
  12246. // Shadow generators
  12247. var generator = light.getShadowGenerator();
  12248. if (generator) {
  12249. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  12250. if (meshIndex !== -1) {
  12251. generator.getShadowMap().renderList.splice(meshIndex, 1);
  12252. }
  12253. }
  12254. });
  12255. // Edges
  12256. if (this._edgesRenderer) {
  12257. this._edgesRenderer.dispose();
  12258. this._edgesRenderer = null;
  12259. }
  12260. // SubMeshes
  12261. if (this.getClassName() !== "InstancedMesh") {
  12262. this.releaseSubMeshes();
  12263. }
  12264. // Octree
  12265. var sceneOctree = this.getScene().selectionOctree;
  12266. if (sceneOctree) {
  12267. var index = sceneOctree.dynamicContent.indexOf(this);
  12268. if (index !== -1) {
  12269. sceneOctree.dynamicContent.splice(index, 1);
  12270. }
  12271. }
  12272. // Engine
  12273. this.getScene().getEngine().wipeCaches();
  12274. // Remove from scene
  12275. this.getScene().removeMesh(this);
  12276. if (!doNotRecurse) {
  12277. // Particles
  12278. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  12279. if (this.getScene().particleSystems[index].emitter === this) {
  12280. this.getScene().particleSystems[index].dispose();
  12281. index--;
  12282. }
  12283. }
  12284. // Children
  12285. var objects = this.getDescendants(true);
  12286. for (index = 0; index < objects.length; index++) {
  12287. objects[index].dispose();
  12288. }
  12289. }
  12290. else {
  12291. var childMeshes = this.getChildMeshes(true);
  12292. for (index = 0; index < childMeshes.length; index++) {
  12293. var child = childMeshes[index];
  12294. child.parent = null;
  12295. child.computeWorldMatrix(true);
  12296. }
  12297. }
  12298. // facet data
  12299. if (this._facetDataEnabled) {
  12300. this.disableFacetData();
  12301. }
  12302. this.onAfterWorldMatrixUpdateObservable.clear();
  12303. this.onCollideObservable.clear();
  12304. this.onCollisionPositionChangeObservable.clear();
  12305. this._isDisposed = true;
  12306. _super.prototype.dispose.call(this);
  12307. };
  12308. /**
  12309. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  12310. * This Vector3 is expressed in the World space.
  12311. */
  12312. AbstractMesh.prototype.getDirection = function (localAxis) {
  12313. var result = BABYLON.Vector3.Zero();
  12314. this.getDirectionToRef(localAxis, result);
  12315. return result;
  12316. };
  12317. /**
  12318. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  12319. * localAxis is expressed in the mesh local space.
  12320. * result is computed in the Wordl space from the mesh World matrix.
  12321. * Returns the AbstractMesh.
  12322. */
  12323. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  12324. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  12325. return this;
  12326. };
  12327. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  12328. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12329. if (this.getScene().getRenderId() == 0) {
  12330. this.computeWorldMatrix(true);
  12331. }
  12332. var wm = this.getWorldMatrix();
  12333. if (space == BABYLON.Space.WORLD) {
  12334. var tmat = BABYLON.Tmp.Matrix[0];
  12335. wm.invertToRef(tmat);
  12336. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  12337. }
  12338. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  12339. this._pivotMatrix.m[12] = -point.x;
  12340. this._pivotMatrix.m[13] = -point.y;
  12341. this._pivotMatrix.m[14] = -point.z;
  12342. this._cache.pivotMatrixUpdated = true;
  12343. return this;
  12344. };
  12345. /**
  12346. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  12347. */
  12348. AbstractMesh.prototype.getPivotPoint = function () {
  12349. var point = BABYLON.Vector3.Zero();
  12350. this.getPivotPointToRef(point);
  12351. return point;
  12352. };
  12353. /**
  12354. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  12355. * Returns the AbstractMesh.
  12356. */
  12357. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  12358. result.x = -this._pivotMatrix.m[12];
  12359. result.y = -this._pivotMatrix.m[13];
  12360. result.z = -this._pivotMatrix.m[14];
  12361. return this;
  12362. };
  12363. /**
  12364. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  12365. */
  12366. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  12367. var point = BABYLON.Vector3.Zero();
  12368. this.getAbsolutePivotPointToRef(point);
  12369. return point;
  12370. };
  12371. /**
  12372. * Defines the passed mesh as the parent of the current mesh.
  12373. * Returns the AbstractMesh.
  12374. */
  12375. AbstractMesh.prototype.setParent = function (mesh) {
  12376. var child = this;
  12377. var parent = mesh;
  12378. if (mesh == null) {
  12379. var rotation = BABYLON.Tmp.Quaternion[0];
  12380. var position = BABYLON.Tmp.Vector3[0];
  12381. var scale = BABYLON.Tmp.Vector3[1];
  12382. child.getWorldMatrix().decompose(scale, rotation, position);
  12383. if (child.rotationQuaternion) {
  12384. child.rotationQuaternion.copyFrom(rotation);
  12385. }
  12386. else {
  12387. rotation.toEulerAnglesToRef(child.rotation);
  12388. }
  12389. child.position.x = position.x;
  12390. child.position.y = position.y;
  12391. child.position.z = position.z;
  12392. }
  12393. else {
  12394. var rotation = BABYLON.Tmp.Quaternion[0];
  12395. var position = BABYLON.Tmp.Vector3[0];
  12396. var scale = BABYLON.Tmp.Vector3[1];
  12397. var m1 = BABYLON.Tmp.Matrix[0];
  12398. var m2 = BABYLON.Tmp.Matrix[1];
  12399. parent.getWorldMatrix().decompose(scale, rotation, position);
  12400. rotation.toRotationMatrix(m1);
  12401. m2.setTranslation(position);
  12402. m2.multiplyToRef(m1, m1);
  12403. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  12404. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12405. m.decompose(scale, rotation, position);
  12406. if (child.rotationQuaternion) {
  12407. child.rotationQuaternion.copyFrom(rotation);
  12408. }
  12409. else {
  12410. rotation.toEulerAnglesToRef(child.rotation);
  12411. }
  12412. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  12413. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12414. m.decompose(scale, rotation, position);
  12415. child.position.x = position.x;
  12416. child.position.y = position.y;
  12417. child.position.z = position.z;
  12418. }
  12419. child.parent = parent;
  12420. return this;
  12421. };
  12422. /**
  12423. * Adds the passed mesh as a child to the current mesh.
  12424. * Returns the AbstractMesh.
  12425. */
  12426. AbstractMesh.prototype.addChild = function (mesh) {
  12427. mesh.setParent(this);
  12428. return this;
  12429. };
  12430. /**
  12431. * Removes the passed mesh from the current mesh children list.
  12432. * Returns the AbstractMesh.
  12433. */
  12434. AbstractMesh.prototype.removeChild = function (mesh) {
  12435. mesh.setParent(null);
  12436. return this;
  12437. };
  12438. /**
  12439. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  12440. * Returns the AbstractMesh.
  12441. */
  12442. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  12443. result.x = this._pivotMatrix.m[12];
  12444. result.y = this._pivotMatrix.m[13];
  12445. result.z = this._pivotMatrix.m[14];
  12446. this.getPivotPointToRef(result);
  12447. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  12448. return this;
  12449. };
  12450. // Facet data
  12451. /**
  12452. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  12453. * Returns the AbstractMesh.
  12454. */
  12455. AbstractMesh.prototype._initFacetData = function () {
  12456. if (!this._facetNormals) {
  12457. this._facetNormals = new Array();
  12458. }
  12459. if (!this._facetPositions) {
  12460. this._facetPositions = new Array();
  12461. }
  12462. if (!this._facetPartitioning) {
  12463. this._facetPartitioning = new Array();
  12464. }
  12465. this._facetNb = this.getIndices().length / 3;
  12466. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  12467. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  12468. for (var f = 0; f < this._facetNb; f++) {
  12469. this._facetNormals[f] = BABYLON.Vector3.Zero();
  12470. this._facetPositions[f] = BABYLON.Vector3.Zero();
  12471. }
  12472. this._facetDataEnabled = true;
  12473. return this;
  12474. };
  12475. /**
  12476. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  12477. * This method can be called within the render loop.
  12478. * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation.
  12479. * Returns the AbstractMesh.
  12480. */
  12481. AbstractMesh.prototype.updateFacetData = function () {
  12482. if (!this._facetDataEnabled) {
  12483. this._initFacetData();
  12484. }
  12485. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12486. var indices = this.getIndices();
  12487. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12488. var bInfo = this.getBoundingInfo();
  12489. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  12490. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  12491. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  12492. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  12493. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  12494. this._subDiv.max = this._partitioningSubdivisions;
  12495. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  12496. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  12497. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  12498. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  12499. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  12500. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  12501. // set the parameters for ComputeNormals()
  12502. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  12503. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  12504. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  12505. this._facetParameters.bInfo = bInfo;
  12506. this._facetParameters.bbSize = this._bbSize;
  12507. this._facetParameters.subDiv = this._subDiv;
  12508. this._facetParameters.ratio = this.partitioningBBoxRatio;
  12509. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  12510. return this;
  12511. };
  12512. /**
  12513. * Returns the facetLocalNormals array.
  12514. * The normals are expressed in the mesh local space.
  12515. */
  12516. AbstractMesh.prototype.getFacetLocalNormals = function () {
  12517. if (!this._facetNormals) {
  12518. this.updateFacetData();
  12519. }
  12520. return this._facetNormals;
  12521. };
  12522. /**
  12523. * Returns the facetLocalPositions array.
  12524. * The facet positions are expressed in the mesh local space.
  12525. */
  12526. AbstractMesh.prototype.getFacetLocalPositions = function () {
  12527. if (!this._facetPositions) {
  12528. this.updateFacetData();
  12529. }
  12530. return this._facetPositions;
  12531. };
  12532. /**
  12533. * Returns the facetLocalPartioning array.
  12534. */
  12535. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  12536. if (!this._facetPartitioning) {
  12537. this.updateFacetData();
  12538. }
  12539. return this._facetPartitioning;
  12540. };
  12541. /**
  12542. * Returns the i-th facet position in the world system.
  12543. * This method allocates a new Vector3 per call.
  12544. */
  12545. AbstractMesh.prototype.getFacetPosition = function (i) {
  12546. var pos = BABYLON.Vector3.Zero();
  12547. this.getFacetPositionToRef(i, pos);
  12548. return pos;
  12549. };
  12550. /**
  12551. * Sets the reference Vector3 with the i-th facet position in the world system.
  12552. * Returns the AbstractMesh.
  12553. */
  12554. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  12555. var localPos = (this.getFacetLocalPositions())[i];
  12556. var world = this.getWorldMatrix();
  12557. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  12558. return this;
  12559. };
  12560. /**
  12561. * Returns the i-th facet normal in the world system.
  12562. * This method allocates a new Vector3 per call.
  12563. */
  12564. AbstractMesh.prototype.getFacetNormal = function (i) {
  12565. var norm = BABYLON.Vector3.Zero();
  12566. this.getFacetNormalToRef(i, norm);
  12567. return norm;
  12568. };
  12569. /**
  12570. * Sets the reference Vector3 with the i-th facet normal in the world system.
  12571. * Returns the AbstractMesh.
  12572. */
  12573. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  12574. var localNorm = (this.getFacetLocalNormals())[i];
  12575. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  12576. return this;
  12577. };
  12578. /**
  12579. * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system).
  12580. */
  12581. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  12582. var bInfo = this.getBoundingInfo();
  12583. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  12584. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  12585. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  12586. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  12587. return null;
  12588. }
  12589. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  12590. };
  12591. /**
  12592. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  12593. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  12594. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  12595. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  12596. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  12597. */
  12598. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  12599. if (checkFace === void 0) { checkFace = false; }
  12600. if (facing === void 0) { facing = true; }
  12601. var world = this.getWorldMatrix();
  12602. var invMat = BABYLON.Tmp.Matrix[5];
  12603. world.invertToRef(invMat);
  12604. var invVect = BABYLON.Tmp.Vector3[8];
  12605. var closest = null;
  12606. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  12607. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  12608. if (projected) {
  12609. // tranform the local computed projected vector to world coordinates
  12610. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  12611. }
  12612. return closest;
  12613. };
  12614. /**
  12615. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  12616. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  12617. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  12618. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  12619. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  12620. */
  12621. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  12622. if (checkFace === void 0) { checkFace = false; }
  12623. if (facing === void 0) { facing = true; }
  12624. var closest = null;
  12625. var tmpx = 0.0;
  12626. var tmpy = 0.0;
  12627. var tmpz = 0.0;
  12628. var d = 0.0; // tmp dot facet normal * facet position
  12629. var t0 = 0.0;
  12630. var projx = 0.0;
  12631. var projy = 0.0;
  12632. var projz = 0.0;
  12633. // Get all the facets in the same partitioning block than (x, y, z)
  12634. var facetPositions = this.getFacetLocalPositions();
  12635. var facetNormals = this.getFacetLocalNormals();
  12636. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  12637. if (!facetsInBlock) {
  12638. return null;
  12639. }
  12640. // Get the closest facet to (x, y, z)
  12641. var shortest = Number.MAX_VALUE; // init distance vars
  12642. var tmpDistance = shortest;
  12643. var fib; // current facet in the block
  12644. var norm; // current facet normal
  12645. var p0; // current facet barycenter position
  12646. // loop on all the facets in the current partitioning block
  12647. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  12648. fib = facetsInBlock[idx];
  12649. norm = facetNormals[fib];
  12650. p0 = facetPositions[fib];
  12651. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  12652. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  12653. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  12654. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  12655. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  12656. projx = x + norm.x * t0;
  12657. projy = y + norm.y * t0;
  12658. projz = z + norm.z * t0;
  12659. tmpx = projx - x;
  12660. tmpy = projy - y;
  12661. tmpz = projz - z;
  12662. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  12663. if (tmpDistance < shortest) {
  12664. shortest = tmpDistance;
  12665. closest = fib;
  12666. if (projected) {
  12667. projected.x = projx;
  12668. projected.y = projy;
  12669. projected.z = projz;
  12670. }
  12671. }
  12672. }
  12673. }
  12674. return closest;
  12675. };
  12676. /**
  12677. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  12678. */
  12679. AbstractMesh.prototype.getFacetDataParameters = function () {
  12680. return this._facetParameters;
  12681. };
  12682. /**
  12683. * Disables the feature FacetData and frees the related memory.
  12684. * Returns the AbstractMesh.
  12685. */
  12686. AbstractMesh.prototype.disableFacetData = function () {
  12687. if (this._facetDataEnabled) {
  12688. this._facetDataEnabled = false;
  12689. this._facetPositions = null;
  12690. this._facetNormals = null;
  12691. this._facetPartitioning = null;
  12692. this._facetParameters = null;
  12693. }
  12694. return this;
  12695. };
  12696. /**
  12697. * Creates new normals data for the mesh.
  12698. * @param updatable.
  12699. */
  12700. AbstractMesh.prototype.createNormals = function (updatable) {
  12701. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12702. var indices = this.getIndices();
  12703. var normals;
  12704. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  12705. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12706. }
  12707. else {
  12708. normals = [];
  12709. }
  12710. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  12711. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  12712. };
  12713. return AbstractMesh;
  12714. }(BABYLON.Node));
  12715. // Statics
  12716. AbstractMesh._BILLBOARDMODE_NONE = 0;
  12717. AbstractMesh._BILLBOARDMODE_X = 1;
  12718. AbstractMesh._BILLBOARDMODE_Y = 2;
  12719. AbstractMesh._BILLBOARDMODE_Z = 4;
  12720. AbstractMesh._BILLBOARDMODE_ALL = 7;
  12721. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  12722. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  12723. BABYLON.AbstractMesh = AbstractMesh;
  12724. })(BABYLON || (BABYLON = {}));
  12725. //# sourceMappingURL=babylon.abstractMesh.js.map
  12726. var BABYLON;
  12727. (function (BABYLON) {
  12728. var Light = (function (_super) {
  12729. __extends(Light, _super);
  12730. /**
  12731. * Creates a Light object in the scene.
  12732. * Documentation : http://doc.babylonjs.com/tutorials/lights
  12733. */
  12734. function Light(name, scene) {
  12735. var _this = _super.call(this, name, scene) || this;
  12736. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  12737. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  12738. _this.intensity = 1.0;
  12739. _this.range = Number.MAX_VALUE;
  12740. _this._excludeWithLayerMask = 0;
  12741. _this._includeOnlyWithLayerMask = 0;
  12742. _this._lightmapMode = 0;
  12743. // PBR Properties.
  12744. _this.radius = 0.00001;
  12745. _this._excludedMeshesIds = new Array();
  12746. _this._includedOnlyMeshesIds = new Array();
  12747. _this.getScene().addLight(_this);
  12748. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  12749. _this._buildUniformLayout();
  12750. _this.includedOnlyMeshes = new Array();
  12751. _this.excludedMeshes = new Array();
  12752. _this._resyncMeshes();
  12753. return _this;
  12754. }
  12755. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  12756. /**
  12757. * If every light affecting the material is in this lightmapMode,
  12758. * material.lightmapTexture adds or multiplies
  12759. * (depends on material.useLightmapAsShadowmap)
  12760. * after every other light calculations.
  12761. */
  12762. get: function () {
  12763. return Light._LIGHTMAP_DEFAULT;
  12764. },
  12765. enumerable: true,
  12766. configurable: true
  12767. });
  12768. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  12769. /**
  12770. * material.lightmapTexture as only diffuse lighting from this light
  12771. * adds pnly specular lighting from this light
  12772. * adds dynamic shadows
  12773. */
  12774. get: function () {
  12775. return Light._LIGHTMAP_SPECULAR;
  12776. },
  12777. enumerable: true,
  12778. configurable: true
  12779. });
  12780. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  12781. /**
  12782. * material.lightmapTexture as only lighting
  12783. * no light calculation from this light
  12784. * only adds dynamic shadows from this light
  12785. */
  12786. get: function () {
  12787. return Light._LIGHTMAP_SHADOWSONLY;
  12788. },
  12789. enumerable: true,
  12790. configurable: true
  12791. });
  12792. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  12793. get: function () {
  12794. return this._includedOnlyMeshes;
  12795. },
  12796. set: function (value) {
  12797. this._includedOnlyMeshes = value;
  12798. this._hookArrayForIncludedOnly(value);
  12799. },
  12800. enumerable: true,
  12801. configurable: true
  12802. });
  12803. Object.defineProperty(Light.prototype, "excludedMeshes", {
  12804. get: function () {
  12805. return this._excludedMeshes;
  12806. },
  12807. set: function (value) {
  12808. this._excludedMeshes = value;
  12809. this._hookArrayForExcluded(value);
  12810. },
  12811. enumerable: true,
  12812. configurable: true
  12813. });
  12814. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  12815. get: function () {
  12816. return this._excludeWithLayerMask;
  12817. },
  12818. set: function (value) {
  12819. this._excludeWithLayerMask = value;
  12820. this._resyncMeshes();
  12821. },
  12822. enumerable: true,
  12823. configurable: true
  12824. });
  12825. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  12826. get: function () {
  12827. return this._includeOnlyWithLayerMask;
  12828. },
  12829. set: function (value) {
  12830. this._includeOnlyWithLayerMask = value;
  12831. this._resyncMeshes();
  12832. },
  12833. enumerable: true,
  12834. configurable: true
  12835. });
  12836. Object.defineProperty(Light.prototype, "lightmapMode", {
  12837. get: function () {
  12838. return this._lightmapMode;
  12839. },
  12840. set: function (value) {
  12841. if (this._lightmapMode === value) {
  12842. return;
  12843. }
  12844. this._lightmapMode = value;
  12845. this._markMeshesAsLightDirty();
  12846. },
  12847. enumerable: true,
  12848. configurable: true
  12849. });
  12850. Light.prototype._buildUniformLayout = function () {
  12851. // Overridden
  12852. };
  12853. /**
  12854. * Returns the string "Light".
  12855. */
  12856. Light.prototype.getClassName = function () {
  12857. return "Light";
  12858. };
  12859. /**
  12860. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12861. */
  12862. Light.prototype.toString = function (fullDetails) {
  12863. var ret = "Name: " + this.name;
  12864. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  12865. if (this.animations) {
  12866. for (var i = 0; i < this.animations.length; i++) {
  12867. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  12868. }
  12869. }
  12870. if (fullDetails) {
  12871. }
  12872. return ret;
  12873. };
  12874. /**
  12875. * Set the enabled state of this node.
  12876. * @param {boolean} value - the new enabled state
  12877. * @see isEnabled
  12878. */
  12879. Light.prototype.setEnabled = function (value) {
  12880. _super.prototype.setEnabled.call(this, value);
  12881. this._resyncMeshes();
  12882. };
  12883. /**
  12884. * Returns the Light associated shadow generator.
  12885. */
  12886. Light.prototype.getShadowGenerator = function () {
  12887. return this._shadowGenerator;
  12888. };
  12889. /**
  12890. * Returns a Vector3, the absolute light position in the World.
  12891. */
  12892. Light.prototype.getAbsolutePosition = function () {
  12893. return BABYLON.Vector3.Zero();
  12894. };
  12895. Light.prototype.transferToEffect = function (effect, lightIndex) {
  12896. };
  12897. Light.prototype._getWorldMatrix = function () {
  12898. return BABYLON.Matrix.Identity();
  12899. };
  12900. /**
  12901. * Boolean : True if the light will affect the passed mesh.
  12902. */
  12903. Light.prototype.canAffectMesh = function (mesh) {
  12904. if (!mesh) {
  12905. return true;
  12906. }
  12907. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  12908. return false;
  12909. }
  12910. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  12911. return false;
  12912. }
  12913. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  12914. return false;
  12915. }
  12916. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  12917. return false;
  12918. }
  12919. return true;
  12920. };
  12921. /**
  12922. * Returns the light World matrix.
  12923. */
  12924. Light.prototype.getWorldMatrix = function () {
  12925. this._currentRenderId = this.getScene().getRenderId();
  12926. var worldMatrix = this._getWorldMatrix();
  12927. if (this.parent && this.parent.getWorldMatrix) {
  12928. if (!this._parentedWorldMatrix) {
  12929. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  12930. }
  12931. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  12932. this._markSyncedWithParent();
  12933. return this._parentedWorldMatrix;
  12934. }
  12935. return worldMatrix;
  12936. };
  12937. /**
  12938. * Disposes the light.
  12939. */
  12940. Light.prototype.dispose = function () {
  12941. if (this._shadowGenerator) {
  12942. this._shadowGenerator.dispose();
  12943. this._shadowGenerator = null;
  12944. }
  12945. // Animations
  12946. this.getScene().stopAnimation(this);
  12947. // Remove from meshes
  12948. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  12949. var mesh = _a[_i];
  12950. mesh._removeLightSource(this);
  12951. }
  12952. this._uniformBuffer.dispose();
  12953. // Remove from scene
  12954. this.getScene().removeLight(this);
  12955. _super.prototype.dispose.call(this);
  12956. };
  12957. /**
  12958. * Returns the light type ID (integer).
  12959. */
  12960. Light.prototype.getTypeID = function () {
  12961. return 0;
  12962. };
  12963. /**
  12964. * Returns a new Light object, named "name", from the current one.
  12965. */
  12966. Light.prototype.clone = function (name) {
  12967. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  12968. };
  12969. /**
  12970. * Serializes the current light into a Serialization object.
  12971. * Returns the serialized object.
  12972. */
  12973. Light.prototype.serialize = function () {
  12974. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  12975. // Type
  12976. serializationObject.type = this.getTypeID();
  12977. // Parent
  12978. if (this.parent) {
  12979. serializationObject.parentId = this.parent.id;
  12980. }
  12981. // Inclusion / exclusions
  12982. if (this.excludedMeshes.length > 0) {
  12983. serializationObject.excludedMeshesIds = [];
  12984. this.excludedMeshes.forEach(function (mesh) {
  12985. serializationObject.excludedMeshesIds.push(mesh.id);
  12986. });
  12987. }
  12988. if (this.includedOnlyMeshes.length > 0) {
  12989. serializationObject.includedOnlyMeshesIds = [];
  12990. this.includedOnlyMeshes.forEach(function (mesh) {
  12991. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  12992. });
  12993. }
  12994. // Animations
  12995. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  12996. serializationObject.ranges = this.serializeAnimationRanges();
  12997. return serializationObject;
  12998. };
  12999. /**
  13000. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  13001. * This new light is named "name" and added to the passed scene.
  13002. */
  13003. Light.GetConstructorFromName = function (type, name, scene) {
  13004. switch (type) {
  13005. case 0:
  13006. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  13007. case 1:
  13008. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  13009. case 2:
  13010. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  13011. case 3:
  13012. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  13013. }
  13014. };
  13015. /**
  13016. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  13017. */
  13018. Light.Parse = function (parsedLight, scene) {
  13019. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  13020. // Inclusion / exclusions
  13021. if (parsedLight.excludedMeshesIds) {
  13022. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  13023. }
  13024. if (parsedLight.includedOnlyMeshesIds) {
  13025. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  13026. }
  13027. // Parent
  13028. if (parsedLight.parentId) {
  13029. light._waitingParentId = parsedLight.parentId;
  13030. }
  13031. // Animations
  13032. if (parsedLight.animations) {
  13033. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  13034. var parsedAnimation = parsedLight.animations[animationIndex];
  13035. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13036. }
  13037. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  13038. }
  13039. if (parsedLight.autoAnimate) {
  13040. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  13041. }
  13042. return light;
  13043. };
  13044. Light.prototype._hookArrayForExcluded = function (array) {
  13045. var _this = this;
  13046. var oldPush = array.push;
  13047. array.push = function () {
  13048. var items = [];
  13049. for (var _i = 0; _i < arguments.length; _i++) {
  13050. items[_i] = arguments[_i];
  13051. }
  13052. var result = oldPush.apply(array, items);
  13053. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  13054. var item = items_1[_a];
  13055. item._resyncLighSource(_this);
  13056. }
  13057. return result;
  13058. };
  13059. var oldSplice = array.splice;
  13060. array.splice = function (index, deleteCount) {
  13061. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13062. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  13063. var item = deleted_1[_i];
  13064. item._resyncLighSource(_this);
  13065. }
  13066. return deleted;
  13067. };
  13068. };
  13069. Light.prototype._hookArrayForIncludedOnly = function (array) {
  13070. var _this = this;
  13071. var oldPush = array.push;
  13072. array.push = function () {
  13073. var items = [];
  13074. for (var _i = 0; _i < arguments.length; _i++) {
  13075. items[_i] = arguments[_i];
  13076. }
  13077. var result = oldPush.apply(array, items);
  13078. _this._resyncMeshes();
  13079. return result;
  13080. };
  13081. var oldSplice = array.splice;
  13082. array.splice = function (index, deleteCount) {
  13083. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13084. _this._resyncMeshes();
  13085. return deleted;
  13086. };
  13087. };
  13088. Light.prototype._resyncMeshes = function () {
  13089. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13090. var mesh = _a[_i];
  13091. mesh._resyncLighSource(this);
  13092. }
  13093. };
  13094. Light.prototype._markMeshesAsLightDirty = function () {
  13095. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13096. var mesh = _a[_i];
  13097. if (mesh._lightSources.indexOf(this) !== -1) {
  13098. mesh._markSubMeshesAsLightDirty();
  13099. }
  13100. }
  13101. };
  13102. return Light;
  13103. }(BABYLON.Node));
  13104. //lightmapMode Consts
  13105. Light._LIGHTMAP_DEFAULT = 0;
  13106. Light._LIGHTMAP_SPECULAR = 1;
  13107. Light._LIGHTMAP_SHADOWSONLY = 2;
  13108. __decorate([
  13109. BABYLON.serializeAsColor3()
  13110. ], Light.prototype, "diffuse", void 0);
  13111. __decorate([
  13112. BABYLON.serializeAsColor3()
  13113. ], Light.prototype, "specular", void 0);
  13114. __decorate([
  13115. BABYLON.serialize()
  13116. ], Light.prototype, "intensity", void 0);
  13117. __decorate([
  13118. BABYLON.serialize()
  13119. ], Light.prototype, "range", void 0);
  13120. __decorate([
  13121. BABYLON.serialize("excludeWithLayerMask")
  13122. ], Light.prototype, "_excludeWithLayerMask", void 0);
  13123. __decorate([
  13124. BABYLON.serialize("includeOnlyWithLayerMask")
  13125. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  13126. __decorate([
  13127. BABYLON.serialize("lightmapMode")
  13128. ], Light.prototype, "_lightmapMode", void 0);
  13129. __decorate([
  13130. BABYLON.serialize()
  13131. ], Light.prototype, "radius", void 0);
  13132. BABYLON.Light = Light;
  13133. })(BABYLON || (BABYLON = {}));
  13134. //# sourceMappingURL=babylon.light.js.map
  13135. var BABYLON;
  13136. (function (BABYLON) {
  13137. var Camera = (function (_super) {
  13138. __extends(Camera, _super);
  13139. function Camera(name, position, scene) {
  13140. var _this = _super.call(this, name, scene) || this;
  13141. _this.upVector = BABYLON.Vector3.Up();
  13142. _this.orthoLeft = null;
  13143. _this.orthoRight = null;
  13144. _this.orthoBottom = null;
  13145. _this.orthoTop = null;
  13146. _this.fov = 0.8;
  13147. _this.minZ = 1.0;
  13148. _this.maxZ = 10000.0;
  13149. _this.inertia = 0.9;
  13150. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13151. _this.isIntermediate = false;
  13152. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13153. _this.layerMask = 0x0FFFFFFF;
  13154. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13155. // Camera rig members
  13156. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13157. _this._rigCameras = new Array();
  13158. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13159. // Cache
  13160. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13161. _this._projectionMatrix = new BABYLON.Matrix();
  13162. _this._doNotComputeProjectionMatrix = false;
  13163. _this._postProcesses = new Array();
  13164. _this._transformMatrix = BABYLON.Matrix.Zero();
  13165. _this._activeMeshes = new BABYLON.SmartArray(256);
  13166. _this._globalPosition = BABYLON.Vector3.Zero();
  13167. _this._refreshFrustumPlanes = true;
  13168. _this.getScene().addCamera(_this);
  13169. if (!_this.getScene().activeCamera) {
  13170. _this.getScene().activeCamera = _this;
  13171. }
  13172. _this.position = position;
  13173. return _this;
  13174. }
  13175. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13176. get: function () {
  13177. return Camera._PERSPECTIVE_CAMERA;
  13178. },
  13179. enumerable: true,
  13180. configurable: true
  13181. });
  13182. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13183. get: function () {
  13184. return Camera._ORTHOGRAPHIC_CAMERA;
  13185. },
  13186. enumerable: true,
  13187. configurable: true
  13188. });
  13189. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13190. get: function () {
  13191. return Camera._FOVMODE_VERTICAL_FIXED;
  13192. },
  13193. enumerable: true,
  13194. configurable: true
  13195. });
  13196. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13197. get: function () {
  13198. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13199. },
  13200. enumerable: true,
  13201. configurable: true
  13202. });
  13203. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13204. get: function () {
  13205. return Camera._RIG_MODE_NONE;
  13206. },
  13207. enumerable: true,
  13208. configurable: true
  13209. });
  13210. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13211. get: function () {
  13212. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13213. },
  13214. enumerable: true,
  13215. configurable: true
  13216. });
  13217. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13218. get: function () {
  13219. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13220. },
  13221. enumerable: true,
  13222. configurable: true
  13223. });
  13224. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  13225. get: function () {
  13226. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13227. },
  13228. enumerable: true,
  13229. configurable: true
  13230. });
  13231. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  13232. get: function () {
  13233. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  13234. },
  13235. enumerable: true,
  13236. configurable: true
  13237. });
  13238. Object.defineProperty(Camera, "RIG_MODE_VR", {
  13239. get: function () {
  13240. return Camera._RIG_MODE_VR;
  13241. },
  13242. enumerable: true,
  13243. configurable: true
  13244. });
  13245. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  13246. get: function () {
  13247. return Camera._RIG_MODE_WEBVR;
  13248. },
  13249. enumerable: true,
  13250. configurable: true
  13251. });
  13252. Camera.prototype.getClassName = function () {
  13253. return "Camera";
  13254. };
  13255. /**
  13256. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13257. */
  13258. Camera.prototype.toString = function (fullDetails) {
  13259. var ret = "Name: " + this.name;
  13260. ret += ", type: " + this.getClassName();
  13261. if (this.animations) {
  13262. for (var i = 0; i < this.animations.length; i++) {
  13263. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13264. }
  13265. }
  13266. if (fullDetails) {
  13267. }
  13268. return ret;
  13269. };
  13270. Object.defineProperty(Camera.prototype, "globalPosition", {
  13271. get: function () {
  13272. return this._globalPosition;
  13273. },
  13274. enumerable: true,
  13275. configurable: true
  13276. });
  13277. Camera.prototype.getActiveMeshes = function () {
  13278. return this._activeMeshes;
  13279. };
  13280. Camera.prototype.isActiveMesh = function (mesh) {
  13281. return (this._activeMeshes.indexOf(mesh) !== -1);
  13282. };
  13283. //Cache
  13284. Camera.prototype._initCache = function () {
  13285. _super.prototype._initCache.call(this);
  13286. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13287. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13288. this._cache.mode = undefined;
  13289. this._cache.minZ = undefined;
  13290. this._cache.maxZ = undefined;
  13291. this._cache.fov = undefined;
  13292. this._cache.fovMode = undefined;
  13293. this._cache.aspectRatio = undefined;
  13294. this._cache.orthoLeft = undefined;
  13295. this._cache.orthoRight = undefined;
  13296. this._cache.orthoBottom = undefined;
  13297. this._cache.orthoTop = undefined;
  13298. this._cache.renderWidth = undefined;
  13299. this._cache.renderHeight = undefined;
  13300. };
  13301. Camera.prototype._updateCache = function (ignoreParentClass) {
  13302. if (!ignoreParentClass) {
  13303. _super.prototype._updateCache.call(this);
  13304. }
  13305. var engine = this.getEngine();
  13306. this._cache.position.copyFrom(this.position);
  13307. this._cache.upVector.copyFrom(this.upVector);
  13308. this._cache.mode = this.mode;
  13309. this._cache.minZ = this.minZ;
  13310. this._cache.maxZ = this.maxZ;
  13311. this._cache.fov = this.fov;
  13312. this._cache.fovMode = this.fovMode;
  13313. this._cache.aspectRatio = engine.getAspectRatio(this);
  13314. this._cache.orthoLeft = this.orthoLeft;
  13315. this._cache.orthoRight = this.orthoRight;
  13316. this._cache.orthoBottom = this.orthoBottom;
  13317. this._cache.orthoTop = this.orthoTop;
  13318. this._cache.renderWidth = engine.getRenderWidth();
  13319. this._cache.renderHeight = engine.getRenderHeight();
  13320. };
  13321. Camera.prototype._updateFromScene = function () {
  13322. this.updateCache();
  13323. this.update();
  13324. };
  13325. // Synchronized
  13326. Camera.prototype._isSynchronized = function () {
  13327. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  13328. };
  13329. Camera.prototype._isSynchronizedViewMatrix = function () {
  13330. if (!_super.prototype._isSynchronized.call(this))
  13331. return false;
  13332. return this._cache.position.equals(this.position)
  13333. && this._cache.upVector.equals(this.upVector)
  13334. && this.isSynchronizedWithParent();
  13335. };
  13336. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  13337. var check = this._cache.mode === this.mode
  13338. && this._cache.minZ === this.minZ
  13339. && this._cache.maxZ === this.maxZ;
  13340. if (!check) {
  13341. return false;
  13342. }
  13343. var engine = this.getEngine();
  13344. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13345. check = this._cache.fov === this.fov
  13346. && this._cache.fovMode === this.fovMode
  13347. && this._cache.aspectRatio === engine.getAspectRatio(this);
  13348. }
  13349. else {
  13350. check = this._cache.orthoLeft === this.orthoLeft
  13351. && this._cache.orthoRight === this.orthoRight
  13352. && this._cache.orthoBottom === this.orthoBottom
  13353. && this._cache.orthoTop === this.orthoTop
  13354. && this._cache.renderWidth === engine.getRenderWidth()
  13355. && this._cache.renderHeight === engine.getRenderHeight();
  13356. }
  13357. return check;
  13358. };
  13359. // Controls
  13360. Camera.prototype.attachControl = function (element, noPreventDefault) {
  13361. };
  13362. Camera.prototype.detachControl = function (element) {
  13363. };
  13364. Camera.prototype.update = function () {
  13365. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13366. this._updateRigCameras();
  13367. }
  13368. this._checkInputs();
  13369. };
  13370. Camera.prototype._checkInputs = function () {
  13371. };
  13372. Object.defineProperty(Camera.prototype, "rigCameras", {
  13373. get: function () {
  13374. return this._rigCameras;
  13375. },
  13376. enumerable: true,
  13377. configurable: true
  13378. });
  13379. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  13380. get: function () {
  13381. return this._rigPostProcess;
  13382. },
  13383. enumerable: true,
  13384. configurable: true
  13385. });
  13386. Camera.prototype._cascadePostProcessesToRigCams = function () {
  13387. // invalidate framebuffer
  13388. if (this._postProcesses.length > 0) {
  13389. this._postProcesses[0].markTextureDirty();
  13390. }
  13391. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  13392. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  13393. var cam = this._rigCameras[i];
  13394. var rigPostProcess = cam._rigPostProcess;
  13395. // for VR rig, there does not have to be a post process
  13396. if (rigPostProcess) {
  13397. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  13398. if (isPass) {
  13399. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  13400. cam.isIntermediate = this._postProcesses.length === 0;
  13401. }
  13402. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  13403. rigPostProcess.markTextureDirty();
  13404. }
  13405. else {
  13406. cam._postProcesses = this._postProcesses.slice(0);
  13407. }
  13408. }
  13409. };
  13410. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  13411. if (insertAt === void 0) { insertAt = null; }
  13412. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  13413. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  13414. return 0;
  13415. }
  13416. if (insertAt == null || insertAt < 0) {
  13417. this._postProcesses.push(postProcess);
  13418. }
  13419. else {
  13420. this._postProcesses.splice(insertAt, 0, postProcess);
  13421. }
  13422. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13423. return this._postProcesses.indexOf(postProcess);
  13424. };
  13425. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  13426. if (atIndices === void 0) { atIndices = null; }
  13427. var result = [];
  13428. var i;
  13429. var index;
  13430. if (!atIndices) {
  13431. var idx = this._postProcesses.indexOf(postProcess);
  13432. if (idx !== -1) {
  13433. this._postProcesses.splice(idx, 1);
  13434. }
  13435. }
  13436. else {
  13437. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  13438. // iterate descending, so can just splice as we go
  13439. for (i = atIndices.length - 1; i >= 0; i--) {
  13440. if (this._postProcesses[atIndices[i]] !== postProcess) {
  13441. result.push(i);
  13442. continue;
  13443. }
  13444. index = atIndices[i];
  13445. this._postProcesses.splice(index, 1);
  13446. }
  13447. }
  13448. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13449. return result;
  13450. };
  13451. Camera.prototype.getWorldMatrix = function () {
  13452. if (!this._worldMatrix) {
  13453. this._worldMatrix = BABYLON.Matrix.Identity();
  13454. }
  13455. var viewMatrix = this.getViewMatrix();
  13456. viewMatrix.invertToRef(this._worldMatrix);
  13457. return this._worldMatrix;
  13458. };
  13459. Camera.prototype._getViewMatrix = function () {
  13460. return BABYLON.Matrix.Identity();
  13461. };
  13462. Camera.prototype.getViewMatrix = function (force) {
  13463. this._computedViewMatrix = this._computeViewMatrix(force);
  13464. if (!force && this._isSynchronizedViewMatrix()) {
  13465. return this._computedViewMatrix;
  13466. }
  13467. this._refreshFrustumPlanes = true;
  13468. if (!this.parent || !this.parent.getWorldMatrix) {
  13469. this._globalPosition.copyFrom(this.position);
  13470. }
  13471. else {
  13472. if (!this._worldMatrix) {
  13473. this._worldMatrix = BABYLON.Matrix.Identity();
  13474. }
  13475. this._computedViewMatrix.invertToRef(this._worldMatrix);
  13476. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  13477. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  13478. this._computedViewMatrix.invert();
  13479. this._markSyncedWithParent();
  13480. }
  13481. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  13482. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  13483. }
  13484. this._currentRenderId = this.getScene().getRenderId();
  13485. return this._computedViewMatrix;
  13486. };
  13487. Camera.prototype._computeViewMatrix = function (force) {
  13488. if (!force && this._isSynchronizedViewMatrix()) {
  13489. return this._computedViewMatrix;
  13490. }
  13491. this._computedViewMatrix = this._getViewMatrix();
  13492. this._currentRenderId = this.getScene().getRenderId();
  13493. return this._computedViewMatrix;
  13494. };
  13495. Camera.prototype.freezeProjectionMatrix = function (projection) {
  13496. this._doNotComputeProjectionMatrix = true;
  13497. if (projection !== undefined) {
  13498. this._projectionMatrix = projection;
  13499. }
  13500. };
  13501. ;
  13502. Camera.prototype.unfreezeProjectionMatrix = function () {
  13503. this._doNotComputeProjectionMatrix = false;
  13504. };
  13505. ;
  13506. Camera.prototype.getProjectionMatrix = function (force) {
  13507. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  13508. return this._projectionMatrix;
  13509. }
  13510. this._refreshFrustumPlanes = true;
  13511. var engine = this.getEngine();
  13512. var scene = this.getScene();
  13513. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13514. if (this.minZ <= 0) {
  13515. this.minZ = 0.1;
  13516. }
  13517. if (scene.useRightHandedSystem) {
  13518. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13519. }
  13520. else {
  13521. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13522. }
  13523. return this._projectionMatrix;
  13524. }
  13525. var halfWidth = engine.getRenderWidth() / 2.0;
  13526. var halfHeight = engine.getRenderHeight() / 2.0;
  13527. if (scene.useRightHandedSystem) {
  13528. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13529. }
  13530. else {
  13531. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13532. }
  13533. return this._projectionMatrix;
  13534. };
  13535. Camera.prototype.getTranformationMatrix = function () {
  13536. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13537. return this._transformMatrix;
  13538. };
  13539. Camera.prototype.updateFrustumPlanes = function () {
  13540. if (!this._refreshFrustumPlanes) {
  13541. return;
  13542. }
  13543. this.getTranformationMatrix();
  13544. if (!this._frustumPlanes) {
  13545. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13546. }
  13547. else {
  13548. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13549. }
  13550. this._refreshFrustumPlanes = false;
  13551. };
  13552. Camera.prototype.isInFrustum = function (target) {
  13553. this.updateFrustumPlanes();
  13554. return target.isInFrustum(this._frustumPlanes);
  13555. };
  13556. Camera.prototype.isCompletelyInFrustum = function (target) {
  13557. this.updateFrustumPlanes();
  13558. return target.isCompletelyInFrustum(this._frustumPlanes);
  13559. };
  13560. Camera.prototype.getForwardRay = function (length, transform, origin) {
  13561. if (length === void 0) { length = 100; }
  13562. if (!transform) {
  13563. transform = this.getWorldMatrix();
  13564. }
  13565. if (!origin) {
  13566. origin = this.position;
  13567. }
  13568. var forward = new BABYLON.Vector3(0, 0, 1);
  13569. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  13570. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  13571. return new BABYLON.Ray(origin, direction, length);
  13572. };
  13573. Camera.prototype.dispose = function () {
  13574. // Animations
  13575. this.getScene().stopAnimation(this);
  13576. // Remove from scene
  13577. this.getScene().removeCamera(this);
  13578. while (this._rigCameras.length > 0) {
  13579. this._rigCameras.pop().dispose();
  13580. }
  13581. // Postprocesses
  13582. var i = this._postProcesses.length;
  13583. while (--i >= 0) {
  13584. this._postProcesses[i].dispose(this);
  13585. }
  13586. _super.prototype.dispose.call(this);
  13587. };
  13588. Object.defineProperty(Camera.prototype, "leftCamera", {
  13589. // ---- Camera rigs section ----
  13590. get: function () {
  13591. if (this._rigCameras.length < 1) {
  13592. return undefined;
  13593. }
  13594. return this._rigCameras[0];
  13595. },
  13596. enumerable: true,
  13597. configurable: true
  13598. });
  13599. Object.defineProperty(Camera.prototype, "rightCamera", {
  13600. get: function () {
  13601. if (this._rigCameras.length < 2) {
  13602. return undefined;
  13603. }
  13604. return this._rigCameras[1];
  13605. },
  13606. enumerable: true,
  13607. configurable: true
  13608. });
  13609. Camera.prototype.getLeftTarget = function () {
  13610. if (this._rigCameras.length < 1) {
  13611. return undefined;
  13612. }
  13613. return this._rigCameras[0].getTarget();
  13614. };
  13615. Camera.prototype.getRightTarget = function () {
  13616. if (this._rigCameras.length < 2) {
  13617. return undefined;
  13618. }
  13619. return this._rigCameras[1].getTarget();
  13620. };
  13621. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  13622. while (this._rigCameras.length > 0) {
  13623. this._rigCameras.pop().dispose();
  13624. }
  13625. this.cameraRigMode = mode;
  13626. this._cameraRigParams = {};
  13627. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  13628. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  13629. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  13630. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  13631. // create the rig cameras, unless none
  13632. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13633. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  13634. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  13635. }
  13636. switch (this.cameraRigMode) {
  13637. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13638. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13639. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  13640. break;
  13641. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13642. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13643. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13644. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13645. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13646. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  13647. break;
  13648. case Camera.RIG_MODE_VR:
  13649. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  13650. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  13651. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13652. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13653. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  13654. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  13655. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  13656. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  13657. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13658. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13659. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  13660. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  13661. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  13662. if (metrics.compensateDistortion) {
  13663. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  13664. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  13665. }
  13666. break;
  13667. case Camera.RIG_MODE_WEBVR:
  13668. if (rigParams.vrDisplay) {
  13669. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  13670. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  13671. //Left eye
  13672. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13673. this._rigCameras[0].setCameraRigParameter("left", true);
  13674. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  13675. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  13676. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  13677. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  13678. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13679. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13680. this._rigCameras[0].parent = this;
  13681. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  13682. //Right eye
  13683. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13684. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  13685. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  13686. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  13687. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  13688. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13689. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13690. this._rigCameras[1].parent = this;
  13691. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  13692. }
  13693. break;
  13694. }
  13695. this._cascadePostProcessesToRigCams();
  13696. this.
  13697. update();
  13698. };
  13699. Camera.prototype._getVRProjectionMatrix = function () {
  13700. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  13701. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  13702. return this._projectionMatrix;
  13703. };
  13704. Camera.prototype._updateCameraRotationMatrix = function () {
  13705. //Here for WebVR
  13706. };
  13707. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  13708. //Here for WebVR
  13709. };
  13710. /**
  13711. * This function MUST be overwritten by the different WebVR cameras available.
  13712. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  13713. */
  13714. Camera.prototype._getWebVRProjectionMatrix = function () {
  13715. return BABYLON.Matrix.Identity();
  13716. };
  13717. /**
  13718. * This function MUST be overwritten by the different WebVR cameras available.
  13719. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  13720. */
  13721. Camera.prototype._getWebVRViewMatrix = function () {
  13722. return BABYLON.Matrix.Identity();
  13723. };
  13724. Camera.prototype.setCameraRigParameter = function (name, value) {
  13725. if (!this._cameraRigParams) {
  13726. this._cameraRigParams = {};
  13727. }
  13728. this._cameraRigParams[name] = value;
  13729. //provisionnally:
  13730. if (name === "interaxialDistance") {
  13731. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  13732. }
  13733. };
  13734. /**
  13735. * needs to be overridden by children so sub has required properties to be copied
  13736. */
  13737. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  13738. return null;
  13739. };
  13740. /**
  13741. * May need to be overridden by children
  13742. */
  13743. Camera.prototype._updateRigCameras = function () {
  13744. for (var i = 0; i < this._rigCameras.length; i++) {
  13745. this._rigCameras[i].minZ = this.minZ;
  13746. this._rigCameras[i].maxZ = this.maxZ;
  13747. this._rigCameras[i].fov = this.fov;
  13748. }
  13749. // only update viewport when ANAGLYPH
  13750. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  13751. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  13752. }
  13753. };
  13754. Camera.prototype._setupInputs = function () {
  13755. };
  13756. Camera.prototype.serialize = function () {
  13757. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13758. // Type
  13759. serializationObject.type = this.getClassName();
  13760. // Parent
  13761. if (this.parent) {
  13762. serializationObject.parentId = this.parent.id;
  13763. }
  13764. if (this.inputs) {
  13765. this.inputs.serialize(serializationObject);
  13766. }
  13767. // Animations
  13768. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13769. serializationObject.ranges = this.serializeAnimationRanges();
  13770. return serializationObject;
  13771. };
  13772. Camera.prototype.clone = function (name) {
  13773. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  13774. };
  13775. Camera.prototype.getDirection = function (localAxis) {
  13776. var result = BABYLON.Vector3.Zero();
  13777. this.getDirectionToRef(localAxis, result);
  13778. return result;
  13779. };
  13780. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  13781. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13782. };
  13783. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  13784. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  13785. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  13786. switch (type) {
  13787. case "ArcRotateCamera":
  13788. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  13789. case "DeviceOrientationCamera":
  13790. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  13791. case "FollowCamera":
  13792. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  13793. case "ArcFollowCamera":
  13794. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  13795. case "GamepadCamera":
  13796. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13797. case "TouchCamera":
  13798. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  13799. case "VirtualJoysticksCamera":
  13800. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  13801. case "WebVRFreeCamera":
  13802. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13803. case "WebVRGamepadCamera":
  13804. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13805. case "VRDeviceOrientationFreeCamera":
  13806. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13807. case "VRDeviceOrientationGamepadCamera":
  13808. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13809. case "AnaglyphArcRotateCamera":
  13810. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13811. case "AnaglyphFreeCamera":
  13812. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13813. case "AnaglyphGamepadCamera":
  13814. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13815. case "AnaglyphUniversalCamera":
  13816. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13817. case "StereoscopicArcRotateCamera":
  13818. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13819. case "StereoscopicFreeCamera":
  13820. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13821. case "StereoscopicGamepadCamera":
  13822. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13823. case "StereoscopicUniversalCamera":
  13824. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13825. case "FreeCamera":
  13826. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13827. default:
  13828. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13829. }
  13830. };
  13831. Camera.Parse = function (parsedCamera, scene) {
  13832. var type = parsedCamera.type;
  13833. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  13834. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  13835. // Parent
  13836. if (parsedCamera.parentId) {
  13837. camera._waitingParentId = parsedCamera.parentId;
  13838. }
  13839. //If camera has an input manager, let it parse inputs settings
  13840. if (camera.inputs) {
  13841. camera.inputs.parse(parsedCamera);
  13842. camera._setupInputs();
  13843. }
  13844. // Target
  13845. if (parsedCamera.target) {
  13846. if (camera.setTarget) {
  13847. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  13848. }
  13849. }
  13850. // Apply 3d rig, when found
  13851. if (parsedCamera.cameraRigMode) {
  13852. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  13853. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  13854. }
  13855. // Animations
  13856. if (parsedCamera.animations) {
  13857. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  13858. var parsedAnimation = parsedCamera.animations[animationIndex];
  13859. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13860. }
  13861. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  13862. }
  13863. if (parsedCamera.autoAnimate) {
  13864. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  13865. }
  13866. return camera;
  13867. };
  13868. return Camera;
  13869. }(BABYLON.Node));
  13870. // Statics
  13871. Camera._PERSPECTIVE_CAMERA = 0;
  13872. Camera._ORTHOGRAPHIC_CAMERA = 1;
  13873. Camera._FOVMODE_VERTICAL_FIXED = 0;
  13874. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  13875. Camera._RIG_MODE_NONE = 0;
  13876. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  13877. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  13878. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  13879. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  13880. Camera._RIG_MODE_VR = 20;
  13881. Camera._RIG_MODE_WEBVR = 21;
  13882. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  13883. __decorate([
  13884. BABYLON.serializeAsVector3()
  13885. ], Camera.prototype, "position", void 0);
  13886. __decorate([
  13887. BABYLON.serializeAsVector3()
  13888. ], Camera.prototype, "upVector", void 0);
  13889. __decorate([
  13890. BABYLON.serialize()
  13891. ], Camera.prototype, "orthoLeft", void 0);
  13892. __decorate([
  13893. BABYLON.serialize()
  13894. ], Camera.prototype, "orthoRight", void 0);
  13895. __decorate([
  13896. BABYLON.serialize()
  13897. ], Camera.prototype, "orthoBottom", void 0);
  13898. __decorate([
  13899. BABYLON.serialize()
  13900. ], Camera.prototype, "orthoTop", void 0);
  13901. __decorate([
  13902. BABYLON.serialize()
  13903. ], Camera.prototype, "fov", void 0);
  13904. __decorate([
  13905. BABYLON.serialize()
  13906. ], Camera.prototype, "minZ", void 0);
  13907. __decorate([
  13908. BABYLON.serialize()
  13909. ], Camera.prototype, "maxZ", void 0);
  13910. __decorate([
  13911. BABYLON.serialize()
  13912. ], Camera.prototype, "inertia", void 0);
  13913. __decorate([
  13914. BABYLON.serialize()
  13915. ], Camera.prototype, "mode", void 0);
  13916. __decorate([
  13917. BABYLON.serialize()
  13918. ], Camera.prototype, "layerMask", void 0);
  13919. __decorate([
  13920. BABYLON.serialize()
  13921. ], Camera.prototype, "fovMode", void 0);
  13922. __decorate([
  13923. BABYLON.serialize()
  13924. ], Camera.prototype, "cameraRigMode", void 0);
  13925. __decorate([
  13926. BABYLON.serialize()
  13927. ], Camera.prototype, "interaxialDistance", void 0);
  13928. __decorate([
  13929. BABYLON.serialize()
  13930. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  13931. BABYLON.Camera = Camera;
  13932. })(BABYLON || (BABYLON = {}));
  13933. //# sourceMappingURL=babylon.camera.js.map
  13934. var BABYLON;
  13935. (function (BABYLON) {
  13936. var RenderingManager = (function () {
  13937. function RenderingManager(scene) {
  13938. this._renderingGroups = new Array();
  13939. this._autoClearDepthStencil = {};
  13940. this._customOpaqueSortCompareFn = {};
  13941. this._customAlphaTestSortCompareFn = {};
  13942. this._customTransparentSortCompareFn = {};
  13943. this._renderinGroupInfo = null;
  13944. this._scene = scene;
  13945. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  13946. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  13947. }
  13948. }
  13949. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  13950. if (depth === void 0) { depth = true; }
  13951. if (stencil === void 0) { stencil = true; }
  13952. if (this._depthStencilBufferAlreadyCleaned) {
  13953. return;
  13954. }
  13955. this._scene.getEngine().clear(null, false, depth, stencil);
  13956. this._depthStencilBufferAlreadyCleaned = true;
  13957. };
  13958. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  13959. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  13960. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  13961. var info = null;
  13962. if (observable) {
  13963. if (!this._renderinGroupInfo) {
  13964. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  13965. }
  13966. info = this._renderinGroupInfo;
  13967. info.scene = this._scene;
  13968. info.camera = this._scene.activeCamera;
  13969. }
  13970. // Dispatch sprites
  13971. if (renderSprites) {
  13972. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  13973. var manager = this._scene.spriteManagers[index];
  13974. this.dispatchSprites(manager);
  13975. }
  13976. }
  13977. // Render
  13978. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13979. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  13980. var renderingGroup = this._renderingGroups[index];
  13981. if (!renderingGroup && !observable)
  13982. continue;
  13983. this._currentIndex = index;
  13984. var renderingGroupMask = 0;
  13985. // Fire PRECLEAR stage
  13986. if (observable) {
  13987. renderingGroupMask = Math.pow(2, index);
  13988. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  13989. info.renderingGroupId = index;
  13990. observable.notifyObservers(info, renderingGroupMask);
  13991. }
  13992. // Clear depth/stencil if needed
  13993. var autoClear = this._autoClearDepthStencil[index];
  13994. if (autoClear && autoClear.autoClear) {
  13995. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  13996. }
  13997. if (observable) {
  13998. // Fire PREOPAQUE stage
  13999. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  14000. observable.notifyObservers(info, renderingGroupMask);
  14001. // Fire PRETRANSPARENT stage
  14002. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  14003. observable.notifyObservers(info, renderingGroupMask);
  14004. }
  14005. if (renderingGroup)
  14006. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  14007. // Fire POSTTRANSPARENT stage
  14008. if (observable) {
  14009. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  14010. observable.notifyObservers(info, renderingGroupMask);
  14011. }
  14012. }
  14013. };
  14014. RenderingManager.prototype.reset = function () {
  14015. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14016. var renderingGroup = this._renderingGroups[index];
  14017. if (renderingGroup) {
  14018. renderingGroup.prepare();
  14019. }
  14020. }
  14021. };
  14022. RenderingManager.prototype.dispose = function () {
  14023. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  14024. var renderingGroup = this._renderingGroups[index];
  14025. if (renderingGroup) {
  14026. renderingGroup.dispose();
  14027. }
  14028. }
  14029. this._renderingGroups.length = 0;
  14030. };
  14031. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  14032. if (!this._renderingGroups[renderingGroupId]) {
  14033. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  14034. }
  14035. };
  14036. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  14037. var renderingGroupId = spriteManager.renderingGroupId || 0;
  14038. this._prepareRenderingGroup(renderingGroupId);
  14039. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  14040. };
  14041. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  14042. var renderingGroupId = particleSystem.renderingGroupId || 0;
  14043. this._prepareRenderingGroup(renderingGroupId);
  14044. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  14045. };
  14046. RenderingManager.prototype.dispatch = function (subMesh) {
  14047. var mesh = subMesh.getMesh();
  14048. var renderingGroupId = mesh.renderingGroupId || 0;
  14049. this._prepareRenderingGroup(renderingGroupId);
  14050. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  14051. };
  14052. /**
  14053. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  14054. * This allowed control for front to back rendering or reversly depending of the special needs.
  14055. *
  14056. * @param renderingGroupId The rendering group id corresponding to its index
  14057. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  14058. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  14059. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  14060. */
  14061. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14062. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14063. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14064. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14065. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  14066. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  14067. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  14068. if (this._renderingGroups[renderingGroupId]) {
  14069. var group = this._renderingGroups[renderingGroupId];
  14070. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  14071. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  14072. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  14073. }
  14074. };
  14075. /**
  14076. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  14077. *
  14078. * @param renderingGroupId The rendering group id corresponding to its index
  14079. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  14080. * @param depth Automatically clears depth between groups if true and autoClear is true.
  14081. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  14082. */
  14083. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  14084. if (depth === void 0) { depth = true; }
  14085. if (stencil === void 0) { stencil = true; }
  14086. this._autoClearDepthStencil[renderingGroupId] = {
  14087. autoClear: autoClearDepthStencil,
  14088. depth: depth,
  14089. stencil: stencil
  14090. };
  14091. };
  14092. return RenderingManager;
  14093. }());
  14094. /**
  14095. * The max id used for rendering groups (not included)
  14096. */
  14097. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14098. /**
  14099. * The min id used for rendering groups (included)
  14100. */
  14101. RenderingManager.MIN_RENDERINGGROUPS = 0;
  14102. BABYLON.RenderingManager = RenderingManager;
  14103. })(BABYLON || (BABYLON = {}));
  14104. //# sourceMappingURL=babylon.renderingManager.js.map
  14105. var BABYLON;
  14106. (function (BABYLON) {
  14107. var RenderingGroup = (function () {
  14108. /**
  14109. * Creates a new rendering group.
  14110. * @param index The rendering group index
  14111. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  14112. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  14113. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  14114. */
  14115. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14116. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14117. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14118. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14119. this.index = index;
  14120. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14121. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14122. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14123. this._particleSystems = new BABYLON.SmartArray(256);
  14124. this._spriteManagers = new BABYLON.SmartArray(256);
  14125. this._scene = scene;
  14126. this.opaqueSortCompareFn = opaqueSortCompareFn;
  14127. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  14128. this.transparentSortCompareFn = transparentSortCompareFn;
  14129. }
  14130. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  14131. /**
  14132. * Set the opaque sort comparison function.
  14133. * If null the sub meshes will be render in the order they were created
  14134. */
  14135. set: function (value) {
  14136. this._opaqueSortCompareFn = value;
  14137. if (value) {
  14138. this._renderOpaque = this.renderOpaqueSorted;
  14139. }
  14140. else {
  14141. this._renderOpaque = RenderingGroup.renderUnsorted;
  14142. }
  14143. },
  14144. enumerable: true,
  14145. configurable: true
  14146. });
  14147. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  14148. /**
  14149. * Set the alpha test sort comparison function.
  14150. * If null the sub meshes will be render in the order they were created
  14151. */
  14152. set: function (value) {
  14153. this._alphaTestSortCompareFn = value;
  14154. if (value) {
  14155. this._renderAlphaTest = this.renderAlphaTestSorted;
  14156. }
  14157. else {
  14158. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  14159. }
  14160. },
  14161. enumerable: true,
  14162. configurable: true
  14163. });
  14164. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  14165. /**
  14166. * Set the transparent sort comparison function.
  14167. * If null the sub meshes will be render in the order they were created
  14168. */
  14169. set: function (value) {
  14170. if (value) {
  14171. this._transparentSortCompareFn = value;
  14172. }
  14173. else {
  14174. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  14175. }
  14176. this._renderTransparent = this.renderTransparentSorted;
  14177. },
  14178. enumerable: true,
  14179. configurable: true
  14180. });
  14181. /**
  14182. * Render all the sub meshes contained in the group.
  14183. * @param customRenderFunction Used to override the default render behaviour of the group.
  14184. * @returns true if rendered some submeshes.
  14185. */
  14186. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  14187. if (customRenderFunction) {
  14188. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14189. return;
  14190. }
  14191. var engine = this._scene.getEngine();
  14192. // Opaque
  14193. if (this._opaqueSubMeshes.length !== 0) {
  14194. this._renderOpaque(this._opaqueSubMeshes);
  14195. }
  14196. // Alpha test
  14197. if (this._alphaTestSubMeshes.length !== 0) {
  14198. engine.setAlphaTesting(true);
  14199. this._renderAlphaTest(this._alphaTestSubMeshes);
  14200. engine.setAlphaTesting(false);
  14201. }
  14202. var stencilState = engine.getStencilBuffer();
  14203. engine.setStencilBuffer(false);
  14204. // Sprites
  14205. if (renderSprites) {
  14206. this._renderSprites();
  14207. }
  14208. // Particles
  14209. if (renderParticles) {
  14210. this._renderParticles(activeMeshes);
  14211. }
  14212. if (this.onBeforeTransparentRendering) {
  14213. this.onBeforeTransparentRendering();
  14214. }
  14215. // Transparent
  14216. if (this._transparentSubMeshes.length !== 0) {
  14217. this._renderTransparent(this._transparentSubMeshes);
  14218. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14219. }
  14220. engine.setStencilBuffer(stencilState);
  14221. };
  14222. /**
  14223. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  14224. * @param subMeshes The submeshes to render
  14225. */
  14226. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  14227. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14228. };
  14229. /**
  14230. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  14231. * @param subMeshes The submeshes to render
  14232. */
  14233. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  14234. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14235. };
  14236. /**
  14237. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  14238. * @param subMeshes The submeshes to render
  14239. */
  14240. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  14241. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  14242. };
  14243. /**
  14244. * Renders the submeshes in a specified order.
  14245. * @param subMeshes The submeshes to sort before render
  14246. * @param sortCompareFn The comparison function use to sort
  14247. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  14248. * @param transparent Specifies to activate blending if true
  14249. */
  14250. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  14251. var subIndex = 0;
  14252. var subMesh;
  14253. for (; subIndex < subMeshes.length; subIndex++) {
  14254. subMesh = subMeshes.data[subIndex];
  14255. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  14256. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  14257. }
  14258. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  14259. sortedArray.sort(sortCompareFn);
  14260. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14261. subMesh = sortedArray[subIndex];
  14262. subMesh.render(transparent);
  14263. }
  14264. };
  14265. /**
  14266. * Renders the submeshes in the order they were dispatched (no sort applied).
  14267. * @param subMeshes The submeshes to render
  14268. */
  14269. RenderingGroup.renderUnsorted = function (subMeshes) {
  14270. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  14271. var submesh = subMeshes.data[subIndex];
  14272. submesh.render(false);
  14273. }
  14274. };
  14275. /**
  14276. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14277. * are rendered back to front if in the same alpha index.
  14278. *
  14279. * @param a The first submesh
  14280. * @param b The second submesh
  14281. * @returns The result of the comparison
  14282. */
  14283. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  14284. // Alpha index first
  14285. if (a._alphaIndex > b._alphaIndex) {
  14286. return 1;
  14287. }
  14288. if (a._alphaIndex < b._alphaIndex) {
  14289. return -1;
  14290. }
  14291. // Then distance to camera
  14292. return RenderingGroup.backToFrontSortCompare(a, b);
  14293. };
  14294. /**
  14295. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14296. * are rendered back to front.
  14297. *
  14298. * @param a The first submesh
  14299. * @param b The second submesh
  14300. * @returns The result of the comparison
  14301. */
  14302. RenderingGroup.backToFrontSortCompare = function (a, b) {
  14303. // Then distance to camera
  14304. if (a._distanceToCamera < b._distanceToCamera) {
  14305. return 1;
  14306. }
  14307. if (a._distanceToCamera > b._distanceToCamera) {
  14308. return -1;
  14309. }
  14310. return 0;
  14311. };
  14312. /**
  14313. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14314. * are rendered front to back (prevent overdraw).
  14315. *
  14316. * @param a The first submesh
  14317. * @param b The second submesh
  14318. * @returns The result of the comparison
  14319. */
  14320. RenderingGroup.frontToBackSortCompare = function (a, b) {
  14321. // Then distance to camera
  14322. if (a._distanceToCamera < b._distanceToCamera) {
  14323. return -1;
  14324. }
  14325. if (a._distanceToCamera > b._distanceToCamera) {
  14326. return 1;
  14327. }
  14328. return 0;
  14329. };
  14330. /**
  14331. * Resets the different lists of submeshes to prepare a new frame.
  14332. */
  14333. RenderingGroup.prototype.prepare = function () {
  14334. this._opaqueSubMeshes.reset();
  14335. this._transparentSubMeshes.reset();
  14336. this._alphaTestSubMeshes.reset();
  14337. this._particleSystems.reset();
  14338. this._spriteManagers.reset();
  14339. };
  14340. RenderingGroup.prototype.dispose = function () {
  14341. this._opaqueSubMeshes.dispose();
  14342. this._transparentSubMeshes.dispose();
  14343. this._alphaTestSubMeshes.dispose();
  14344. this._particleSystems.dispose();
  14345. this._spriteManagers.dispose();
  14346. };
  14347. /**
  14348. * Inserts the submesh in its correct queue depending on its material.
  14349. * @param subMesh The submesh to dispatch
  14350. */
  14351. RenderingGroup.prototype.dispatch = function (subMesh) {
  14352. var material = subMesh.getMaterial();
  14353. var mesh = subMesh.getMesh();
  14354. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  14355. this._transparentSubMeshes.push(subMesh);
  14356. }
  14357. else if (material.needAlphaTesting()) {
  14358. this._alphaTestSubMeshes.push(subMesh);
  14359. }
  14360. else {
  14361. this._opaqueSubMeshes.push(subMesh); // Opaque
  14362. }
  14363. };
  14364. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  14365. this._spriteManagers.push(spriteManager);
  14366. };
  14367. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  14368. this._particleSystems.push(particleSystem);
  14369. };
  14370. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  14371. if (this._particleSystems.length === 0) {
  14372. return;
  14373. }
  14374. // Particles
  14375. var activeCamera = this._scene.activeCamera;
  14376. this._scene._particlesDuration.beginMonitoring();
  14377. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  14378. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  14379. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  14380. continue;
  14381. }
  14382. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  14383. this._scene._activeParticles.addCount(particleSystem.render(), false);
  14384. }
  14385. }
  14386. this._scene._particlesDuration.endMonitoring(false);
  14387. };
  14388. RenderingGroup.prototype._renderSprites = function () {
  14389. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  14390. return;
  14391. }
  14392. // Sprites
  14393. var activeCamera = this._scene.activeCamera;
  14394. this._scene._spritesDuration.beginMonitoring();
  14395. for (var id = 0; id < this._spriteManagers.length; id++) {
  14396. var spriteManager = this._spriteManagers.data[id];
  14397. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  14398. spriteManager.render();
  14399. }
  14400. }
  14401. this._scene._spritesDuration.endMonitoring(false);
  14402. };
  14403. return RenderingGroup;
  14404. }());
  14405. BABYLON.RenderingGroup = RenderingGroup;
  14406. })(BABYLON || (BABYLON = {}));
  14407. //# sourceMappingURL=babylon.renderingGroup.js.map
  14408. var BABYLON;
  14409. (function (BABYLON) {
  14410. var ClickInfo = (function () {
  14411. function ClickInfo() {
  14412. this._singleClick = false;
  14413. this._doubleClick = false;
  14414. this._hasSwiped = false;
  14415. this._ignore = false;
  14416. }
  14417. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  14418. get: function () {
  14419. return this._singleClick;
  14420. },
  14421. set: function (b) {
  14422. this._singleClick = b;
  14423. },
  14424. enumerable: true,
  14425. configurable: true
  14426. });
  14427. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  14428. get: function () {
  14429. return this._doubleClick;
  14430. },
  14431. set: function (b) {
  14432. this._doubleClick = b;
  14433. },
  14434. enumerable: true,
  14435. configurable: true
  14436. });
  14437. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  14438. get: function () {
  14439. return this._hasSwiped;
  14440. },
  14441. set: function (b) {
  14442. this._hasSwiped = b;
  14443. },
  14444. enumerable: true,
  14445. configurable: true
  14446. });
  14447. Object.defineProperty(ClickInfo.prototype, "ignore", {
  14448. get: function () {
  14449. return this._ignore;
  14450. },
  14451. set: function (b) {
  14452. this._ignore = b;
  14453. },
  14454. enumerable: true,
  14455. configurable: true
  14456. });
  14457. return ClickInfo;
  14458. }());
  14459. var PointerEventTypes = (function () {
  14460. function PointerEventTypes() {
  14461. }
  14462. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  14463. get: function () {
  14464. return PointerEventTypes._POINTERDOWN;
  14465. },
  14466. enumerable: true,
  14467. configurable: true
  14468. });
  14469. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  14470. get: function () {
  14471. return PointerEventTypes._POINTERUP;
  14472. },
  14473. enumerable: true,
  14474. configurable: true
  14475. });
  14476. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  14477. get: function () {
  14478. return PointerEventTypes._POINTERMOVE;
  14479. },
  14480. enumerable: true,
  14481. configurable: true
  14482. });
  14483. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  14484. get: function () {
  14485. return PointerEventTypes._POINTERWHEEL;
  14486. },
  14487. enumerable: true,
  14488. configurable: true
  14489. });
  14490. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  14491. get: function () {
  14492. return PointerEventTypes._POINTERPICK;
  14493. },
  14494. enumerable: true,
  14495. configurable: true
  14496. });
  14497. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  14498. get: function () {
  14499. return PointerEventTypes._POINTERTAP;
  14500. },
  14501. enumerable: true,
  14502. configurable: true
  14503. });
  14504. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  14505. get: function () {
  14506. return PointerEventTypes._POINTERDOUBLETAP;
  14507. },
  14508. enumerable: true,
  14509. configurable: true
  14510. });
  14511. return PointerEventTypes;
  14512. }());
  14513. PointerEventTypes._POINTERDOWN = 0x01;
  14514. PointerEventTypes._POINTERUP = 0x02;
  14515. PointerEventTypes._POINTERMOVE = 0x04;
  14516. PointerEventTypes._POINTERWHEEL = 0x08;
  14517. PointerEventTypes._POINTERPICK = 0x10;
  14518. PointerEventTypes._POINTERTAP = 0x20;
  14519. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  14520. BABYLON.PointerEventTypes = PointerEventTypes;
  14521. var PointerInfoBase = (function () {
  14522. function PointerInfoBase(type, event) {
  14523. this.type = type;
  14524. this.event = event;
  14525. }
  14526. return PointerInfoBase;
  14527. }());
  14528. BABYLON.PointerInfoBase = PointerInfoBase;
  14529. /**
  14530. * This class is used to store pointer related info for the onPrePointerObservable event.
  14531. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  14532. */
  14533. var PointerInfoPre = (function (_super) {
  14534. __extends(PointerInfoPre, _super);
  14535. function PointerInfoPre(type, event, localX, localY) {
  14536. var _this = _super.call(this, type, event) || this;
  14537. _this.skipOnPointerObservable = false;
  14538. _this.localPosition = new BABYLON.Vector2(localX, localY);
  14539. return _this;
  14540. }
  14541. return PointerInfoPre;
  14542. }(PointerInfoBase));
  14543. BABYLON.PointerInfoPre = PointerInfoPre;
  14544. /**
  14545. * This type contains all the data related to a pointer event in Babylon.js.
  14546. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  14547. */
  14548. var PointerInfo = (function (_super) {
  14549. __extends(PointerInfo, _super);
  14550. function PointerInfo(type, event, pickInfo) {
  14551. var _this = _super.call(this, type, event) || this;
  14552. _this.pickInfo = pickInfo;
  14553. return _this;
  14554. }
  14555. return PointerInfo;
  14556. }(PointerInfoBase));
  14557. BABYLON.PointerInfo = PointerInfo;
  14558. /**
  14559. * This class is used by the onRenderingGroupObservable
  14560. */
  14561. var RenderingGroupInfo = (function () {
  14562. function RenderingGroupInfo() {
  14563. }
  14564. return RenderingGroupInfo;
  14565. }());
  14566. /**
  14567. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  14568. * This stage will be fired no matter what
  14569. */
  14570. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  14571. /**
  14572. * Called before opaque object are rendered.
  14573. * This stage will be fired only if there's 3D Opaque content to render
  14574. */
  14575. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  14576. /**
  14577. * Called after the opaque objects are rendered and before the transparent ones
  14578. * This stage will be fired only if there's 3D transparent content to render
  14579. */
  14580. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  14581. /**
  14582. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  14583. * This stage will be fired no matter what
  14584. */
  14585. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  14586. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  14587. /**
  14588. * Represents a scene to be rendered by the engine.
  14589. * @see http://doc.babylonjs.com/page.php?p=21911
  14590. */
  14591. var Scene = (function () {
  14592. /**
  14593. * @constructor
  14594. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  14595. */
  14596. function Scene(engine) {
  14597. // Members
  14598. this.autoClear = true;
  14599. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  14600. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14601. this.forceWireframe = false;
  14602. this._forcePointsCloud = false;
  14603. this.forceShowBoundingBoxes = false;
  14604. this.animationsEnabled = true;
  14605. this.constantlyUpdateMeshUnderPointer = false;
  14606. this.useRightHandedSystem = false;
  14607. this.hoverCursor = "pointer";
  14608. // Metadata
  14609. this.metadata = null;
  14610. // Events
  14611. /**
  14612. * An event triggered when the scene is disposed.
  14613. * @type {BABYLON.Observable}
  14614. */
  14615. this.onDisposeObservable = new BABYLON.Observable();
  14616. /**
  14617. * An event triggered before rendering the scene
  14618. * @type {BABYLON.Observable}
  14619. */
  14620. this.onBeforeRenderObservable = new BABYLON.Observable();
  14621. /**
  14622. * An event triggered after rendering the scene
  14623. * @type {BABYLON.Observable}
  14624. */
  14625. this.onAfterRenderObservable = new BABYLON.Observable();
  14626. /**
  14627. * An event triggered when the scene is ready
  14628. * @type {BABYLON.Observable}
  14629. */
  14630. this.onReadyObservable = new BABYLON.Observable();
  14631. /**
  14632. * An event triggered before rendering a camera
  14633. * @type {BABYLON.Observable}
  14634. */
  14635. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  14636. /**
  14637. * An event triggered after rendering a camera
  14638. * @type {BABYLON.Observable}
  14639. */
  14640. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  14641. /**
  14642. * An event triggered when a camera is created
  14643. * @type {BABYLON.Observable}
  14644. */
  14645. this.onNewCameraAddedObservable = new BABYLON.Observable();
  14646. /**
  14647. * An event triggered when a camera is removed
  14648. * @type {BABYLON.Observable}
  14649. */
  14650. this.onCameraRemovedObservable = new BABYLON.Observable();
  14651. /**
  14652. * An event triggered when a light is created
  14653. * @type {BABYLON.Observable}
  14654. */
  14655. this.onNewLightAddedObservable = new BABYLON.Observable();
  14656. /**
  14657. * An event triggered when a light is removed
  14658. * @type {BABYLON.Observable}
  14659. */
  14660. this.onLightRemovedObservable = new BABYLON.Observable();
  14661. /**
  14662. * An event triggered when a geometry is created
  14663. * @type {BABYLON.Observable}
  14664. */
  14665. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  14666. /**
  14667. * An event triggered when a geometry is removed
  14668. * @type {BABYLON.Observable}
  14669. */
  14670. this.onGeometryRemovedObservable = new BABYLON.Observable();
  14671. /**
  14672. * An event triggered when a mesh is created
  14673. * @type {BABYLON.Observable}
  14674. */
  14675. this.onNewMeshAddedObservable = new BABYLON.Observable();
  14676. /**
  14677. * An event triggered when a mesh is removed
  14678. * @type {BABYLON.Observable}
  14679. */
  14680. this.onMeshRemovedObservable = new BABYLON.Observable();
  14681. /**
  14682. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  14683. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  14684. * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
  14685. */
  14686. this.onRenderingGroupObservable = new BABYLON.Observable();
  14687. // Animations
  14688. this.animations = [];
  14689. /**
  14690. * This observable event is triggered when any mouse event registered during Scene.attach() is called BEFORE the 3D engine to process anything (mesh/sprite picking for instance).
  14691. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  14692. */
  14693. this.onPrePointerObservable = new BABYLON.Observable();
  14694. /**
  14695. * Observable event triggered each time an input event is received from the rendering canvas
  14696. */
  14697. this.onPointerObservable = new BABYLON.Observable();
  14698. this._meshPickProceed = false;
  14699. this._previousHasSwiped = false;
  14700. this._currentPickResult = null;
  14701. this._previousPickResult = null;
  14702. this._isButtonPressed = false;
  14703. this._doubleClickOccured = false;
  14704. 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
  14705. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  14706. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  14707. this._startingPointerTime = 0;
  14708. this._previousStartingPointerTime = 0;
  14709. // Fog
  14710. /**
  14711. * is fog enabled on this scene.
  14712. * @type {boolean}
  14713. */
  14714. this._fogEnabled = true;
  14715. this._fogMode = Scene.FOGMODE_NONE;
  14716. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14717. this.fogDensity = 0.1;
  14718. this.fogStart = 0;
  14719. this.fogEnd = 1000.0;
  14720. // Lights
  14721. /**
  14722. * is shadow enabled on this scene.
  14723. * @type {boolean}
  14724. */
  14725. this._shadowsEnabled = true;
  14726. /**
  14727. * is light enabled on this scene.
  14728. * @type {boolean}
  14729. */
  14730. this._lightsEnabled = true;
  14731. /**
  14732. * All of the lights added to this scene.
  14733. * @see BABYLON.Light
  14734. * @type {BABYLON.Light[]}
  14735. */
  14736. this.lights = new Array();
  14737. // Cameras
  14738. /**
  14739. * All of the cameras added to this scene.
  14740. * @see BABYLON.Camera
  14741. * @type {BABYLON.Camera[]}
  14742. */
  14743. this.cameras = new Array();
  14744. this.activeCameras = new Array();
  14745. // Meshes
  14746. /**
  14747. * All of the (abstract) meshes added to this scene.
  14748. * @see BABYLON.AbstractMesh
  14749. * @type {BABYLON.AbstractMesh[]}
  14750. */
  14751. this.meshes = new Array();
  14752. // Geometries
  14753. this._geometries = new Array();
  14754. this.materials = new Array();
  14755. this.multiMaterials = new Array();
  14756. // Textures
  14757. this._texturesEnabled = true;
  14758. this.textures = new Array();
  14759. // Particles
  14760. this.particlesEnabled = true;
  14761. this.particleSystems = new Array();
  14762. // Sprites
  14763. this.spritesEnabled = true;
  14764. this.spriteManagers = new Array();
  14765. // Layers
  14766. this.layers = new Array();
  14767. this.highlightLayers = new Array();
  14768. // Skeletons
  14769. this._skeletonsEnabled = true;
  14770. this.skeletons = new Array();
  14771. // Morph targets
  14772. this.morphTargetManagers = new Array();
  14773. // Lens flares
  14774. this.lensFlaresEnabled = true;
  14775. this.lensFlareSystems = new Array();
  14776. // Collisions
  14777. this.collisionsEnabled = true;
  14778. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  14779. // Postprocesses
  14780. this.postProcessesEnabled = true;
  14781. // Customs render targets
  14782. this.renderTargetsEnabled = true;
  14783. this.dumpNextRenderTargets = false;
  14784. this.customRenderTargets = new Array();
  14785. // Imported meshes
  14786. this.importedMeshesFiles = new Array();
  14787. // Probes
  14788. this.probesEnabled = true;
  14789. this.reflectionProbes = new Array();
  14790. this._actionManagers = new Array();
  14791. this._meshesForIntersections = new BABYLON.SmartArray(256);
  14792. // Procedural textures
  14793. this.proceduralTexturesEnabled = true;
  14794. this._proceduralTextures = new Array();
  14795. this.soundTracks = new Array();
  14796. this._audioEnabled = true;
  14797. this._headphone = false;
  14798. // Performance counters
  14799. this._totalMeshesCounter = new BABYLON.PerfCounter();
  14800. this._totalLightsCounter = new BABYLON.PerfCounter();
  14801. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  14802. this._totalTexturesCounter = new BABYLON.PerfCounter();
  14803. this._totalVertices = new BABYLON.PerfCounter();
  14804. this._activeIndices = new BABYLON.PerfCounter();
  14805. this._activeParticles = new BABYLON.PerfCounter();
  14806. this._lastFrameDuration = new BABYLON.PerfCounter();
  14807. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  14808. this._renderTargetsDuration = new BABYLON.PerfCounter();
  14809. this._particlesDuration = new BABYLON.PerfCounter();
  14810. this._renderDuration = new BABYLON.PerfCounter();
  14811. this._spritesDuration = new BABYLON.PerfCounter();
  14812. this._activeBones = new BABYLON.PerfCounter();
  14813. this._animationTime = 0;
  14814. this.animationTimeScale = 1;
  14815. this._renderId = 0;
  14816. this._executeWhenReadyTimeoutId = -1;
  14817. this._intermediateRendering = false;
  14818. this._viewUpdateFlag = -1;
  14819. this._projectionUpdateFlag = -1;
  14820. this._toBeDisposed = new BABYLON.SmartArray(256);
  14821. this._pendingData = []; //ANY
  14822. this._activeMeshes = new BABYLON.SmartArray(256);
  14823. this._processedMaterials = new BABYLON.SmartArray(256);
  14824. this._renderTargets = new BABYLON.SmartArray(256);
  14825. this._activeParticleSystems = new BABYLON.SmartArray(256);
  14826. this._activeSkeletons = new BABYLON.SmartArray(32);
  14827. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  14828. this._activeAnimatables = new Array();
  14829. this._transformMatrix = BABYLON.Matrix.Zero();
  14830. this._edgesRenderers = new BABYLON.SmartArray(16);
  14831. this._uniqueIdCounter = 0;
  14832. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  14833. this._engine.scenes.push(this);
  14834. this._uid = null;
  14835. this._renderingManager = new BABYLON.RenderingManager(this);
  14836. this.postProcessManager = new BABYLON.PostProcessManager(this);
  14837. if (BABYLON.OutlineRenderer) {
  14838. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  14839. }
  14840. this.attachControl();
  14841. if (BABYLON.SoundTrack) {
  14842. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  14843. }
  14844. //simplification queue
  14845. if (BABYLON.SimplificationQueue) {
  14846. this.simplificationQueue = new BABYLON.SimplificationQueue();
  14847. }
  14848. //collision coordinator initialization. For now legacy per default.
  14849. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  14850. // Uniform Buffer
  14851. this._createUbo();
  14852. }
  14853. Object.defineProperty(Scene, "FOGMODE_NONE", {
  14854. get: function () {
  14855. return Scene._FOGMODE_NONE;
  14856. },
  14857. enumerable: true,
  14858. configurable: true
  14859. });
  14860. Object.defineProperty(Scene, "FOGMODE_EXP", {
  14861. get: function () {
  14862. return Scene._FOGMODE_EXP;
  14863. },
  14864. enumerable: true,
  14865. configurable: true
  14866. });
  14867. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  14868. get: function () {
  14869. return Scene._FOGMODE_EXP2;
  14870. },
  14871. enumerable: true,
  14872. configurable: true
  14873. });
  14874. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  14875. get: function () {
  14876. return Scene._FOGMODE_LINEAR;
  14877. },
  14878. enumerable: true,
  14879. configurable: true
  14880. });
  14881. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  14882. get: function () {
  14883. return this._forcePointsCloud;
  14884. },
  14885. set: function (value) {
  14886. if (this._forcePointsCloud === value) {
  14887. return;
  14888. }
  14889. this._forcePointsCloud = value;
  14890. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  14891. },
  14892. enumerable: true,
  14893. configurable: true
  14894. });
  14895. Object.defineProperty(Scene.prototype, "onDispose", {
  14896. set: function (callback) {
  14897. if (this._onDisposeObserver) {
  14898. this.onDisposeObservable.remove(this._onDisposeObserver);
  14899. }
  14900. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14901. },
  14902. enumerable: true,
  14903. configurable: true
  14904. });
  14905. Object.defineProperty(Scene.prototype, "beforeRender", {
  14906. set: function (callback) {
  14907. if (this._onBeforeRenderObserver) {
  14908. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  14909. }
  14910. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  14911. },
  14912. enumerable: true,
  14913. configurable: true
  14914. });
  14915. Object.defineProperty(Scene.prototype, "afterRender", {
  14916. set: function (callback) {
  14917. if (this._onAfterRenderObserver) {
  14918. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  14919. }
  14920. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  14921. },
  14922. enumerable: true,
  14923. configurable: true
  14924. });
  14925. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  14926. set: function (callback) {
  14927. if (this._onBeforeCameraRenderObserver) {
  14928. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  14929. }
  14930. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  14931. },
  14932. enumerable: true,
  14933. configurable: true
  14934. });
  14935. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  14936. set: function (callback) {
  14937. if (this._onAfterCameraRenderObserver) {
  14938. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  14939. }
  14940. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  14941. },
  14942. enumerable: true,
  14943. configurable: true
  14944. });
  14945. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  14946. get: function () {
  14947. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  14948. },
  14949. enumerable: true,
  14950. configurable: true
  14951. });
  14952. Object.defineProperty(Scene.prototype, "fogEnabled", {
  14953. get: function () {
  14954. return this._fogEnabled;
  14955. },
  14956. set: function (value) {
  14957. if (this._fogEnabled === value) {
  14958. return;
  14959. }
  14960. this._fogEnabled = value;
  14961. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  14962. },
  14963. enumerable: true,
  14964. configurable: true
  14965. });
  14966. Object.defineProperty(Scene.prototype, "fogMode", {
  14967. get: function () {
  14968. return this._fogMode;
  14969. },
  14970. set: function (value) {
  14971. if (this._fogMode === value) {
  14972. return;
  14973. }
  14974. this._fogMode = value;
  14975. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  14976. },
  14977. enumerable: true,
  14978. configurable: true
  14979. });
  14980. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  14981. get: function () {
  14982. return this._shadowsEnabled;
  14983. },
  14984. set: function (value) {
  14985. if (this._shadowsEnabled === value) {
  14986. return;
  14987. }
  14988. this._shadowsEnabled = value;
  14989. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  14990. },
  14991. enumerable: true,
  14992. configurable: true
  14993. });
  14994. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  14995. get: function () {
  14996. return this._lightsEnabled;
  14997. },
  14998. set: function (value) {
  14999. if (this._lightsEnabled === value) {
  15000. return;
  15001. }
  15002. this._lightsEnabled = value;
  15003. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  15004. },
  15005. enumerable: true,
  15006. configurable: true
  15007. });
  15008. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  15009. get: function () {
  15010. if (!this._defaultMaterial) {
  15011. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15012. }
  15013. return this._defaultMaterial;
  15014. },
  15015. enumerable: true,
  15016. configurable: true
  15017. });
  15018. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  15019. get: function () {
  15020. return this._texturesEnabled;
  15021. },
  15022. set: function (value) {
  15023. if (this._texturesEnabled === value) {
  15024. return;
  15025. }
  15026. this._texturesEnabled = value;
  15027. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  15028. },
  15029. enumerable: true,
  15030. configurable: true
  15031. });
  15032. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  15033. get: function () {
  15034. return this._skeletonsEnabled;
  15035. },
  15036. set: function (value) {
  15037. if (this._skeletonsEnabled === value) {
  15038. return;
  15039. }
  15040. this._skeletonsEnabled = value;
  15041. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  15042. },
  15043. enumerable: true,
  15044. configurable: true
  15045. });
  15046. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  15047. get: function () {
  15048. if (!this._postProcessRenderPipelineManager) {
  15049. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15050. }
  15051. return this._postProcessRenderPipelineManager;
  15052. },
  15053. enumerable: true,
  15054. configurable: true
  15055. });
  15056. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  15057. get: function () {
  15058. return this._frustumPlanes;
  15059. },
  15060. enumerable: true,
  15061. configurable: true
  15062. });
  15063. Object.defineProperty(Scene.prototype, "debugLayer", {
  15064. // Properties
  15065. get: function () {
  15066. if (!this._debugLayer) {
  15067. this._debugLayer = new BABYLON.DebugLayer(this);
  15068. }
  15069. return this._debugLayer;
  15070. },
  15071. enumerable: true,
  15072. configurable: true
  15073. });
  15074. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15075. get: function () {
  15076. return this._workerCollisions;
  15077. },
  15078. set: function (enabled) {
  15079. if (!BABYLON.CollisionCoordinatorLegacy) {
  15080. return;
  15081. }
  15082. enabled = (enabled && !!Worker);
  15083. this._workerCollisions = enabled;
  15084. if (this.collisionCoordinator) {
  15085. this.collisionCoordinator.destroy();
  15086. }
  15087. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15088. this.collisionCoordinator.init(this);
  15089. },
  15090. enumerable: true,
  15091. configurable: true
  15092. });
  15093. Object.defineProperty(Scene.prototype, "selectionOctree", {
  15094. get: function () {
  15095. return this._selectionOctree;
  15096. },
  15097. enumerable: true,
  15098. configurable: true
  15099. });
  15100. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  15101. /**
  15102. * The mesh that is currently under the pointer.
  15103. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  15104. */
  15105. get: function () {
  15106. return this._pointerOverMesh;
  15107. },
  15108. enumerable: true,
  15109. configurable: true
  15110. });
  15111. Object.defineProperty(Scene.prototype, "pointerX", {
  15112. /**
  15113. * Current on-screen X position of the pointer
  15114. * @return {number} X position of the pointer
  15115. */
  15116. get: function () {
  15117. return this._pointerX;
  15118. },
  15119. enumerable: true,
  15120. configurable: true
  15121. });
  15122. Object.defineProperty(Scene.prototype, "pointerY", {
  15123. /**
  15124. * Current on-screen Y position of the pointer
  15125. * @return {number} Y position of the pointer
  15126. */
  15127. get: function () {
  15128. return this._pointerY;
  15129. },
  15130. enumerable: true,
  15131. configurable: true
  15132. });
  15133. Scene.prototype.getCachedMaterial = function () {
  15134. return this._cachedMaterial;
  15135. };
  15136. Scene.prototype.getCachedEffect = function () {
  15137. return this._cachedEffect;
  15138. };
  15139. Scene.prototype.getCachedVisibility = function () {
  15140. return this._cachedVisibility;
  15141. };
  15142. Scene.prototype.isCachedMaterialValid = function (material, effect, visibility) {
  15143. if (visibility === void 0) { visibility = 0; }
  15144. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  15145. };
  15146. Scene.prototype.getBoundingBoxRenderer = function () {
  15147. if (!this._boundingBoxRenderer) {
  15148. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  15149. }
  15150. return this._boundingBoxRenderer;
  15151. };
  15152. Scene.prototype.getOutlineRenderer = function () {
  15153. return this._outlineRenderer;
  15154. };
  15155. Scene.prototype.getEngine = function () {
  15156. return this._engine;
  15157. };
  15158. Scene.prototype.getTotalVertices = function () {
  15159. return this._totalVertices.current;
  15160. };
  15161. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  15162. get: function () {
  15163. return this._totalVertices;
  15164. },
  15165. enumerable: true,
  15166. configurable: true
  15167. });
  15168. Scene.prototype.getActiveIndices = function () {
  15169. return this._activeIndices.current;
  15170. };
  15171. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  15172. get: function () {
  15173. return this._activeIndices;
  15174. },
  15175. enumerable: true,
  15176. configurable: true
  15177. });
  15178. Scene.prototype.getActiveParticles = function () {
  15179. return this._activeParticles.current;
  15180. };
  15181. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  15182. get: function () {
  15183. return this._activeParticles;
  15184. },
  15185. enumerable: true,
  15186. configurable: true
  15187. });
  15188. Scene.prototype.getActiveBones = function () {
  15189. return this._activeBones.current;
  15190. };
  15191. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  15192. get: function () {
  15193. return this._activeBones;
  15194. },
  15195. enumerable: true,
  15196. configurable: true
  15197. });
  15198. // Stats
  15199. Scene.prototype.getLastFrameDuration = function () {
  15200. return this._lastFrameDuration.current;
  15201. };
  15202. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  15203. get: function () {
  15204. return this._lastFrameDuration;
  15205. },
  15206. enumerable: true,
  15207. configurable: true
  15208. });
  15209. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  15210. return this._evaluateActiveMeshesDuration.current;
  15211. };
  15212. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  15213. get: function () {
  15214. return this._evaluateActiveMeshesDuration;
  15215. },
  15216. enumerable: true,
  15217. configurable: true
  15218. });
  15219. Scene.prototype.getActiveMeshes = function () {
  15220. return this._activeMeshes;
  15221. };
  15222. Scene.prototype.getRenderTargetsDuration = function () {
  15223. return this._renderTargetsDuration.current;
  15224. };
  15225. Scene.prototype.getRenderDuration = function () {
  15226. return this._renderDuration.current;
  15227. };
  15228. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  15229. get: function () {
  15230. return this._renderDuration;
  15231. },
  15232. enumerable: true,
  15233. configurable: true
  15234. });
  15235. Scene.prototype.getParticlesDuration = function () {
  15236. return this._particlesDuration.current;
  15237. };
  15238. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  15239. get: function () {
  15240. return this._particlesDuration;
  15241. },
  15242. enumerable: true,
  15243. configurable: true
  15244. });
  15245. Scene.prototype.getSpritesDuration = function () {
  15246. return this._spritesDuration.current;
  15247. };
  15248. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  15249. get: function () {
  15250. return this._spritesDuration;
  15251. },
  15252. enumerable: true,
  15253. configurable: true
  15254. });
  15255. Scene.prototype.getAnimationRatio = function () {
  15256. return this._animationRatio;
  15257. };
  15258. Scene.prototype.getRenderId = function () {
  15259. return this._renderId;
  15260. };
  15261. Scene.prototype.incrementRenderId = function () {
  15262. this._renderId++;
  15263. };
  15264. Scene.prototype._updatePointerPosition = function (evt) {
  15265. var canvasRect = this._engine.getRenderingCanvasClientRect();
  15266. this._pointerX = evt.clientX - canvasRect.left;
  15267. this._pointerY = evt.clientY - canvasRect.top;
  15268. this._unTranslatedPointerX = this._pointerX;
  15269. this._unTranslatedPointerY = this._pointerY;
  15270. if (this.cameraToUseForPointers) {
  15271. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  15272. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  15273. }
  15274. };
  15275. Scene.prototype._createUbo = function () {
  15276. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  15277. this._sceneUbo.addUniform("viewProjection", 16);
  15278. this._sceneUbo.addUniform("view", 16);
  15279. };
  15280. // Pointers handling
  15281. /**
  15282. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  15283. * @param attachUp defines if you want to attach events to pointerup
  15284. * @param attachDown defines if you want to attach events to pointerdown
  15285. * @param attachMove defines if you want to attach events to pointermove
  15286. */
  15287. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  15288. var _this = this;
  15289. if (attachUp === void 0) { attachUp = true; }
  15290. if (attachDown === void 0) { attachDown = true; }
  15291. if (attachMove === void 0) { attachMove = true; }
  15292. this._initActionManager = function (act, clickInfo) {
  15293. if (!_this._meshPickProceed) {
  15294. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  15295. _this._currentPickResult = pickResult;
  15296. if (pickResult) {
  15297. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  15298. }
  15299. _this._meshPickProceed = true;
  15300. }
  15301. return act;
  15302. };
  15303. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  15304. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  15305. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  15306. btn !== _this._previousButtonPressed) {
  15307. _this._doubleClickOccured = false;
  15308. clickInfo.singleClick = true;
  15309. clickInfo.ignore = false;
  15310. cb(clickInfo, _this._currentPickResult);
  15311. }
  15312. };
  15313. this._initClickEvent = function (obs1, obs2, evt, cb) {
  15314. var clickInfo = new ClickInfo();
  15315. _this._currentPickResult = null;
  15316. var act;
  15317. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  15318. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  15319. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  15320. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  15321. act = _this._initActionManager(act, clickInfo);
  15322. if (act)
  15323. checkPicking = act.hasPickTriggers;
  15324. }
  15325. if (checkPicking) {
  15326. var btn = evt.button;
  15327. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  15328. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  15329. if (!clickInfo.hasSwiped) {
  15330. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  15331. if (!checkSingleClickImmediately) {
  15332. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  15333. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  15334. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  15335. act = _this._initActionManager(act, clickInfo);
  15336. if (act)
  15337. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  15338. }
  15339. }
  15340. if (checkSingleClickImmediately) {
  15341. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  15342. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  15343. btn !== _this._previousButtonPressed) {
  15344. clickInfo.singleClick = true;
  15345. cb(clickInfo, _this._currentPickResult);
  15346. }
  15347. }
  15348. else {
  15349. // wait that no double click has been raised during the double click delay
  15350. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  15351. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  15352. }
  15353. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  15354. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  15355. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  15356. act = _this._initActionManager(act, clickInfo);
  15357. if (act)
  15358. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  15359. }
  15360. if (checkDoubleClick) {
  15361. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  15362. if (btn === _this._previousButtonPressed &&
  15363. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  15364. !_this._doubleClickOccured) {
  15365. // pointer has not moved for 2 clicks, it's a double click
  15366. if (!clickInfo.hasSwiped &&
  15367. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  15368. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  15369. _this._previousStartingPointerTime = 0;
  15370. _this._doubleClickOccured = true;
  15371. clickInfo.doubleClick = true;
  15372. clickInfo.ignore = false;
  15373. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  15374. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  15375. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  15376. cb(clickInfo, _this._currentPickResult);
  15377. }
  15378. else {
  15379. _this._doubleClickOccured = false;
  15380. _this._previousStartingPointerTime = _this._startingPointerTime;
  15381. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  15382. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  15383. _this._previousButtonPressed = btn;
  15384. _this._previousHasSwiped = clickInfo.hasSwiped;
  15385. if (Scene.ExclusiveDoubleClickMode) {
  15386. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  15387. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  15388. }
  15389. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  15390. cb(clickInfo, _this._previousPickResult);
  15391. }
  15392. else {
  15393. cb(clickInfo, _this._currentPickResult);
  15394. }
  15395. }
  15396. }
  15397. else {
  15398. _this._doubleClickOccured = false;
  15399. _this._previousStartingPointerTime = _this._startingPointerTime;
  15400. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  15401. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  15402. _this._previousButtonPressed = btn;
  15403. _this._previousHasSwiped = clickInfo.hasSwiped;
  15404. }
  15405. }
  15406. }
  15407. }
  15408. clickInfo.ignore = true;
  15409. cb(clickInfo, _this._currentPickResult);
  15410. };
  15411. var spritePredicate = function (sprite) {
  15412. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  15413. };
  15414. this._onPointerMove = function (evt) {
  15415. _this._updatePointerPosition(evt);
  15416. // PreObservable support
  15417. if (_this.onPrePointerObservable.hasObservers()) {
  15418. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15419. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15420. _this.onPrePointerObservable.notifyObservers(pi, type);
  15421. if (pi.skipOnPointerObservable) {
  15422. return;
  15423. }
  15424. }
  15425. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15426. return;
  15427. }
  15428. var canvas = _this._engine.getRenderingCanvas();
  15429. if (!_this.pointerMovePredicate) {
  15430. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  15431. }
  15432. // Meshes
  15433. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  15434. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  15435. _this.setPointerOverSprite(null);
  15436. _this.setPointerOverMesh(pickResult.pickedMesh);
  15437. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  15438. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  15439. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  15440. }
  15441. else {
  15442. canvas.style.cursor = _this.hoverCursor;
  15443. }
  15444. }
  15445. else {
  15446. canvas.style.cursor = "";
  15447. }
  15448. }
  15449. else {
  15450. _this.setPointerOverMesh(null);
  15451. // Sprites
  15452. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15453. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  15454. _this.setPointerOverSprite(pickResult.pickedSprite);
  15455. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  15456. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  15457. }
  15458. else {
  15459. canvas.style.cursor = _this.hoverCursor;
  15460. }
  15461. }
  15462. else {
  15463. _this.setPointerOverSprite(null);
  15464. // Restore pointer
  15465. canvas.style.cursor = "";
  15466. }
  15467. }
  15468. if (_this.onPointerMove) {
  15469. _this.onPointerMove(evt, pickResult);
  15470. }
  15471. if (_this.onPointerObservable.hasObservers()) {
  15472. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15473. var pi = new PointerInfo(type, evt, pickResult);
  15474. _this.onPointerObservable.notifyObservers(pi, type);
  15475. }
  15476. };
  15477. this._onPointerDown = function (evt) {
  15478. _this._isButtonPressed = true;
  15479. _this._pickedDownMesh = null;
  15480. _this._meshPickProceed = false;
  15481. _this._updatePointerPosition(evt);
  15482. // PreObservable support
  15483. if (_this.onPrePointerObservable.hasObservers()) {
  15484. var type = PointerEventTypes.POINTERDOWN;
  15485. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15486. _this.onPrePointerObservable.notifyObservers(pi, type);
  15487. if (pi.skipOnPointerObservable) {
  15488. return;
  15489. }
  15490. }
  15491. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15492. return;
  15493. }
  15494. _this._startingPointerPosition.x = _this._pointerX;
  15495. _this._startingPointerPosition.y = _this._pointerY;
  15496. _this._startingPointerTime = new Date().getTime();
  15497. if (!_this.pointerDownPredicate) {
  15498. _this.pointerDownPredicate = function (mesh) {
  15499. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  15500. };
  15501. }
  15502. // Meshes
  15503. _this._pickedDownMesh = null;
  15504. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  15505. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  15506. _this._pickedDownMesh = pickResult.pickedMesh;
  15507. var actionManager = pickResult.pickedMesh.actionManager;
  15508. if (actionManager) {
  15509. if (actionManager.hasPickTriggers) {
  15510. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15511. switch (evt.button) {
  15512. case 0:
  15513. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15514. break;
  15515. case 1:
  15516. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15517. break;
  15518. case 2:
  15519. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15520. break;
  15521. }
  15522. }
  15523. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  15524. window.setTimeout((function () {
  15525. var _this = this;
  15526. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger) && mesh == _this._pickedDownMesh; }, false, this.cameraToUseForPointers);
  15527. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  15528. if (this._isButtonPressed &&
  15529. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  15530. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  15531. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  15532. this._startingPointerTime = 0;
  15533. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15534. }
  15535. }
  15536. }).bind(_this), Scene.LongPressDelay);
  15537. }
  15538. }
  15539. }
  15540. if (_this.onPointerDown) {
  15541. _this.onPointerDown(evt, pickResult);
  15542. }
  15543. if (_this.onPointerObservable.hasObservers()) {
  15544. var type = PointerEventTypes.POINTERDOWN;
  15545. var pi = new PointerInfo(type, evt, pickResult);
  15546. _this.onPointerObservable.notifyObservers(pi, type);
  15547. }
  15548. // Sprites
  15549. _this._pickedDownSprite = null;
  15550. if (_this.spriteManagers.length > 0) {
  15551. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15552. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  15553. if (pickResult.pickedSprite.actionManager) {
  15554. _this._pickedDownSprite = pickResult.pickedSprite;
  15555. switch (evt.button) {
  15556. case 0:
  15557. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15558. break;
  15559. case 1:
  15560. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15561. break;
  15562. case 2:
  15563. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15564. break;
  15565. }
  15566. if (pickResult.pickedSprite.actionManager) {
  15567. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15568. }
  15569. }
  15570. }
  15571. }
  15572. };
  15573. this._onPointerUp = function (evt) {
  15574. _this._isButtonPressed = false;
  15575. _this._pickedUpMesh = null;
  15576. _this._meshPickProceed = false;
  15577. _this._updatePointerPosition(evt);
  15578. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  15579. // PreObservable support
  15580. if (this.onPrePointerObservable.hasObservers()) {
  15581. if (!clickInfo.ignore) {
  15582. if (!clickInfo.hasSwiped) {
  15583. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  15584. var type = PointerEventTypes.POINTERTAP;
  15585. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  15586. this.onPrePointerObservable.notifyObservers(pi, type);
  15587. if (pi.skipOnPointerObservable) {
  15588. return;
  15589. }
  15590. }
  15591. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  15592. var type = PointerEventTypes.POINTERDOUBLETAP;
  15593. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  15594. this.onPrePointerObservable.notifyObservers(pi, type);
  15595. if (pi.skipOnPointerObservable) {
  15596. return;
  15597. }
  15598. }
  15599. }
  15600. }
  15601. else {
  15602. var type = PointerEventTypes.POINTERUP;
  15603. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  15604. this.onPrePointerObservable.notifyObservers(pi, type);
  15605. if (pi.skipOnPointerObservable) {
  15606. return;
  15607. }
  15608. }
  15609. }
  15610. if (!this.cameraToUseForPointers && !this.activeCamera) {
  15611. return;
  15612. }
  15613. if (!this.pointerUpPredicate) {
  15614. this.pointerUpPredicate = function (mesh) {
  15615. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  15616. };
  15617. }
  15618. // Meshes
  15619. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  15620. this._initActionManager(null, clickInfo);
  15621. }
  15622. if (!pickResult) {
  15623. pickResult = this._currentPickResult;
  15624. }
  15625. if (pickResult && pickResult && pickResult.pickedMesh) {
  15626. this._pickedUpMesh = pickResult.pickedMesh;
  15627. if (this._pickedDownMesh === this._pickedUpMesh) {
  15628. if (this.onPointerPick) {
  15629. this.onPointerPick(evt, pickResult);
  15630. }
  15631. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  15632. var type = PointerEventTypes.POINTERPICK;
  15633. var pi = new PointerInfo(type, evt, pickResult);
  15634. this.onPointerObservable.notifyObservers(pi, type);
  15635. }
  15636. }
  15637. if (pickResult.pickedMesh.actionManager) {
  15638. if (clickInfo.ignore) {
  15639. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15640. }
  15641. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  15642. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15643. }
  15644. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  15645. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15646. }
  15647. }
  15648. }
  15649. if (this._pickedDownMesh &&
  15650. this._pickedDownMesh.actionManager &&
  15651. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  15652. this._pickedDownMesh !== this._pickedUpMesh) {
  15653. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  15654. }
  15655. if (this.onPointerUp) {
  15656. this.onPointerUp(evt, pickResult);
  15657. }
  15658. if (this.onPointerObservable.hasObservers()) {
  15659. if (!clickInfo.ignore) {
  15660. if (!clickInfo.hasSwiped) {
  15661. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  15662. var type = PointerEventTypes.POINTERTAP;
  15663. var pi = new PointerInfo(type, evt, pickResult);
  15664. this.onPointerObservable.notifyObservers(pi, type);
  15665. }
  15666. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  15667. var type = PointerEventTypes.POINTERDOUBLETAP;
  15668. var pi = new PointerInfo(type, evt, pickResult);
  15669. this.onPointerObservable.notifyObservers(pi, type);
  15670. }
  15671. }
  15672. }
  15673. else {
  15674. var type = PointerEventTypes.POINTERUP;
  15675. var pi = new PointerInfo(type, evt, pickResult);
  15676. this.onPointerObservable.notifyObservers(pi, type);
  15677. }
  15678. }
  15679. // Sprites
  15680. if (this.spriteManagers.length > 0) {
  15681. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  15682. if (pickResult.hit && pickResult.pickedSprite) {
  15683. if (pickResult.pickedSprite.actionManager) {
  15684. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  15685. if (pickResult.pickedSprite.actionManager) {
  15686. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  15687. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  15688. }
  15689. }
  15690. }
  15691. }
  15692. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  15693. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  15694. }
  15695. }
  15696. this._previousPickResult = this._currentPickResult;
  15697. }).bind(_this));
  15698. };
  15699. this._onKeyDown = function (evt) {
  15700. if (_this.actionManager) {
  15701. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15702. }
  15703. };
  15704. this._onKeyUp = function (evt) {
  15705. if (_this.actionManager) {
  15706. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15707. }
  15708. };
  15709. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15710. var canvas = this._engine.getRenderingCanvas();
  15711. if (attachMove) {
  15712. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  15713. // Wheel
  15714. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  15715. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  15716. }
  15717. if (attachDown) {
  15718. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  15719. }
  15720. if (attachUp) {
  15721. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  15722. }
  15723. canvas.tabIndex = 1;
  15724. canvas.addEventListener("keydown", this._onKeyDown, false);
  15725. canvas.addEventListener("keyup", this._onKeyUp, false);
  15726. };
  15727. Scene.prototype.detachControl = function () {
  15728. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15729. var canvas = this._engine.getRenderingCanvas();
  15730. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  15731. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  15732. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  15733. // Wheel
  15734. canvas.removeEventListener('mousewheel', this._onPointerMove);
  15735. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  15736. canvas.removeEventListener("keydown", this._onKeyDown);
  15737. canvas.removeEventListener("keyup", this._onKeyUp);
  15738. };
  15739. // Ready
  15740. Scene.prototype.isReady = function () {
  15741. if (this._pendingData.length > 0) {
  15742. return false;
  15743. }
  15744. var index;
  15745. // Geometries
  15746. for (index = 0; index < this._geometries.length; index++) {
  15747. var geometry = this._geometries[index];
  15748. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15749. return false;
  15750. }
  15751. }
  15752. // Meshes
  15753. for (index = 0; index < this.meshes.length; index++) {
  15754. var mesh = this.meshes[index];
  15755. if (!mesh.isEnabled()) {
  15756. continue;
  15757. }
  15758. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  15759. continue;
  15760. }
  15761. if (!mesh.isReady()) {
  15762. return false;
  15763. }
  15764. var mat = mesh.material;
  15765. if (mat) {
  15766. if (!mat.isReady(mesh)) {
  15767. return false;
  15768. }
  15769. }
  15770. }
  15771. return true;
  15772. };
  15773. Scene.prototype.resetCachedMaterial = function () {
  15774. this._cachedMaterial = null;
  15775. this._cachedEffect = null;
  15776. this._cachedVisibility = null;
  15777. };
  15778. Scene.prototype.registerBeforeRender = function (func) {
  15779. this.onBeforeRenderObservable.add(func);
  15780. };
  15781. Scene.prototype.unregisterBeforeRender = function (func) {
  15782. this.onBeforeRenderObservable.removeCallback(func);
  15783. };
  15784. Scene.prototype.registerAfterRender = function (func) {
  15785. this.onAfterRenderObservable.add(func);
  15786. };
  15787. Scene.prototype.unregisterAfterRender = function (func) {
  15788. this.onAfterRenderObservable.removeCallback(func);
  15789. };
  15790. Scene.prototype._addPendingData = function (data) {
  15791. this._pendingData.push(data);
  15792. };
  15793. Scene.prototype._removePendingData = function (data) {
  15794. var index = this._pendingData.indexOf(data);
  15795. if (index !== -1) {
  15796. this._pendingData.splice(index, 1);
  15797. }
  15798. };
  15799. Scene.prototype.getWaitingItemsCount = function () {
  15800. return this._pendingData.length;
  15801. };
  15802. /**
  15803. * Registers a function to be executed when the scene is ready.
  15804. * @param {Function} func - the function to be executed.
  15805. */
  15806. Scene.prototype.executeWhenReady = function (func) {
  15807. var _this = this;
  15808. this.onReadyObservable.add(func);
  15809. if (this._executeWhenReadyTimeoutId !== -1) {
  15810. return;
  15811. }
  15812. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15813. _this._checkIsReady();
  15814. }, 150);
  15815. };
  15816. Scene.prototype._checkIsReady = function () {
  15817. var _this = this;
  15818. if (this.isReady()) {
  15819. this.onReadyObservable.notifyObservers(this);
  15820. this.onReadyObservable.clear();
  15821. this._executeWhenReadyTimeoutId = -1;
  15822. return;
  15823. }
  15824. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15825. _this._checkIsReady();
  15826. }, 150);
  15827. };
  15828. // Animations
  15829. /**
  15830. * Will start the animation sequence of a given target
  15831. * @param target - the target
  15832. * @param {number} from - from which frame should animation start
  15833. * @param {number} to - till which frame should animation run.
  15834. * @param {boolean} [loop] - should the animation loop
  15835. * @param {number} [speedRatio] - the speed in which to run the animation
  15836. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  15837. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  15838. * @return {BABYLON.Animatable} the animatable object created for this animation
  15839. * @see BABYLON.Animatable
  15840. * @see http://doc.babylonjs.com/page.php?p=22081
  15841. */
  15842. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  15843. if (speedRatio === void 0) { speedRatio = 1.0; }
  15844. this.stopAnimation(target);
  15845. if (!animatable) {
  15846. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  15847. }
  15848. // Local animations
  15849. if (target.animations) {
  15850. animatable.appendAnimations(target, target.animations);
  15851. }
  15852. // Children animations
  15853. if (target.getAnimatables) {
  15854. var animatables = target.getAnimatables();
  15855. for (var index = 0; index < animatables.length; index++) {
  15856. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  15857. }
  15858. }
  15859. animatable.reset();
  15860. return animatable;
  15861. };
  15862. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  15863. if (speedRatio === undefined) {
  15864. speedRatio = 1.0;
  15865. }
  15866. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  15867. return animatable;
  15868. };
  15869. Scene.prototype.getAnimatableByTarget = function (target) {
  15870. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15871. if (this._activeAnimatables[index].target === target) {
  15872. return this._activeAnimatables[index];
  15873. }
  15874. }
  15875. return null;
  15876. };
  15877. Object.defineProperty(Scene.prototype, "Animatables", {
  15878. get: function () {
  15879. return this._activeAnimatables;
  15880. },
  15881. enumerable: true,
  15882. configurable: true
  15883. });
  15884. /**
  15885. * Will stop the animation of the given target
  15886. * @param target - the target
  15887. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  15888. * @see beginAnimation
  15889. */
  15890. Scene.prototype.stopAnimation = function (target, animationName) {
  15891. var animatable = this.getAnimatableByTarget(target);
  15892. if (animatable) {
  15893. animatable.stop(animationName);
  15894. }
  15895. };
  15896. Scene.prototype._animate = function () {
  15897. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  15898. return;
  15899. }
  15900. // Getting time
  15901. var now = BABYLON.Tools.Now;
  15902. if (!this._animationTimeLast) {
  15903. if (this._pendingData.length > 0) {
  15904. return;
  15905. }
  15906. this._animationTimeLast = now;
  15907. }
  15908. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  15909. this._animationTime += deltaTime;
  15910. this._animationTimeLast = now;
  15911. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15912. this._activeAnimatables[index]._animate(this._animationTime);
  15913. }
  15914. };
  15915. // Matrix
  15916. Scene.prototype.getViewMatrix = function () {
  15917. return this._viewMatrix;
  15918. };
  15919. Scene.prototype.getProjectionMatrix = function () {
  15920. return this._projectionMatrix;
  15921. };
  15922. Scene.prototype.getTransformMatrix = function () {
  15923. return this._transformMatrix;
  15924. };
  15925. Scene.prototype.setTransformMatrix = function (view, projection) {
  15926. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  15927. return;
  15928. }
  15929. this._viewUpdateFlag = view.updateFlag;
  15930. this._projectionUpdateFlag = projection.updateFlag;
  15931. this._viewMatrix = view;
  15932. this._projectionMatrix = projection;
  15933. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15934. // Update frustum
  15935. if (!this._frustumPlanes) {
  15936. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15937. }
  15938. else {
  15939. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15940. }
  15941. if (this._sceneUbo.useUbo) {
  15942. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  15943. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  15944. this._sceneUbo.update();
  15945. }
  15946. };
  15947. Scene.prototype.getSceneUniformBuffer = function () {
  15948. return this._sceneUbo;
  15949. };
  15950. // Methods
  15951. Scene.prototype.getUniqueId = function () {
  15952. var result = this._uniqueIdCounter;
  15953. this._uniqueIdCounter++;
  15954. return result;
  15955. };
  15956. Scene.prototype.addMesh = function (newMesh) {
  15957. newMesh.uniqueId = this.getUniqueId();
  15958. var position = this.meshes.push(newMesh);
  15959. //notify the collision coordinator
  15960. if (this.collisionCoordinator) {
  15961. this.collisionCoordinator.onMeshAdded(newMesh);
  15962. }
  15963. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  15964. };
  15965. Scene.prototype.removeMesh = function (toRemove) {
  15966. var index = this.meshes.indexOf(toRemove);
  15967. if (index !== -1) {
  15968. // Remove from the scene if mesh found
  15969. this.meshes.splice(index, 1);
  15970. }
  15971. //notify the collision coordinator
  15972. if (this.collisionCoordinator) {
  15973. this.collisionCoordinator.onMeshRemoved(toRemove);
  15974. }
  15975. this.onMeshRemovedObservable.notifyObservers(toRemove);
  15976. return index;
  15977. };
  15978. Scene.prototype.removeSkeleton = function (toRemove) {
  15979. var index = this.skeletons.indexOf(toRemove);
  15980. if (index !== -1) {
  15981. // Remove from the scene if found
  15982. this.skeletons.splice(index, 1);
  15983. }
  15984. return index;
  15985. };
  15986. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  15987. var index = this.morphTargetManagers.indexOf(toRemove);
  15988. if (index !== -1) {
  15989. // Remove from the scene if found
  15990. this.morphTargetManagers.splice(index, 1);
  15991. }
  15992. return index;
  15993. };
  15994. Scene.prototype.removeLight = function (toRemove) {
  15995. var index = this.lights.indexOf(toRemove);
  15996. if (index !== -1) {
  15997. // Remove from the scene if mesh found
  15998. this.lights.splice(index, 1);
  15999. }
  16000. this.onLightRemovedObservable.notifyObservers(toRemove);
  16001. return index;
  16002. };
  16003. Scene.prototype.removeCamera = function (toRemove) {
  16004. var index = this.cameras.indexOf(toRemove);
  16005. if (index !== -1) {
  16006. // Remove from the scene if mesh found
  16007. this.cameras.splice(index, 1);
  16008. }
  16009. // Remove from activeCameras
  16010. var index2 = this.activeCameras.indexOf(toRemove);
  16011. if (index2 !== -1) {
  16012. // Remove from the scene if mesh found
  16013. this.activeCameras.splice(index2, 1);
  16014. }
  16015. // Reset the activeCamera
  16016. if (this.activeCamera === toRemove) {
  16017. if (this.cameras.length > 0) {
  16018. this.activeCamera = this.cameras[0];
  16019. }
  16020. else {
  16021. this.activeCamera = null;
  16022. }
  16023. }
  16024. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16025. return index;
  16026. };
  16027. Scene.prototype.addLight = function (newLight) {
  16028. newLight.uniqueId = this.getUniqueId();
  16029. var position = this.lights.push(newLight);
  16030. this.onNewLightAddedObservable.notifyObservers(newLight);
  16031. };
  16032. Scene.prototype.addCamera = function (newCamera) {
  16033. newCamera.uniqueId = this.getUniqueId();
  16034. var position = this.cameras.push(newCamera);
  16035. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16036. };
  16037. /**
  16038. * Switch active camera
  16039. * @param {Camera} newCamera - new active camera
  16040. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16041. */
  16042. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16043. if (attachControl === void 0) { attachControl = true; }
  16044. var canvas = this._engine.getRenderingCanvas();
  16045. this.activeCamera.detachControl(canvas);
  16046. this.activeCamera = newCamera;
  16047. if (attachControl) {
  16048. newCamera.attachControl(canvas);
  16049. }
  16050. };
  16051. /**
  16052. * sets the active camera of the scene using its ID
  16053. * @param {string} id - the camera's ID
  16054. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16055. * @see activeCamera
  16056. */
  16057. Scene.prototype.setActiveCameraByID = function (id) {
  16058. var camera = this.getCameraByID(id);
  16059. if (camera) {
  16060. this.activeCamera = camera;
  16061. return camera;
  16062. }
  16063. return null;
  16064. };
  16065. /**
  16066. * sets the active camera of the scene using its name
  16067. * @param {string} name - the camera's name
  16068. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16069. * @see activeCamera
  16070. */
  16071. Scene.prototype.setActiveCameraByName = function (name) {
  16072. var camera = this.getCameraByName(name);
  16073. if (camera) {
  16074. this.activeCamera = camera;
  16075. return camera;
  16076. }
  16077. return null;
  16078. };
  16079. /**
  16080. * get a material using its id
  16081. * @param {string} the material's ID
  16082. * @return {BABYLON.Material|null} the material or null if none found.
  16083. */
  16084. Scene.prototype.getMaterialByID = function (id) {
  16085. for (var index = 0; index < this.materials.length; index++) {
  16086. if (this.materials[index].id === id) {
  16087. return this.materials[index];
  16088. }
  16089. }
  16090. return null;
  16091. };
  16092. /**
  16093. * get a material using its name
  16094. * @param {string} the material's name
  16095. * @return {BABYLON.Material|null} the material or null if none found.
  16096. */
  16097. Scene.prototype.getMaterialByName = function (name) {
  16098. for (var index = 0; index < this.materials.length; index++) {
  16099. if (this.materials[index].name === name) {
  16100. return this.materials[index];
  16101. }
  16102. }
  16103. return null;
  16104. };
  16105. Scene.prototype.getLensFlareSystemByName = function (name) {
  16106. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16107. if (this.lensFlareSystems[index].name === name) {
  16108. return this.lensFlareSystems[index];
  16109. }
  16110. }
  16111. return null;
  16112. };
  16113. Scene.prototype.getLensFlareSystemByID = function (id) {
  16114. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16115. if (this.lensFlareSystems[index].id === id) {
  16116. return this.lensFlareSystems[index];
  16117. }
  16118. }
  16119. return null;
  16120. };
  16121. Scene.prototype.getCameraByID = function (id) {
  16122. for (var index = 0; index < this.cameras.length; index++) {
  16123. if (this.cameras[index].id === id) {
  16124. return this.cameras[index];
  16125. }
  16126. }
  16127. return null;
  16128. };
  16129. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  16130. for (var index = 0; index < this.cameras.length; index++) {
  16131. if (this.cameras[index].uniqueId === uniqueId) {
  16132. return this.cameras[index];
  16133. }
  16134. }
  16135. return null;
  16136. };
  16137. /**
  16138. * get a camera using its name
  16139. * @param {string} the camera's name
  16140. * @return {BABYLON.Camera|null} the camera or null if none found.
  16141. */
  16142. Scene.prototype.getCameraByName = function (name) {
  16143. for (var index = 0; index < this.cameras.length; index++) {
  16144. if (this.cameras[index].name === name) {
  16145. return this.cameras[index];
  16146. }
  16147. }
  16148. return null;
  16149. };
  16150. /**
  16151. * get a bone using its id
  16152. * @param {string} the bone's id
  16153. * @return {BABYLON.Bone|null} the bone or null if not found
  16154. */
  16155. Scene.prototype.getBoneByID = function (id) {
  16156. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16157. var skeleton = this.skeletons[skeletonIndex];
  16158. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16159. if (skeleton.bones[boneIndex].id === id) {
  16160. return skeleton.bones[boneIndex];
  16161. }
  16162. }
  16163. }
  16164. return null;
  16165. };
  16166. /**
  16167. * get a bone using its id
  16168. * @param {string} the bone's name
  16169. * @return {BABYLON.Bone|null} the bone or null if not found
  16170. */
  16171. Scene.prototype.getBoneByName = function (name) {
  16172. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16173. var skeleton = this.skeletons[skeletonIndex];
  16174. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16175. if (skeleton.bones[boneIndex].name === name) {
  16176. return skeleton.bones[boneIndex];
  16177. }
  16178. }
  16179. }
  16180. return null;
  16181. };
  16182. /**
  16183. * get a light node using its name
  16184. * @param {string} the light's name
  16185. * @return {BABYLON.Light|null} the light or null if none found.
  16186. */
  16187. Scene.prototype.getLightByName = function (name) {
  16188. for (var index = 0; index < this.lights.length; index++) {
  16189. if (this.lights[index].name === name) {
  16190. return this.lights[index];
  16191. }
  16192. }
  16193. return null;
  16194. };
  16195. /**
  16196. * get a light node using its ID
  16197. * @param {string} the light's id
  16198. * @return {BABYLON.Light|null} the light or null if none found.
  16199. */
  16200. Scene.prototype.getLightByID = function (id) {
  16201. for (var index = 0; index < this.lights.length; index++) {
  16202. if (this.lights[index].id === id) {
  16203. return this.lights[index];
  16204. }
  16205. }
  16206. return null;
  16207. };
  16208. /**
  16209. * get a light node using its scene-generated unique ID
  16210. * @param {number} the light's unique id
  16211. * @return {BABYLON.Light|null} the light or null if none found.
  16212. */
  16213. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  16214. for (var index = 0; index < this.lights.length; index++) {
  16215. if (this.lights[index].uniqueId === uniqueId) {
  16216. return this.lights[index];
  16217. }
  16218. }
  16219. return null;
  16220. };
  16221. /**
  16222. * get a particle system by id
  16223. * @param id {number} the particle system id
  16224. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  16225. */
  16226. Scene.prototype.getParticleSystemByID = function (id) {
  16227. for (var index = 0; index < this.particleSystems.length; index++) {
  16228. if (this.particleSystems[index].id === id) {
  16229. return this.particleSystems[index];
  16230. }
  16231. }
  16232. return null;
  16233. };
  16234. /**
  16235. * get a geometry using its ID
  16236. * @param {string} the geometry's id
  16237. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  16238. */
  16239. Scene.prototype.getGeometryByID = function (id) {
  16240. for (var index = 0; index < this._geometries.length; index++) {
  16241. if (this._geometries[index].id === id) {
  16242. return this._geometries[index];
  16243. }
  16244. }
  16245. return null;
  16246. };
  16247. /**
  16248. * add a new geometry to this scene.
  16249. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  16250. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  16251. * @return {boolean} was the geometry added or not
  16252. */
  16253. Scene.prototype.pushGeometry = function (geometry, force) {
  16254. if (!force && this.getGeometryByID(geometry.id)) {
  16255. return false;
  16256. }
  16257. this._geometries.push(geometry);
  16258. //notify the collision coordinator
  16259. if (this.collisionCoordinator) {
  16260. this.collisionCoordinator.onGeometryAdded(geometry);
  16261. }
  16262. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  16263. return true;
  16264. };
  16265. /**
  16266. * Removes an existing geometry
  16267. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  16268. * @return {boolean} was the geometry removed or not
  16269. */
  16270. Scene.prototype.removeGeometry = function (geometry) {
  16271. var index = this._geometries.indexOf(geometry);
  16272. if (index > -1) {
  16273. this._geometries.splice(index, 1);
  16274. //notify the collision coordinator
  16275. if (this.collisionCoordinator) {
  16276. this.collisionCoordinator.onGeometryDeleted(geometry);
  16277. }
  16278. this.onGeometryRemovedObservable.notifyObservers(geometry);
  16279. return true;
  16280. }
  16281. return false;
  16282. };
  16283. Scene.prototype.getGeometries = function () {
  16284. return this._geometries;
  16285. };
  16286. /**
  16287. * Get the first added mesh found of a given ID
  16288. * @param {string} id - the id to search for
  16289. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16290. */
  16291. Scene.prototype.getMeshByID = function (id) {
  16292. for (var index = 0; index < this.meshes.length; index++) {
  16293. if (this.meshes[index].id === id) {
  16294. return this.meshes[index];
  16295. }
  16296. }
  16297. return null;
  16298. };
  16299. Scene.prototype.getMeshesByID = function (id) {
  16300. return this.meshes.filter(function (m) {
  16301. return m.id === id;
  16302. });
  16303. };
  16304. /**
  16305. * Get a mesh with its auto-generated unique id
  16306. * @param {number} uniqueId - the unique id to search for
  16307. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16308. */
  16309. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  16310. for (var index = 0; index < this.meshes.length; index++) {
  16311. if (this.meshes[index].uniqueId === uniqueId) {
  16312. return this.meshes[index];
  16313. }
  16314. }
  16315. return null;
  16316. };
  16317. /**
  16318. * Get a the last added mesh found of a given ID
  16319. * @param {string} id - the id to search for
  16320. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16321. */
  16322. Scene.prototype.getLastMeshByID = function (id) {
  16323. for (var index = this.meshes.length - 1; index >= 0; index--) {
  16324. if (this.meshes[index].id === id) {
  16325. return this.meshes[index];
  16326. }
  16327. }
  16328. return null;
  16329. };
  16330. /**
  16331. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  16332. * @param {string} id - the id to search for
  16333. * @return {BABYLON.Node|null} the node found or null if not found at all.
  16334. */
  16335. Scene.prototype.getLastEntryByID = function (id) {
  16336. var index;
  16337. for (index = this.meshes.length - 1; index >= 0; index--) {
  16338. if (this.meshes[index].id === id) {
  16339. return this.meshes[index];
  16340. }
  16341. }
  16342. for (index = this.cameras.length - 1; index >= 0; index--) {
  16343. if (this.cameras[index].id === id) {
  16344. return this.cameras[index];
  16345. }
  16346. }
  16347. for (index = this.lights.length - 1; index >= 0; index--) {
  16348. if (this.lights[index].id === id) {
  16349. return this.lights[index];
  16350. }
  16351. }
  16352. return null;
  16353. };
  16354. Scene.prototype.getNodeByID = function (id) {
  16355. var mesh = this.getMeshByID(id);
  16356. if (mesh) {
  16357. return mesh;
  16358. }
  16359. var light = this.getLightByID(id);
  16360. if (light) {
  16361. return light;
  16362. }
  16363. var camera = this.getCameraByID(id);
  16364. if (camera) {
  16365. return camera;
  16366. }
  16367. var bone = this.getBoneByID(id);
  16368. return bone;
  16369. };
  16370. Scene.prototype.getNodeByName = function (name) {
  16371. var mesh = this.getMeshByName(name);
  16372. if (mesh) {
  16373. return mesh;
  16374. }
  16375. var light = this.getLightByName(name);
  16376. if (light) {
  16377. return light;
  16378. }
  16379. var camera = this.getCameraByName(name);
  16380. if (camera) {
  16381. return camera;
  16382. }
  16383. var bone = this.getBoneByName(name);
  16384. return bone;
  16385. };
  16386. Scene.prototype.getMeshByName = function (name) {
  16387. for (var index = 0; index < this.meshes.length; index++) {
  16388. if (this.meshes[index].name === name) {
  16389. return this.meshes[index];
  16390. }
  16391. }
  16392. return null;
  16393. };
  16394. Scene.prototype.getSoundByName = function (name) {
  16395. var index;
  16396. if (BABYLON.AudioEngine) {
  16397. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  16398. if (this.mainSoundTrack.soundCollection[index].name === name) {
  16399. return this.mainSoundTrack.soundCollection[index];
  16400. }
  16401. }
  16402. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  16403. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  16404. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  16405. return this.soundTracks[sdIndex].soundCollection[index];
  16406. }
  16407. }
  16408. }
  16409. }
  16410. return null;
  16411. };
  16412. Scene.prototype.getLastSkeletonByID = function (id) {
  16413. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  16414. if (this.skeletons[index].id === id) {
  16415. return this.skeletons[index];
  16416. }
  16417. }
  16418. return null;
  16419. };
  16420. Scene.prototype.getSkeletonById = function (id) {
  16421. for (var index = 0; index < this.skeletons.length; index++) {
  16422. if (this.skeletons[index].id === id) {
  16423. return this.skeletons[index];
  16424. }
  16425. }
  16426. return null;
  16427. };
  16428. Scene.prototype.getSkeletonByName = function (name) {
  16429. for (var index = 0; index < this.skeletons.length; index++) {
  16430. if (this.skeletons[index].name === name) {
  16431. return this.skeletons[index];
  16432. }
  16433. }
  16434. return null;
  16435. };
  16436. Scene.prototype.getMorphTargetManagerById = function (id) {
  16437. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  16438. if (this.morphTargetManagers[index].uniqueId === id) {
  16439. return this.morphTargetManagers[index];
  16440. }
  16441. }
  16442. return null;
  16443. };
  16444. Scene.prototype.isActiveMesh = function (mesh) {
  16445. return (this._activeMeshes.indexOf(mesh) !== -1);
  16446. };
  16447. /**
  16448. * Return a the first highlight layer of the scene with a given name.
  16449. * @param name The name of the highlight layer to look for.
  16450. * @return The highlight layer if found otherwise null.
  16451. */
  16452. Scene.prototype.getHighlightLayerByName = function (name) {
  16453. for (var index = 0; index < this.highlightLayers.length; index++) {
  16454. if (this.highlightLayers[index].name === name) {
  16455. return this.highlightLayers[index];
  16456. }
  16457. }
  16458. return null;
  16459. };
  16460. Object.defineProperty(Scene.prototype, "uid", {
  16461. /**
  16462. * Return a unique id as a string which can serve as an identifier for the scene
  16463. */
  16464. get: function () {
  16465. if (!this._uid) {
  16466. this._uid = BABYLON.Tools.RandomId();
  16467. }
  16468. return this._uid;
  16469. },
  16470. enumerable: true,
  16471. configurable: true
  16472. });
  16473. /**
  16474. * Add an externaly attached data from its key.
  16475. * This method call will fail and return false, if such key already exists.
  16476. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16477. * @param key the unique key that identifies the data
  16478. * @param data the data object to associate to the key for this Engine instance
  16479. * @return true if no such key were already present and the data was added successfully, false otherwise
  16480. */
  16481. Scene.prototype.addExternalData = function (key, data) {
  16482. if (!this._externalData) {
  16483. this._externalData = new BABYLON.StringDictionary();
  16484. }
  16485. return this._externalData.add(key, data);
  16486. };
  16487. /**
  16488. * Get an externaly attached data from its key
  16489. * @param key the unique key that identifies the data
  16490. * @return the associated data, if present (can be null), or undefined if not present
  16491. */
  16492. Scene.prototype.getExternalData = function (key) {
  16493. if (!this._externalData) {
  16494. return null;
  16495. }
  16496. return this._externalData.get(key);
  16497. };
  16498. /**
  16499. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16500. * @param key the unique key that identifies the data
  16501. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16502. * @return the associated data, can be null if the factory returned null.
  16503. */
  16504. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16505. if (!this._externalData) {
  16506. this._externalData = new BABYLON.StringDictionary();
  16507. }
  16508. return this._externalData.getOrAddWithFactory(key, factory);
  16509. };
  16510. /**
  16511. * Remove an externaly attached data from the Engine instance
  16512. * @param key the unique key that identifies the data
  16513. * @return true if the data was successfully removed, false if it doesn't exist
  16514. */
  16515. Scene.prototype.removeExternalData = function (key) {
  16516. return this._externalData.remove(key);
  16517. };
  16518. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  16519. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  16520. var material = subMesh.getMaterial();
  16521. if (mesh.showSubMeshesBoundingBox) {
  16522. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  16523. }
  16524. if (material) {
  16525. // Render targets
  16526. if (material.getRenderTargetTextures) {
  16527. if (this._processedMaterials.indexOf(material) === -1) {
  16528. this._processedMaterials.push(material);
  16529. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  16530. }
  16531. }
  16532. // Dispatch
  16533. this._activeIndices.addCount(subMesh.indexCount, false);
  16534. this._renderingManager.dispatch(subMesh);
  16535. }
  16536. }
  16537. };
  16538. Scene.prototype._isInIntermediateRendering = function () {
  16539. return this._intermediateRendering;
  16540. };
  16541. Scene.prototype._evaluateActiveMeshes = function () {
  16542. this.activeCamera._activeMeshes.reset();
  16543. this._activeMeshes.reset();
  16544. this._renderingManager.reset();
  16545. this._processedMaterials.reset();
  16546. this._activeParticleSystems.reset();
  16547. this._activeSkeletons.reset();
  16548. this._softwareSkinnedMeshes.reset();
  16549. if (this._boundingBoxRenderer) {
  16550. this._boundingBoxRenderer.reset();
  16551. }
  16552. this._edgesRenderers.reset();
  16553. // Meshes
  16554. var meshes;
  16555. var len;
  16556. if (this._selectionOctree) {
  16557. var selection = this._selectionOctree.select(this._frustumPlanes);
  16558. meshes = selection.data;
  16559. len = selection.length;
  16560. }
  16561. else {
  16562. len = this.meshes.length;
  16563. meshes = this.meshes;
  16564. }
  16565. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  16566. var mesh = meshes[meshIndex];
  16567. if (mesh.isBlocked) {
  16568. continue;
  16569. }
  16570. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  16571. if (!mesh.isReady() || !mesh.isEnabled()) {
  16572. continue;
  16573. }
  16574. mesh.computeWorldMatrix();
  16575. // Intersections
  16576. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  16577. this._meshesForIntersections.pushNoDuplicate(mesh);
  16578. }
  16579. // Switch to current LOD
  16580. var meshLOD = mesh.getLOD(this.activeCamera);
  16581. if (!meshLOD) {
  16582. continue;
  16583. }
  16584. mesh._preActivate();
  16585. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  16586. this._activeMeshes.push(mesh);
  16587. this.activeCamera._activeMeshes.push(mesh);
  16588. mesh._activate(this._renderId);
  16589. this._activeMesh(mesh, meshLOD);
  16590. }
  16591. }
  16592. // Particle systems
  16593. this._particlesDuration.beginMonitoring();
  16594. var beforeParticlesDate = BABYLON.Tools.Now;
  16595. if (this.particlesEnabled) {
  16596. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  16597. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  16598. var particleSystem = this.particleSystems[particleIndex];
  16599. if (!particleSystem.isStarted()) {
  16600. continue;
  16601. }
  16602. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  16603. this._activeParticleSystems.push(particleSystem);
  16604. particleSystem.animate();
  16605. this._renderingManager.dispatchParticles(particleSystem);
  16606. }
  16607. }
  16608. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  16609. }
  16610. this._particlesDuration.endMonitoring(false);
  16611. };
  16612. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  16613. if (mesh.skeleton && this.skeletonsEnabled) {
  16614. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  16615. mesh.skeleton.prepare();
  16616. }
  16617. if (!mesh.computeBonesUsingShaders) {
  16618. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  16619. }
  16620. }
  16621. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  16622. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  16623. }
  16624. if (sourceMesh._edgesRenderer) {
  16625. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  16626. }
  16627. if (mesh && mesh.subMeshes) {
  16628. // Submeshes Octrees
  16629. var len;
  16630. var subMeshes;
  16631. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  16632. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  16633. len = intersections.length;
  16634. subMeshes = intersections.data;
  16635. }
  16636. else {
  16637. subMeshes = mesh.subMeshes;
  16638. len = subMeshes.length;
  16639. }
  16640. for (var subIndex = 0; subIndex < len; subIndex++) {
  16641. var subMesh = subMeshes[subIndex];
  16642. this._evaluateSubMesh(subMesh, mesh);
  16643. }
  16644. }
  16645. };
  16646. Scene.prototype.updateTransformMatrix = function (force) {
  16647. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  16648. };
  16649. Scene.prototype._renderForCamera = function (camera) {
  16650. var engine = this._engine;
  16651. var startTime = BABYLON.Tools.Now;
  16652. this.activeCamera = camera;
  16653. if (!this.activeCamera)
  16654. throw new Error("Active camera not set");
  16655. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16656. // Viewport
  16657. engine.setViewport(this.activeCamera.viewport);
  16658. // Camera
  16659. this.resetCachedMaterial();
  16660. this._renderId++;
  16661. this.updateTransformMatrix();
  16662. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  16663. // Meshes
  16664. this._evaluateActiveMeshesDuration.beginMonitoring();
  16665. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  16666. this._evaluateActiveMeshes();
  16667. this._evaluateActiveMeshesDuration.endMonitoring(false);
  16668. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  16669. // Software skinning
  16670. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  16671. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  16672. mesh.applySkeleton(mesh.skeleton);
  16673. }
  16674. // Render targets
  16675. this._renderTargetsDuration.beginMonitoring();
  16676. var needsRestoreFrameBuffer = false;
  16677. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16678. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  16679. this._intermediateRendering = true;
  16680. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16681. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  16682. var renderTarget = this._renderTargets.data[renderIndex];
  16683. if (renderTarget._shouldRender()) {
  16684. this._renderId++;
  16685. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  16686. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  16687. }
  16688. }
  16689. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16690. this._intermediateRendering = false;
  16691. this._renderId++;
  16692. needsRestoreFrameBuffer = true; // Restore back buffer
  16693. }
  16694. // Render HighlightLayer Texture
  16695. var stencilState = this._engine.getStencilBuffer();
  16696. var renderhighlights = false;
  16697. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  16698. this._intermediateRendering = true;
  16699. for (var i = 0; i < this.highlightLayers.length; i++) {
  16700. var highlightLayer = this.highlightLayers[i];
  16701. if (highlightLayer.shouldRender() &&
  16702. (!highlightLayer.camera ||
  16703. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  16704. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  16705. renderhighlights = true;
  16706. var renderTarget = highlightLayer._mainTexture;
  16707. if (renderTarget._shouldRender()) {
  16708. this._renderId++;
  16709. renderTarget.render(false, false);
  16710. needsRestoreFrameBuffer = true;
  16711. }
  16712. }
  16713. }
  16714. this._intermediateRendering = false;
  16715. this._renderId++;
  16716. }
  16717. if (needsRestoreFrameBuffer) {
  16718. engine.restoreDefaultFramebuffer();
  16719. }
  16720. this._renderTargetsDuration.endMonitoring(false);
  16721. // Prepare Frame
  16722. this.postProcessManager._prepareFrame();
  16723. this._renderDuration.beginMonitoring();
  16724. // Backgrounds
  16725. var layerIndex;
  16726. var layer;
  16727. if (this.layers.length) {
  16728. engine.setDepthBuffer(false);
  16729. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16730. layer = this.layers[layerIndex];
  16731. if (layer.isBackground) {
  16732. layer.render();
  16733. }
  16734. }
  16735. engine.setDepthBuffer(true);
  16736. }
  16737. // Render
  16738. BABYLON.Tools.StartPerformanceCounter("Main render");
  16739. // Activate HighlightLayer stencil
  16740. if (renderhighlights) {
  16741. this._engine.setStencilBuffer(true);
  16742. }
  16743. this._renderingManager.render(null, null, true, true);
  16744. // Restore HighlightLayer stencil
  16745. if (renderhighlights) {
  16746. this._engine.setStencilBuffer(stencilState);
  16747. }
  16748. BABYLON.Tools.EndPerformanceCounter("Main render");
  16749. // Bounding boxes
  16750. if (this._boundingBoxRenderer) {
  16751. this._boundingBoxRenderer.render();
  16752. }
  16753. // Edges
  16754. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16755. this._edgesRenderers.data[edgesRendererIndex].render();
  16756. }
  16757. // Lens flares
  16758. if (this.lensFlaresEnabled) {
  16759. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16760. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  16761. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  16762. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  16763. lensFlareSystem.render();
  16764. }
  16765. }
  16766. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16767. }
  16768. // Foregrounds
  16769. if (this.layers.length) {
  16770. engine.setDepthBuffer(false);
  16771. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16772. layer = this.layers[layerIndex];
  16773. if (!layer.isBackground) {
  16774. layer.render();
  16775. }
  16776. }
  16777. engine.setDepthBuffer(true);
  16778. }
  16779. // Highlight Layer
  16780. if (renderhighlights) {
  16781. engine.setDepthBuffer(false);
  16782. for (var i = 0; i < this.highlightLayers.length; i++) {
  16783. if (this.highlightLayers[i].shouldRender()) {
  16784. this.highlightLayers[i].render();
  16785. }
  16786. }
  16787. engine.setDepthBuffer(true);
  16788. }
  16789. this._renderDuration.endMonitoring(false);
  16790. // Finalize frame
  16791. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  16792. // Update camera
  16793. this.activeCamera._updateFromScene();
  16794. // Reset some special arrays
  16795. this._renderTargets.reset();
  16796. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  16797. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16798. };
  16799. Scene.prototype._processSubCameras = function (camera) {
  16800. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  16801. this._renderForCamera(camera);
  16802. return;
  16803. }
  16804. // rig cameras
  16805. for (var index = 0; index < camera._rigCameras.length; index++) {
  16806. this._renderForCamera(camera._rigCameras[index]);
  16807. }
  16808. this.activeCamera = camera;
  16809. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  16810. // Update camera
  16811. this.activeCamera._updateFromScene();
  16812. };
  16813. Scene.prototype._checkIntersections = function () {
  16814. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  16815. var sourceMesh = this._meshesForIntersections.data[index];
  16816. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  16817. var action = sourceMesh.actionManager.actions[actionIndex];
  16818. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16819. var parameters = action.getTriggerParameter();
  16820. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  16821. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  16822. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  16823. if (areIntersecting && currentIntersectionInProgress === -1) {
  16824. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  16825. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16826. sourceMesh._intersectionsInProgress.push(otherMesh);
  16827. }
  16828. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16829. sourceMesh._intersectionsInProgress.push(otherMesh);
  16830. }
  16831. }
  16832. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  16833. //They intersected, and now they don't.
  16834. //is this trigger an exit trigger? execute an event.
  16835. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16836. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16837. }
  16838. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  16839. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16840. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  16841. }
  16842. }
  16843. }
  16844. }
  16845. }
  16846. };
  16847. Scene.prototype.render = function () {
  16848. if (this.isDisposed) {
  16849. return;
  16850. }
  16851. this._lastFrameDuration.beginMonitoring();
  16852. this._particlesDuration.fetchNewFrame();
  16853. this._spritesDuration.fetchNewFrame();
  16854. this._activeParticles.fetchNewFrame();
  16855. this._renderDuration.fetchNewFrame();
  16856. this._renderTargetsDuration.fetchNewFrame();
  16857. this._evaluateActiveMeshesDuration.fetchNewFrame();
  16858. this._totalVertices.fetchNewFrame();
  16859. this._activeIndices.fetchNewFrame();
  16860. this._activeBones.fetchNewFrame();
  16861. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  16862. this._meshesForIntersections.reset();
  16863. this.resetCachedMaterial();
  16864. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  16865. // Actions
  16866. if (this.actionManager) {
  16867. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  16868. }
  16869. //Simplification Queue
  16870. if (this.simplificationQueue && !this.simplificationQueue.running) {
  16871. this.simplificationQueue.executeNext();
  16872. }
  16873. // Animations
  16874. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  16875. this._animationRatio = deltaTime * (60.0 / 1000.0);
  16876. this._animate();
  16877. // Physics
  16878. if (this._physicsEngine) {
  16879. BABYLON.Tools.StartPerformanceCounter("Physics");
  16880. this._physicsEngine._step(deltaTime / 1000.0);
  16881. BABYLON.Tools.EndPerformanceCounter("Physics");
  16882. }
  16883. // Before render
  16884. this.onBeforeRenderObservable.notifyObservers(this);
  16885. // Customs render targets
  16886. this._renderTargetsDuration.beginMonitoring();
  16887. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16888. var engine = this.getEngine();
  16889. var currentActiveCamera = this.activeCamera;
  16890. if (this.renderTargetsEnabled) {
  16891. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16892. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  16893. var renderTarget = this.customRenderTargets[customIndex];
  16894. if (renderTarget._shouldRender()) {
  16895. this._renderId++;
  16896. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  16897. if (!this.activeCamera)
  16898. throw new Error("Active camera not set");
  16899. // Viewport
  16900. engine.setViewport(this.activeCamera.viewport);
  16901. // Camera
  16902. this.updateTransformMatrix();
  16903. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  16904. }
  16905. }
  16906. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16907. this._renderId++;
  16908. }
  16909. if (this.customRenderTargets.length > 0) {
  16910. engine.restoreDefaultFramebuffer();
  16911. }
  16912. this._renderTargetsDuration.endMonitoring();
  16913. this.activeCamera = currentActiveCamera;
  16914. // Procedural textures
  16915. if (this.proceduralTexturesEnabled) {
  16916. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16917. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  16918. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  16919. if (proceduralTexture._shouldRender()) {
  16920. proceduralTexture.render();
  16921. }
  16922. }
  16923. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16924. }
  16925. // Clear
  16926. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  16927. // Shadows
  16928. if (this.shadowsEnabled) {
  16929. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  16930. var light = this.lights[lightIndex];
  16931. var shadowGenerator = light.getShadowGenerator();
  16932. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  16933. this._renderTargets.push(shadowGenerator.getShadowMap());
  16934. }
  16935. }
  16936. }
  16937. // Depth renderer
  16938. if (this._depthRenderer) {
  16939. this._renderTargets.push(this._depthRenderer.getDepthMap());
  16940. }
  16941. // RenderPipeline
  16942. if (this._postProcessRenderPipelineManager) {
  16943. this._postProcessRenderPipelineManager.update();
  16944. }
  16945. // Multi-cameras?
  16946. if (this.activeCameras.length > 0) {
  16947. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  16948. if (cameraIndex > 0) {
  16949. this._engine.clear(null, false, true, true);
  16950. }
  16951. this._processSubCameras(this.activeCameras[cameraIndex]);
  16952. }
  16953. }
  16954. else {
  16955. if (!this.activeCamera) {
  16956. throw new Error("No camera defined");
  16957. }
  16958. this._processSubCameras(this.activeCamera);
  16959. }
  16960. // Intersection checks
  16961. this._checkIntersections();
  16962. // Update the audio listener attached to the camera
  16963. if (BABYLON.AudioEngine) {
  16964. this._updateAudioParameters();
  16965. }
  16966. // After render
  16967. if (this.afterRender) {
  16968. this.afterRender();
  16969. }
  16970. this.onAfterRenderObservable.notifyObservers(this);
  16971. // Cleaning
  16972. for (var index = 0; index < this._toBeDisposed.length; index++) {
  16973. this._toBeDisposed.data[index].dispose();
  16974. this._toBeDisposed[index] = null;
  16975. }
  16976. this._toBeDisposed.reset();
  16977. if (this.dumpNextRenderTargets) {
  16978. this.dumpNextRenderTargets = false;
  16979. }
  16980. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  16981. this._lastFrameDuration.endMonitoring();
  16982. this._totalMeshesCounter.addCount(this.meshes.length, true);
  16983. this._totalLightsCounter.addCount(this.lights.length, true);
  16984. this._totalMaterialsCounter.addCount(this.materials.length, true);
  16985. this._totalTexturesCounter.addCount(this.textures.length, true);
  16986. this._activeBones.addCount(0, true);
  16987. this._activeIndices.addCount(0, true);
  16988. this._activeParticles.addCount(0, true);
  16989. };
  16990. Scene.prototype._updateAudioParameters = function () {
  16991. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  16992. return;
  16993. }
  16994. var listeningCamera;
  16995. var audioEngine = BABYLON.Engine.audioEngine;
  16996. if (this.activeCameras.length > 0) {
  16997. listeningCamera = this.activeCameras[0];
  16998. }
  16999. else {
  17000. listeningCamera = this.activeCamera;
  17001. }
  17002. if (listeningCamera && audioEngine.canUseWebAudio) {
  17003. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  17004. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  17005. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  17006. cameraDirection.normalize();
  17007. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  17008. var i;
  17009. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17010. var sound = this.mainSoundTrack.soundCollection[i];
  17011. if (sound.useCustomAttenuation) {
  17012. sound.updateDistanceFromListener();
  17013. }
  17014. }
  17015. for (i = 0; i < this.soundTracks.length; i++) {
  17016. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17017. sound = this.soundTracks[i].soundCollection[j];
  17018. if (sound.useCustomAttenuation) {
  17019. sound.updateDistanceFromListener();
  17020. }
  17021. }
  17022. }
  17023. }
  17024. };
  17025. Object.defineProperty(Scene.prototype, "audioEnabled", {
  17026. // Audio
  17027. get: function () {
  17028. return this._audioEnabled;
  17029. },
  17030. set: function (value) {
  17031. this._audioEnabled = value;
  17032. if (BABYLON.AudioEngine) {
  17033. if (this._audioEnabled) {
  17034. this._enableAudio();
  17035. }
  17036. else {
  17037. this._disableAudio();
  17038. }
  17039. }
  17040. },
  17041. enumerable: true,
  17042. configurable: true
  17043. });
  17044. Scene.prototype._disableAudio = function () {
  17045. var i;
  17046. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17047. this.mainSoundTrack.soundCollection[i].pause();
  17048. }
  17049. for (i = 0; i < this.soundTracks.length; i++) {
  17050. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17051. this.soundTracks[i].soundCollection[j].pause();
  17052. }
  17053. }
  17054. };
  17055. Scene.prototype._enableAudio = function () {
  17056. var i;
  17057. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17058. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  17059. this.mainSoundTrack.soundCollection[i].play();
  17060. }
  17061. }
  17062. for (i = 0; i < this.soundTracks.length; i++) {
  17063. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17064. if (this.soundTracks[i].soundCollection[j].isPaused) {
  17065. this.soundTracks[i].soundCollection[j].play();
  17066. }
  17067. }
  17068. }
  17069. };
  17070. Object.defineProperty(Scene.prototype, "headphone", {
  17071. get: function () {
  17072. return this._headphone;
  17073. },
  17074. set: function (value) {
  17075. this._headphone = value;
  17076. if (BABYLON.AudioEngine) {
  17077. if (this._headphone) {
  17078. this._switchAudioModeForHeadphones();
  17079. }
  17080. else {
  17081. this._switchAudioModeForNormalSpeakers();
  17082. }
  17083. }
  17084. },
  17085. enumerable: true,
  17086. configurable: true
  17087. });
  17088. Scene.prototype._switchAudioModeForHeadphones = function () {
  17089. this.mainSoundTrack.switchPanningModelToHRTF();
  17090. for (var i = 0; i < this.soundTracks.length; i++) {
  17091. this.soundTracks[i].switchPanningModelToHRTF();
  17092. }
  17093. };
  17094. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  17095. this.mainSoundTrack.switchPanningModelToEqualPower();
  17096. for (var i = 0; i < this.soundTracks.length; i++) {
  17097. this.soundTracks[i].switchPanningModelToEqualPower();
  17098. }
  17099. };
  17100. Scene.prototype.enableDepthRenderer = function () {
  17101. if (this._depthRenderer) {
  17102. return this._depthRenderer;
  17103. }
  17104. this._depthRenderer = new BABYLON.DepthRenderer(this);
  17105. return this._depthRenderer;
  17106. };
  17107. Scene.prototype.disableDepthRenderer = function () {
  17108. if (!this._depthRenderer) {
  17109. return;
  17110. }
  17111. this._depthRenderer.dispose();
  17112. this._depthRenderer = null;
  17113. };
  17114. Scene.prototype.freezeMaterials = function () {
  17115. for (var i = 0; i < this.materials.length; i++) {
  17116. this.materials[i].freeze();
  17117. }
  17118. };
  17119. Scene.prototype.unfreezeMaterials = function () {
  17120. for (var i = 0; i < this.materials.length; i++) {
  17121. this.materials[i].unfreeze();
  17122. }
  17123. };
  17124. Scene.prototype.dispose = function () {
  17125. this.beforeRender = null;
  17126. this.afterRender = null;
  17127. this.skeletons = [];
  17128. this.morphTargetManagers = [];
  17129. this.importedMeshesFiles = new Array();
  17130. if (this._depthRenderer) {
  17131. this._depthRenderer.dispose();
  17132. }
  17133. // Smart arrays
  17134. if (this.activeCamera) {
  17135. this.activeCamera._activeMeshes.dispose();
  17136. this.activeCamera = null;
  17137. }
  17138. this._activeMeshes.dispose();
  17139. this._renderingManager.dispose();
  17140. this._processedMaterials.dispose();
  17141. this._activeParticleSystems.dispose();
  17142. this._activeSkeletons.dispose();
  17143. this._softwareSkinnedMeshes.dispose();
  17144. if (this._boundingBoxRenderer) {
  17145. this._boundingBoxRenderer.dispose();
  17146. }
  17147. this._edgesRenderers.dispose();
  17148. this._meshesForIntersections.dispose();
  17149. this._toBeDisposed.dispose();
  17150. // Debug layer
  17151. if (this._debugLayer) {
  17152. this._debugLayer.hide();
  17153. }
  17154. // Events
  17155. this.onDisposeObservable.notifyObservers(this);
  17156. this.onDisposeObservable.clear();
  17157. this.onBeforeRenderObservable.clear();
  17158. this.onAfterRenderObservable.clear();
  17159. this.detachControl();
  17160. // Release sounds & sounds tracks
  17161. if (BABYLON.AudioEngine) {
  17162. this.disposeSounds();
  17163. }
  17164. // Detach cameras
  17165. var canvas = this._engine.getRenderingCanvas();
  17166. var index;
  17167. for (index = 0; index < this.cameras.length; index++) {
  17168. this.cameras[index].detachControl(canvas);
  17169. }
  17170. // Release lights
  17171. while (this.lights.length) {
  17172. this.lights[0].dispose();
  17173. }
  17174. // Release meshes
  17175. while (this.meshes.length) {
  17176. this.meshes[0].dispose(true);
  17177. }
  17178. // Release cameras
  17179. while (this.cameras.length) {
  17180. this.cameras[0].dispose();
  17181. }
  17182. // Release materials
  17183. while (this.materials.length) {
  17184. this.materials[0].dispose();
  17185. }
  17186. // Release particles
  17187. while (this.particleSystems.length) {
  17188. this.particleSystems[0].dispose();
  17189. }
  17190. // Release sprites
  17191. while (this.spriteManagers.length) {
  17192. this.spriteManagers[0].dispose();
  17193. }
  17194. // Release layers
  17195. while (this.layers.length) {
  17196. this.layers[0].dispose();
  17197. }
  17198. while (this.highlightLayers.length) {
  17199. this.highlightLayers[0].dispose();
  17200. }
  17201. // Release textures
  17202. while (this.textures.length) {
  17203. this.textures[0].dispose();
  17204. }
  17205. // Release UBO
  17206. this._sceneUbo.dispose();
  17207. // Post-processes
  17208. this.postProcessManager.dispose();
  17209. // Physics
  17210. if (this._physicsEngine) {
  17211. this.disablePhysicsEngine();
  17212. }
  17213. // Remove from engine
  17214. index = this._engine.scenes.indexOf(this);
  17215. if (index > -1) {
  17216. this._engine.scenes.splice(index, 1);
  17217. }
  17218. this._engine.wipeCaches();
  17219. this._engine = null;
  17220. };
  17221. Object.defineProperty(Scene.prototype, "isDisposed", {
  17222. get: function () {
  17223. return !this._engine;
  17224. },
  17225. enumerable: true,
  17226. configurable: true
  17227. });
  17228. // Release sounds & sounds tracks
  17229. Scene.prototype.disposeSounds = function () {
  17230. this.mainSoundTrack.dispose();
  17231. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  17232. this.soundTracks[scIndex].dispose();
  17233. }
  17234. };
  17235. // Octrees
  17236. Scene.prototype.getWorldExtends = function () {
  17237. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17238. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17239. for (var index = 0; index < this.meshes.length; index++) {
  17240. var mesh = this.meshes[index];
  17241. mesh.computeWorldMatrix(true);
  17242. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  17243. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  17244. BABYLON.Tools.CheckExtends(minBox, min, max);
  17245. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17246. }
  17247. return {
  17248. min: min,
  17249. max: max
  17250. };
  17251. };
  17252. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  17253. if (maxCapacity === void 0) { maxCapacity = 64; }
  17254. if (maxDepth === void 0) { maxDepth = 2; }
  17255. if (!this._selectionOctree) {
  17256. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  17257. }
  17258. var worldExtends = this.getWorldExtends();
  17259. // Update octree
  17260. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  17261. return this._selectionOctree;
  17262. };
  17263. // Picking
  17264. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  17265. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  17266. var engine = this._engine;
  17267. if (!camera) {
  17268. if (!this.activeCamera)
  17269. throw new Error("Active camera not set");
  17270. camera = this.activeCamera;
  17271. }
  17272. var cameraViewport = camera.viewport;
  17273. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17274. // Moving coordinates to local viewport world
  17275. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17276. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17277. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  17278. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  17279. };
  17280. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  17281. if (!BABYLON.PickingInfo) {
  17282. return null;
  17283. }
  17284. var engine = this._engine;
  17285. if (!camera) {
  17286. if (!this.activeCamera)
  17287. throw new Error("Active camera not set");
  17288. camera = this.activeCamera;
  17289. }
  17290. var cameraViewport = camera.viewport;
  17291. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17292. var identity = BABYLON.Matrix.Identity();
  17293. // Moving coordinates to local viewport world
  17294. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17295. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17296. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  17297. };
  17298. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  17299. if (!BABYLON.PickingInfo) {
  17300. return null;
  17301. }
  17302. var pickingInfo = null;
  17303. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  17304. var mesh = this.meshes[meshIndex];
  17305. if (predicate) {
  17306. if (!predicate(mesh)) {
  17307. continue;
  17308. }
  17309. }
  17310. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  17311. continue;
  17312. }
  17313. var world = mesh.getWorldMatrix();
  17314. var ray = rayFunction(world);
  17315. var result = mesh.intersects(ray, fastCheck);
  17316. if (!result || !result.hit)
  17317. continue;
  17318. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17319. continue;
  17320. pickingInfo = result;
  17321. if (fastCheck) {
  17322. break;
  17323. }
  17324. }
  17325. return pickingInfo || new BABYLON.PickingInfo();
  17326. };
  17327. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  17328. if (!BABYLON.PickingInfo) {
  17329. return null;
  17330. }
  17331. var pickingInfos = new Array();
  17332. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  17333. var mesh = this.meshes[meshIndex];
  17334. if (predicate) {
  17335. if (!predicate(mesh)) {
  17336. continue;
  17337. }
  17338. }
  17339. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  17340. continue;
  17341. }
  17342. var world = mesh.getWorldMatrix();
  17343. var ray = rayFunction(world);
  17344. var result = mesh.intersects(ray, false);
  17345. if (!result || !result.hit)
  17346. continue;
  17347. pickingInfos.push(result);
  17348. }
  17349. return pickingInfos;
  17350. };
  17351. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  17352. if (!BABYLON.PickingInfo) {
  17353. return null;
  17354. }
  17355. var pickingInfo = null;
  17356. camera = camera || this.activeCamera;
  17357. if (this.spriteManagers.length > 0) {
  17358. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  17359. var spriteManager = this.spriteManagers[spriteIndex];
  17360. if (!spriteManager.isPickable) {
  17361. continue;
  17362. }
  17363. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  17364. if (!result || !result.hit)
  17365. continue;
  17366. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17367. continue;
  17368. pickingInfo = result;
  17369. if (fastCheck) {
  17370. break;
  17371. }
  17372. }
  17373. }
  17374. return pickingInfo || new BABYLON.PickingInfo();
  17375. };
  17376. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17377. /// <param name="x">X position on screen</param>
  17378. /// <param name="y">Y position on screen</param>
  17379. /// <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>
  17380. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17381. /// <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>
  17382. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  17383. var _this = this;
  17384. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  17385. };
  17386. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17387. /// <param name="x">X position on screen</param>
  17388. /// <param name="y">Y position on screen</param>
  17389. /// <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>
  17390. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17391. /// <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>
  17392. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  17393. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  17394. };
  17395. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  17396. var _this = this;
  17397. return this._internalPick(function (world) {
  17398. if (!_this._pickWithRayInverseMatrix) {
  17399. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  17400. }
  17401. world.invertToRef(_this._pickWithRayInverseMatrix);
  17402. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  17403. }, predicate, fastCheck);
  17404. };
  17405. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17406. /// <param name="x">X position on screen</param>
  17407. /// <param name="y">Y position on screen</param>
  17408. /// <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>
  17409. /// <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>
  17410. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  17411. var _this = this;
  17412. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  17413. };
  17414. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17415. /// <param name="ray">Ray to use</param>
  17416. /// <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>
  17417. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  17418. var _this = this;
  17419. return this._internalMultiPick(function (world) {
  17420. if (!_this._pickWithRayInverseMatrix) {
  17421. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  17422. }
  17423. world.invertToRef(_this._pickWithRayInverseMatrix);
  17424. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  17425. }, predicate);
  17426. };
  17427. Scene.prototype.setPointerOverMesh = function (mesh) {
  17428. if (this._pointerOverMesh === mesh) {
  17429. return;
  17430. }
  17431. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17432. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17433. }
  17434. this._pointerOverMesh = mesh;
  17435. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17436. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17437. }
  17438. };
  17439. Scene.prototype.getPointerOverMesh = function () {
  17440. return this._pointerOverMesh;
  17441. };
  17442. Scene.prototype.setPointerOverSprite = function (sprite) {
  17443. if (this._pointerOverSprite === sprite) {
  17444. return;
  17445. }
  17446. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17447. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17448. }
  17449. this._pointerOverSprite = sprite;
  17450. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17451. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17452. }
  17453. };
  17454. Scene.prototype.getPointerOverSprite = function () {
  17455. return this._pointerOverSprite;
  17456. };
  17457. // Physics
  17458. Scene.prototype.getPhysicsEngine = function () {
  17459. return this._physicsEngine;
  17460. };
  17461. /**
  17462. * Enables physics to the current scene
  17463. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  17464. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  17465. * @return {boolean} was the physics engine initialized
  17466. */
  17467. Scene.prototype.enablePhysics = function (gravity, plugin) {
  17468. if (this._physicsEngine) {
  17469. return true;
  17470. }
  17471. try {
  17472. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  17473. return true;
  17474. }
  17475. catch (e) {
  17476. BABYLON.Tools.Error(e.message);
  17477. return false;
  17478. }
  17479. };
  17480. Scene.prototype.disablePhysicsEngine = function () {
  17481. if (!this._physicsEngine) {
  17482. return;
  17483. }
  17484. this._physicsEngine.dispose();
  17485. this._physicsEngine = undefined;
  17486. };
  17487. Scene.prototype.isPhysicsEnabled = function () {
  17488. return this._physicsEngine !== undefined;
  17489. };
  17490. Scene.prototype.deleteCompoundImpostor = function (compound) {
  17491. var mesh = compound.parts[0].mesh;
  17492. mesh.physicsImpostor.dispose();
  17493. mesh.physicsImpostor = null;
  17494. };
  17495. // Misc.
  17496. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  17497. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  17498. // Light
  17499. if (this.lights.length === 0) {
  17500. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  17501. }
  17502. // Camera
  17503. if (!this.activeCamera) {
  17504. var worldExtends = this.getWorldExtends();
  17505. var worldSize = worldExtends.max.subtract(worldExtends.min);
  17506. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  17507. var camera;
  17508. var radius = worldSize.length() * 1.5;
  17509. if (createArcRotateCamera) {
  17510. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", 4.712, 1.571, radius, worldCenter, this);
  17511. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  17512. arcRotateCamera.wheelPrecision = 100 / radius;
  17513. camera = arcRotateCamera;
  17514. }
  17515. else {
  17516. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, this.useRightHandedSystem ? -radius : radius), this);
  17517. freeCamera.setTarget(worldCenter);
  17518. camera = freeCamera;
  17519. }
  17520. camera.minZ = radius * 0.01;
  17521. camera.maxZ = radius * 100;
  17522. camera.speed = radius * 0.2;
  17523. this.activeCamera = camera;
  17524. }
  17525. };
  17526. // Tags
  17527. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  17528. if (tagsQuery === undefined) {
  17529. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  17530. return list;
  17531. }
  17532. var listByTags = [];
  17533. forEach = forEach || (function (item) { return; });
  17534. for (var i in list) {
  17535. var item = list[i];
  17536. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  17537. listByTags.push(item);
  17538. forEach(item);
  17539. }
  17540. }
  17541. return listByTags;
  17542. };
  17543. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  17544. return this._getByTags(this.meshes, tagsQuery, forEach);
  17545. };
  17546. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  17547. return this._getByTags(this.cameras, tagsQuery, forEach);
  17548. };
  17549. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  17550. return this._getByTags(this.lights, tagsQuery, forEach);
  17551. };
  17552. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  17553. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  17554. };
  17555. /**
  17556. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  17557. * This allowed control for front to back rendering or reversly depending of the special needs.
  17558. *
  17559. * @param renderingGroupId The rendering group id corresponding to its index
  17560. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  17561. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  17562. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  17563. */
  17564. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17565. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17566. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17567. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17568. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  17569. };
  17570. /**
  17571. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  17572. *
  17573. * @param renderingGroupId The rendering group id corresponding to its index
  17574. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  17575. * @param depth Automatically clears depth between groups if true and autoClear is true.
  17576. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  17577. */
  17578. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  17579. if (depth === void 0) { depth = true; }
  17580. if (stencil === void 0) { stencil = true; }
  17581. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  17582. };
  17583. /**
  17584. * Will flag all materials as dirty to trigger new shader compilation
  17585. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  17586. */
  17587. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  17588. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  17589. var material = _a[_i];
  17590. if (predicate && !predicate(material)) {
  17591. continue;
  17592. }
  17593. material.markAsDirty(flag);
  17594. }
  17595. };
  17596. return Scene;
  17597. }());
  17598. // Statics
  17599. Scene._FOGMODE_NONE = 0;
  17600. Scene._FOGMODE_EXP = 1;
  17601. Scene._FOGMODE_EXP2 = 2;
  17602. Scene._FOGMODE_LINEAR = 3;
  17603. Scene.MinDeltaTime = 1.0;
  17604. Scene.MaxDeltaTime = 1000.0;
  17605. Scene.DragMovementThreshold = 10; // in pixels
  17606. Scene.LongPressDelay = 500; // in milliseconds
  17607. Scene.DoubleClickDelay = 300; // in milliseconds
  17608. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  17609. BABYLON.Scene = Scene;
  17610. })(BABYLON || (BABYLON = {}));
  17611. //# sourceMappingURL=babylon.scene.js.map
  17612. var BABYLON;
  17613. (function (BABYLON) {
  17614. var Buffer = (function () {
  17615. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  17616. if (engine instanceof BABYLON.Mesh) {
  17617. this._engine = engine.getScene().getEngine();
  17618. }
  17619. else {
  17620. this._engine = engine;
  17621. }
  17622. this._updatable = updatable;
  17623. this._data = data;
  17624. this._strideSize = stride;
  17625. if (!postponeInternalCreation) {
  17626. this.create();
  17627. }
  17628. this._instanced = instanced;
  17629. }
  17630. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  17631. // a lot of these parameters are ignored as they are overriden by the buffer
  17632. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  17633. };
  17634. // Properties
  17635. Buffer.prototype.isUpdatable = function () {
  17636. return this._updatable;
  17637. };
  17638. Buffer.prototype.getData = function () {
  17639. return this._data;
  17640. };
  17641. Buffer.prototype.getBuffer = function () {
  17642. return this._buffer;
  17643. };
  17644. Buffer.prototype.getStrideSize = function () {
  17645. return this._strideSize;
  17646. };
  17647. Buffer.prototype.getIsInstanced = function () {
  17648. return this._instanced;
  17649. };
  17650. // Methods
  17651. Buffer.prototype.create = function (data) {
  17652. if (!data && this._buffer) {
  17653. return; // nothing to do
  17654. }
  17655. data = data || this._data;
  17656. if (!this._buffer) {
  17657. if (this._updatable) {
  17658. this._buffer = this._engine.createDynamicVertexBuffer(data);
  17659. this._data = data;
  17660. }
  17661. else {
  17662. this._buffer = this._engine.createVertexBuffer(data);
  17663. }
  17664. }
  17665. else if (this._updatable) {
  17666. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  17667. this._data = data;
  17668. }
  17669. };
  17670. Buffer.prototype.update = function (data) {
  17671. this.create(data);
  17672. };
  17673. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  17674. if (!this._buffer) {
  17675. return;
  17676. }
  17677. if (this._updatable) {
  17678. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  17679. this._data = null;
  17680. }
  17681. };
  17682. Buffer.prototype.dispose = function () {
  17683. if (!this._buffer) {
  17684. return;
  17685. }
  17686. if (this._engine._releaseBuffer(this._buffer)) {
  17687. this._buffer = null;
  17688. }
  17689. };
  17690. return Buffer;
  17691. }());
  17692. BABYLON.Buffer = Buffer;
  17693. })(BABYLON || (BABYLON = {}));
  17694. //# sourceMappingURL=babylon.buffer.js.map
  17695. var BABYLON;
  17696. (function (BABYLON) {
  17697. var VertexBuffer = (function () {
  17698. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  17699. if (!stride) {
  17700. // Deduce stride from kind
  17701. switch (kind) {
  17702. case VertexBuffer.PositionKind:
  17703. stride = 3;
  17704. break;
  17705. case VertexBuffer.NormalKind:
  17706. stride = 3;
  17707. break;
  17708. case VertexBuffer.UVKind:
  17709. case VertexBuffer.UV2Kind:
  17710. case VertexBuffer.UV3Kind:
  17711. case VertexBuffer.UV4Kind:
  17712. case VertexBuffer.UV5Kind:
  17713. case VertexBuffer.UV6Kind:
  17714. stride = 2;
  17715. break;
  17716. case VertexBuffer.TangentKind:
  17717. case VertexBuffer.ColorKind:
  17718. stride = 4;
  17719. break;
  17720. case VertexBuffer.MatricesIndicesKind:
  17721. case VertexBuffer.MatricesIndicesExtraKind:
  17722. stride = 4;
  17723. break;
  17724. case VertexBuffer.MatricesWeightsKind:
  17725. case VertexBuffer.MatricesWeightsExtraKind:
  17726. stride = 4;
  17727. break;
  17728. }
  17729. }
  17730. if (data instanceof BABYLON.Buffer) {
  17731. if (!stride) {
  17732. stride = data.getStrideSize();
  17733. }
  17734. this._buffer = data;
  17735. this._ownsBuffer = false;
  17736. }
  17737. else {
  17738. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  17739. this._ownsBuffer = true;
  17740. }
  17741. this._stride = stride;
  17742. this._offset = offset ? offset : 0;
  17743. this._size = size ? size : stride;
  17744. this._kind = kind;
  17745. }
  17746. /**
  17747. * Returns the kind of the VertexBuffer (string).
  17748. */
  17749. VertexBuffer.prototype.getKind = function () {
  17750. return this._kind;
  17751. };
  17752. // Properties
  17753. /**
  17754. * Boolean : is the VertexBuffer updatable ?
  17755. */
  17756. VertexBuffer.prototype.isUpdatable = function () {
  17757. return this._buffer.isUpdatable();
  17758. };
  17759. /**
  17760. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  17761. */
  17762. VertexBuffer.prototype.getData = function () {
  17763. return this._buffer.getData();
  17764. };
  17765. /**
  17766. * Returns the WebGLBuffer associated to the VertexBuffer.
  17767. */
  17768. VertexBuffer.prototype.getBuffer = function () {
  17769. return this._buffer.getBuffer();
  17770. };
  17771. /**
  17772. * Returns the stride of the VertexBuffer (integer).
  17773. */
  17774. VertexBuffer.prototype.getStrideSize = function () {
  17775. return this._stride;
  17776. };
  17777. /**
  17778. * Returns the offset (integer).
  17779. */
  17780. VertexBuffer.prototype.getOffset = function () {
  17781. return this._offset;
  17782. };
  17783. /**
  17784. * Returns the VertexBuffer total size (integer).
  17785. */
  17786. VertexBuffer.prototype.getSize = function () {
  17787. return this._size;
  17788. };
  17789. /**
  17790. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  17791. */
  17792. VertexBuffer.prototype.getIsInstanced = function () {
  17793. return this._buffer.getIsInstanced();
  17794. };
  17795. // Methods
  17796. /**
  17797. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  17798. * Returns the created WebGLBuffer.
  17799. */
  17800. VertexBuffer.prototype.create = function (data) {
  17801. return this._buffer.create(data);
  17802. };
  17803. /**
  17804. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  17805. * Returns the updated WebGLBuffer.
  17806. */
  17807. VertexBuffer.prototype.update = function (data) {
  17808. return this._buffer.update(data);
  17809. };
  17810. /**
  17811. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  17812. * Returns the directly updated WebGLBuffer.
  17813. */
  17814. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  17815. return this._buffer.updateDirectly(data, offset);
  17816. };
  17817. /**
  17818. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  17819. */
  17820. VertexBuffer.prototype.dispose = function () {
  17821. if (this._ownsBuffer) {
  17822. this._buffer.dispose();
  17823. }
  17824. };
  17825. Object.defineProperty(VertexBuffer, "PositionKind", {
  17826. get: function () {
  17827. return VertexBuffer._PositionKind;
  17828. },
  17829. enumerable: true,
  17830. configurable: true
  17831. });
  17832. Object.defineProperty(VertexBuffer, "NormalKind", {
  17833. get: function () {
  17834. return VertexBuffer._NormalKind;
  17835. },
  17836. enumerable: true,
  17837. configurable: true
  17838. });
  17839. Object.defineProperty(VertexBuffer, "TangentKind", {
  17840. get: function () {
  17841. return VertexBuffer._TangentKind;
  17842. },
  17843. enumerable: true,
  17844. configurable: true
  17845. });
  17846. Object.defineProperty(VertexBuffer, "UVKind", {
  17847. get: function () {
  17848. return VertexBuffer._UVKind;
  17849. },
  17850. enumerable: true,
  17851. configurable: true
  17852. });
  17853. Object.defineProperty(VertexBuffer, "UV2Kind", {
  17854. get: function () {
  17855. return VertexBuffer._UV2Kind;
  17856. },
  17857. enumerable: true,
  17858. configurable: true
  17859. });
  17860. Object.defineProperty(VertexBuffer, "UV3Kind", {
  17861. get: function () {
  17862. return VertexBuffer._UV3Kind;
  17863. },
  17864. enumerable: true,
  17865. configurable: true
  17866. });
  17867. Object.defineProperty(VertexBuffer, "UV4Kind", {
  17868. get: function () {
  17869. return VertexBuffer._UV4Kind;
  17870. },
  17871. enumerable: true,
  17872. configurable: true
  17873. });
  17874. Object.defineProperty(VertexBuffer, "UV5Kind", {
  17875. get: function () {
  17876. return VertexBuffer._UV5Kind;
  17877. },
  17878. enumerable: true,
  17879. configurable: true
  17880. });
  17881. Object.defineProperty(VertexBuffer, "UV6Kind", {
  17882. get: function () {
  17883. return VertexBuffer._UV6Kind;
  17884. },
  17885. enumerable: true,
  17886. configurable: true
  17887. });
  17888. Object.defineProperty(VertexBuffer, "ColorKind", {
  17889. get: function () {
  17890. return VertexBuffer._ColorKind;
  17891. },
  17892. enumerable: true,
  17893. configurable: true
  17894. });
  17895. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  17896. get: function () {
  17897. return VertexBuffer._MatricesIndicesKind;
  17898. },
  17899. enumerable: true,
  17900. configurable: true
  17901. });
  17902. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  17903. get: function () {
  17904. return VertexBuffer._MatricesWeightsKind;
  17905. },
  17906. enumerable: true,
  17907. configurable: true
  17908. });
  17909. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  17910. get: function () {
  17911. return VertexBuffer._MatricesIndicesExtraKind;
  17912. },
  17913. enumerable: true,
  17914. configurable: true
  17915. });
  17916. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  17917. get: function () {
  17918. return VertexBuffer._MatricesWeightsExtraKind;
  17919. },
  17920. enumerable: true,
  17921. configurable: true
  17922. });
  17923. return VertexBuffer;
  17924. }());
  17925. // Enums
  17926. VertexBuffer._PositionKind = "position";
  17927. VertexBuffer._NormalKind = "normal";
  17928. VertexBuffer._TangentKind = "tangent";
  17929. VertexBuffer._UVKind = "uv";
  17930. VertexBuffer._UV2Kind = "uv2";
  17931. VertexBuffer._UV3Kind = "uv3";
  17932. VertexBuffer._UV4Kind = "uv4";
  17933. VertexBuffer._UV5Kind = "uv5";
  17934. VertexBuffer._UV6Kind = "uv6";
  17935. VertexBuffer._ColorKind = "color";
  17936. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  17937. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  17938. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  17939. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  17940. BABYLON.VertexBuffer = VertexBuffer;
  17941. })(BABYLON || (BABYLON = {}));
  17942. //# sourceMappingURL=babylon.vertexBuffer.js.map
  17943. var BABYLON;
  17944. (function (BABYLON) {
  17945. var BaseTexture = (function () {
  17946. function BaseTexture(scene) {
  17947. this._hasAlpha = false;
  17948. this.getAlphaFromRGB = false;
  17949. this.level = 1;
  17950. this.coordinatesIndex = 0;
  17951. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  17952. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17953. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17954. this.anisotropicFilteringLevel = 4;
  17955. this.isCube = false;
  17956. this.isRenderTarget = false;
  17957. this.animations = new Array();
  17958. /**
  17959. * An event triggered when the texture is disposed.
  17960. * @type {BABYLON.Observable}
  17961. */
  17962. this.onDisposeObservable = new BABYLON.Observable();
  17963. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17964. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  17965. this._scene.textures.push(this);
  17966. this._uid = null;
  17967. }
  17968. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  17969. get: function () {
  17970. return this._hasAlpha;
  17971. },
  17972. set: function (value) {
  17973. if (this._hasAlpha === value) {
  17974. return;
  17975. }
  17976. this._hasAlpha = value;
  17977. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17978. },
  17979. enumerable: true,
  17980. configurable: true
  17981. });
  17982. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  17983. get: function () {
  17984. return this._coordinatesMode;
  17985. },
  17986. set: function (value) {
  17987. if (this._coordinatesMode === value) {
  17988. return;
  17989. }
  17990. this._coordinatesMode = value;
  17991. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17992. },
  17993. enumerable: true,
  17994. configurable: true
  17995. });
  17996. Object.defineProperty(BaseTexture.prototype, "uid", {
  17997. get: function () {
  17998. if (!this._uid) {
  17999. this._uid = BABYLON.Tools.RandomId();
  18000. }
  18001. return this._uid;
  18002. },
  18003. enumerable: true,
  18004. configurable: true
  18005. });
  18006. BaseTexture.prototype.toString = function () {
  18007. return this.name;
  18008. };
  18009. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  18010. set: function (callback) {
  18011. if (this._onDisposeObserver) {
  18012. this.onDisposeObservable.remove(this._onDisposeObserver);
  18013. }
  18014. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18015. },
  18016. enumerable: true,
  18017. configurable: true
  18018. });
  18019. BaseTexture.prototype.getScene = function () {
  18020. return this._scene;
  18021. };
  18022. BaseTexture.prototype.getTextureMatrix = function () {
  18023. return null;
  18024. };
  18025. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  18026. return null;
  18027. };
  18028. BaseTexture.prototype.getInternalTexture = function () {
  18029. return this._texture;
  18030. };
  18031. BaseTexture.prototype.isReady = function () {
  18032. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18033. this.delayLoad();
  18034. return false;
  18035. }
  18036. if (this._texture) {
  18037. return this._texture.isReady;
  18038. }
  18039. return false;
  18040. };
  18041. BaseTexture.prototype.getSize = function () {
  18042. if (this._texture._width) {
  18043. return new BABYLON.Size(this._texture._width, this._texture._height);
  18044. }
  18045. if (this._texture._size) {
  18046. return new BABYLON.Size(this._texture._size, this._texture._size);
  18047. }
  18048. return BABYLON.Size.Zero();
  18049. };
  18050. BaseTexture.prototype.getBaseSize = function () {
  18051. if (!this.isReady() || !this._texture)
  18052. return BABYLON.Size.Zero();
  18053. if (this._texture._size) {
  18054. return new BABYLON.Size(this._texture._size, this._texture._size);
  18055. }
  18056. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  18057. };
  18058. BaseTexture.prototype.scale = function (ratio) {
  18059. };
  18060. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  18061. get: function () {
  18062. return false;
  18063. },
  18064. enumerable: true,
  18065. configurable: true
  18066. });
  18067. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  18068. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18069. for (var index = 0; index < texturesCache.length; index++) {
  18070. var texturesCacheEntry = texturesCache[index];
  18071. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18072. texturesCache.splice(index, 1);
  18073. return;
  18074. }
  18075. }
  18076. };
  18077. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  18078. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18079. for (var index = 0; index < texturesCache.length; index++) {
  18080. var texturesCacheEntry = texturesCache[index];
  18081. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18082. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  18083. texturesCacheEntry.references++;
  18084. return texturesCacheEntry;
  18085. }
  18086. }
  18087. }
  18088. return null;
  18089. };
  18090. BaseTexture.prototype.delayLoad = function () {
  18091. };
  18092. BaseTexture.prototype.clone = function () {
  18093. return null;
  18094. };
  18095. BaseTexture.prototype.releaseInternalTexture = function () {
  18096. if (this._texture) {
  18097. this._scene.getEngine().releaseInternalTexture(this._texture);
  18098. delete this._texture;
  18099. }
  18100. };
  18101. BaseTexture.prototype.dispose = function () {
  18102. // Animations
  18103. this.getScene().stopAnimation(this);
  18104. // Remove from scene
  18105. this._scene._removePendingData(this);
  18106. var index = this._scene.textures.indexOf(this);
  18107. if (index >= 0) {
  18108. this._scene.textures.splice(index, 1);
  18109. }
  18110. if (this._texture === undefined) {
  18111. return;
  18112. }
  18113. // Release
  18114. this.releaseInternalTexture();
  18115. // Callback
  18116. this.onDisposeObservable.notifyObservers(this);
  18117. this.onDisposeObservable.clear();
  18118. };
  18119. BaseTexture.prototype.serialize = function () {
  18120. if (!this.name) {
  18121. return null;
  18122. }
  18123. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18124. // Animations
  18125. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18126. return serializationObject;
  18127. };
  18128. return BaseTexture;
  18129. }());
  18130. __decorate([
  18131. BABYLON.serialize()
  18132. ], BaseTexture.prototype, "name", void 0);
  18133. __decorate([
  18134. BABYLON.serialize("hasAlpha")
  18135. ], BaseTexture.prototype, "_hasAlpha", void 0);
  18136. __decorate([
  18137. BABYLON.serialize()
  18138. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  18139. __decorate([
  18140. BABYLON.serialize()
  18141. ], BaseTexture.prototype, "level", void 0);
  18142. __decorate([
  18143. BABYLON.serialize()
  18144. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  18145. __decorate([
  18146. BABYLON.serialize("coordinatesMode")
  18147. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  18148. __decorate([
  18149. BABYLON.serialize()
  18150. ], BaseTexture.prototype, "wrapU", void 0);
  18151. __decorate([
  18152. BABYLON.serialize()
  18153. ], BaseTexture.prototype, "wrapV", void 0);
  18154. __decorate([
  18155. BABYLON.serialize()
  18156. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  18157. __decorate([
  18158. BABYLON.serialize()
  18159. ], BaseTexture.prototype, "isCube", void 0);
  18160. __decorate([
  18161. BABYLON.serialize()
  18162. ], BaseTexture.prototype, "isRenderTarget", void 0);
  18163. BABYLON.BaseTexture = BaseTexture;
  18164. })(BABYLON || (BABYLON = {}));
  18165. //# sourceMappingURL=babylon.baseTexture.js.map
  18166. var BABYLON;
  18167. (function (BABYLON) {
  18168. var Texture = (function (_super) {
  18169. __extends(Texture, _super);
  18170. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  18171. if (noMipmap === void 0) { noMipmap = false; }
  18172. if (invertY === void 0) { invertY = true; }
  18173. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  18174. if (onLoad === void 0) { onLoad = null; }
  18175. if (onError === void 0) { onError = null; }
  18176. if (buffer === void 0) { buffer = null; }
  18177. if (deleteBuffer === void 0) { deleteBuffer = false; }
  18178. var _this = _super.call(this, scene) || this;
  18179. _this.uOffset = 0;
  18180. _this.vOffset = 0;
  18181. _this.uScale = 1.0;
  18182. _this.vScale = 1.0;
  18183. _this.uAng = 0;
  18184. _this.vAng = 0;
  18185. _this.wAng = 0;
  18186. _this.name = url;
  18187. _this.url = url;
  18188. _this._noMipmap = noMipmap;
  18189. _this._invertY = invertY;
  18190. _this._samplingMode = samplingMode;
  18191. _this._buffer = buffer;
  18192. _this._deleteBuffer = deleteBuffer;
  18193. _this._format = format;
  18194. scene = _this.getScene();
  18195. if (!url) {
  18196. return _this;
  18197. }
  18198. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  18199. var load = function () {
  18200. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  18201. _this.onLoadObservable.notifyObservers(true);
  18202. }
  18203. if (onLoad) {
  18204. onLoad();
  18205. }
  18206. };
  18207. if (!_this._texture) {
  18208. if (!scene.useDelayedTextureLoading) {
  18209. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  18210. if (deleteBuffer) {
  18211. delete _this._buffer;
  18212. }
  18213. }
  18214. else {
  18215. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18216. _this._delayedOnLoad = load;
  18217. _this._delayedOnError = onError;
  18218. }
  18219. }
  18220. else {
  18221. if (_this._texture.isReady) {
  18222. BABYLON.Tools.SetImmediate(function () { return load(); });
  18223. }
  18224. else {
  18225. _this._texture.onLoadedCallbacks.push(load);
  18226. }
  18227. }
  18228. return _this;
  18229. }
  18230. Object.defineProperty(Texture.prototype, "noMipmap", {
  18231. get: function () {
  18232. return this._noMipmap;
  18233. },
  18234. enumerable: true,
  18235. configurable: true
  18236. });
  18237. Texture.prototype.delayLoad = function () {
  18238. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18239. return;
  18240. }
  18241. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18242. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  18243. if (!this._texture) {
  18244. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  18245. if (this._deleteBuffer) {
  18246. delete this._buffer;
  18247. }
  18248. }
  18249. };
  18250. Texture.prototype.updateSamplingMode = function (samplingMode) {
  18251. if (!this._texture) {
  18252. return;
  18253. }
  18254. this._samplingMode = samplingMode;
  18255. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  18256. };
  18257. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  18258. x *= this.uScale;
  18259. y *= this.vScale;
  18260. x -= 0.5 * this.uScale;
  18261. y -= 0.5 * this.vScale;
  18262. z -= 0.5;
  18263. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  18264. t.x += 0.5 * this.uScale + this.uOffset;
  18265. t.y += 0.5 * this.vScale + this.vOffset;
  18266. t.z += 0.5;
  18267. };
  18268. Texture.prototype.getTextureMatrix = function () {
  18269. if (this.uOffset === this._cachedUOffset &&
  18270. this.vOffset === this._cachedVOffset &&
  18271. this.uScale === this._cachedUScale &&
  18272. this.vScale === this._cachedVScale &&
  18273. this.uAng === this._cachedUAng &&
  18274. this.vAng === this._cachedVAng &&
  18275. this.wAng === this._cachedWAng) {
  18276. return this._cachedTextureMatrix;
  18277. }
  18278. this._cachedUOffset = this.uOffset;
  18279. this._cachedVOffset = this.vOffset;
  18280. this._cachedUScale = this.uScale;
  18281. this._cachedVScale = this.vScale;
  18282. this._cachedUAng = this.uAng;
  18283. this._cachedVAng = this.vAng;
  18284. this._cachedWAng = this.wAng;
  18285. if (!this._cachedTextureMatrix) {
  18286. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  18287. this._rowGenerationMatrix = new BABYLON.Matrix();
  18288. this._t0 = BABYLON.Vector3.Zero();
  18289. this._t1 = BABYLON.Vector3.Zero();
  18290. this._t2 = BABYLON.Vector3.Zero();
  18291. }
  18292. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  18293. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  18294. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  18295. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  18296. this._t1.subtractInPlace(this._t0);
  18297. this._t2.subtractInPlace(this._t0);
  18298. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  18299. this._cachedTextureMatrix.m[0] = this._t1.x;
  18300. this._cachedTextureMatrix.m[1] = this._t1.y;
  18301. this._cachedTextureMatrix.m[2] = this._t1.z;
  18302. this._cachedTextureMatrix.m[4] = this._t2.x;
  18303. this._cachedTextureMatrix.m[5] = this._t2.y;
  18304. this._cachedTextureMatrix.m[6] = this._t2.z;
  18305. this._cachedTextureMatrix.m[8] = this._t0.x;
  18306. this._cachedTextureMatrix.m[9] = this._t0.y;
  18307. this._cachedTextureMatrix.m[10] = this._t0.z;
  18308. return this._cachedTextureMatrix;
  18309. };
  18310. Texture.prototype.getReflectionTextureMatrix = function () {
  18311. if (this.uOffset === this._cachedUOffset &&
  18312. this.vOffset === this._cachedVOffset &&
  18313. this.uScale === this._cachedUScale &&
  18314. this.vScale === this._cachedVScale &&
  18315. this.coordinatesMode === this._cachedCoordinatesMode) {
  18316. return this._cachedTextureMatrix;
  18317. }
  18318. if (!this._cachedTextureMatrix) {
  18319. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  18320. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  18321. }
  18322. this._cachedCoordinatesMode = this.coordinatesMode;
  18323. switch (this.coordinatesMode) {
  18324. case Texture.PLANAR_MODE:
  18325. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  18326. this._cachedTextureMatrix[0] = this.uScale;
  18327. this._cachedTextureMatrix[5] = this.vScale;
  18328. this._cachedTextureMatrix[12] = this.uOffset;
  18329. this._cachedTextureMatrix[13] = this.vOffset;
  18330. break;
  18331. case Texture.PROJECTION_MODE:
  18332. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  18333. this._projectionModeMatrix.m[0] = 0.5;
  18334. this._projectionModeMatrix.m[5] = -0.5;
  18335. this._projectionModeMatrix.m[10] = 0.0;
  18336. this._projectionModeMatrix.m[12] = 0.5;
  18337. this._projectionModeMatrix.m[13] = 0.5;
  18338. this._projectionModeMatrix.m[14] = 1.0;
  18339. this._projectionModeMatrix.m[15] = 1.0;
  18340. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  18341. break;
  18342. default:
  18343. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  18344. break;
  18345. }
  18346. return this._cachedTextureMatrix;
  18347. };
  18348. Texture.prototype.clone = function () {
  18349. var _this = this;
  18350. return BABYLON.SerializationHelper.Clone(function () {
  18351. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  18352. }, this);
  18353. };
  18354. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  18355. get: function () {
  18356. if (!this._onLoadObservarble) {
  18357. this._onLoadObservarble = new BABYLON.Observable();
  18358. }
  18359. return this._onLoadObservarble;
  18360. },
  18361. enumerable: true,
  18362. configurable: true
  18363. });
  18364. // Statics
  18365. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  18366. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  18367. if (onLoad === void 0) { onLoad = null; }
  18368. if (onError === void 0) { onError = null; }
  18369. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  18370. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  18371. };
  18372. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  18373. if (parsedTexture.customType) {
  18374. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  18375. // Update Sampling Mode
  18376. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  18377. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  18378. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  18379. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  18380. }
  18381. }
  18382. return parsedCustomTexture;
  18383. }
  18384. if (parsedTexture.isCube) {
  18385. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  18386. }
  18387. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18388. return null;
  18389. }
  18390. var texture = BABYLON.SerializationHelper.Parse(function () {
  18391. if (parsedTexture.mirrorPlane) {
  18392. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18393. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  18394. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18395. return mirrorTexture;
  18396. }
  18397. else if (parsedTexture.isRenderTarget) {
  18398. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18399. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  18400. return renderTargetTexture;
  18401. }
  18402. else {
  18403. var texture;
  18404. if (parsedTexture.base64String) {
  18405. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  18406. }
  18407. else {
  18408. texture = new Texture(rootUrl + parsedTexture.name, scene);
  18409. }
  18410. return texture;
  18411. }
  18412. }, parsedTexture, scene);
  18413. // Update Sampling Mode
  18414. if (parsedTexture.samplingMode) {
  18415. var sampling = parsedTexture.samplingMode;
  18416. if (texture._samplingMode !== sampling) {
  18417. texture.updateSamplingMode(sampling);
  18418. }
  18419. }
  18420. // Animations
  18421. if (parsedTexture.animations) {
  18422. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18423. var parsedAnimation = parsedTexture.animations[animationIndex];
  18424. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18425. }
  18426. }
  18427. return texture;
  18428. };
  18429. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  18430. if (deleteBuffer === void 0) { deleteBuffer = false; }
  18431. if (noMipmap === void 0) { noMipmap = false; }
  18432. if (invertY === void 0) { invertY = true; }
  18433. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  18434. if (onLoad === void 0) { onLoad = null; }
  18435. if (onError === void 0) { onError = null; }
  18436. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  18437. if (name.substr(0, 5) !== "data:") {
  18438. name = "data:" + name;
  18439. }
  18440. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  18441. };
  18442. return Texture;
  18443. }(BABYLON.BaseTexture));
  18444. // Constants
  18445. Texture.NEAREST_SAMPLINGMODE = 1;
  18446. Texture.BILINEAR_SAMPLINGMODE = 2;
  18447. Texture.TRILINEAR_SAMPLINGMODE = 3;
  18448. Texture.EXPLICIT_MODE = 0;
  18449. Texture.SPHERICAL_MODE = 1;
  18450. Texture.PLANAR_MODE = 2;
  18451. Texture.CUBIC_MODE = 3;
  18452. Texture.PROJECTION_MODE = 4;
  18453. Texture.SKYBOX_MODE = 5;
  18454. Texture.INVCUBIC_MODE = 6;
  18455. Texture.EQUIRECTANGULAR_MODE = 7;
  18456. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  18457. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  18458. Texture.CLAMP_ADDRESSMODE = 0;
  18459. Texture.WRAP_ADDRESSMODE = 1;
  18460. Texture.MIRROR_ADDRESSMODE = 2;
  18461. __decorate([
  18462. BABYLON.serialize()
  18463. ], Texture.prototype, "url", void 0);
  18464. __decorate([
  18465. BABYLON.serialize()
  18466. ], Texture.prototype, "uOffset", void 0);
  18467. __decorate([
  18468. BABYLON.serialize()
  18469. ], Texture.prototype, "vOffset", void 0);
  18470. __decorate([
  18471. BABYLON.serialize()
  18472. ], Texture.prototype, "uScale", void 0);
  18473. __decorate([
  18474. BABYLON.serialize()
  18475. ], Texture.prototype, "vScale", void 0);
  18476. __decorate([
  18477. BABYLON.serialize()
  18478. ], Texture.prototype, "uAng", void 0);
  18479. __decorate([
  18480. BABYLON.serialize()
  18481. ], Texture.prototype, "vAng", void 0);
  18482. __decorate([
  18483. BABYLON.serialize()
  18484. ], Texture.prototype, "wAng", void 0);
  18485. BABYLON.Texture = Texture;
  18486. })(BABYLON || (BABYLON = {}));
  18487. //# sourceMappingURL=babylon.texture.js.map
  18488. var BABYLON;
  18489. (function (BABYLON) {
  18490. var _InstancesBatch = (function () {
  18491. function _InstancesBatch() {
  18492. this.mustReturn = false;
  18493. this.visibleInstances = new Array();
  18494. this.renderSelf = new Array();
  18495. }
  18496. return _InstancesBatch;
  18497. }());
  18498. BABYLON._InstancesBatch = _InstancesBatch;
  18499. var Mesh = (function (_super) {
  18500. __extends(Mesh, _super);
  18501. /**
  18502. * @constructor
  18503. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  18504. * @param {Scene} scene The scene to add this mesh to.
  18505. * @param {Node} parent The parent of this mesh, if it has one
  18506. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  18507. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  18508. * When false, achieved by calling a clone(), also passing False.
  18509. * This will make creation of children, recursive.
  18510. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  18511. */
  18512. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  18513. if (parent === void 0) { parent = null; }
  18514. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  18515. var _this = _super.call(this, name, scene) || this;
  18516. // Events
  18517. /**
  18518. * An event triggered before rendering the mesh
  18519. * @type {BABYLON.Observable}
  18520. */
  18521. _this.onBeforeRenderObservable = new BABYLON.Observable();
  18522. /**
  18523. * An event triggered after rendering the mesh
  18524. * @type {BABYLON.Observable}
  18525. */
  18526. _this.onAfterRenderObservable = new BABYLON.Observable();
  18527. /**
  18528. * An event triggered before drawing the mesh
  18529. * @type {BABYLON.Observable}
  18530. */
  18531. _this.onBeforeDrawObservable = new BABYLON.Observable();
  18532. // Members
  18533. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18534. _this.instances = new Array();
  18535. _this._LODLevels = new Array();
  18536. _this._visibleInstances = {};
  18537. _this._renderIdForInstances = new Array();
  18538. _this._batchCache = new _InstancesBatch();
  18539. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  18540. _this._sideOrientation = Mesh._DEFAULTSIDE;
  18541. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  18542. // Will be used to save a source mesh reference, If any
  18543. _this._source = null;
  18544. if (source) {
  18545. // Source mesh
  18546. _this._source = source;
  18547. // Geometry
  18548. if (source._geometry) {
  18549. source._geometry.applyToMesh(_this);
  18550. }
  18551. // Deep copy
  18552. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  18553. // Parent
  18554. _this.parent = source.parent;
  18555. // Pivot
  18556. _this.setPivotMatrix(source.getPivotMatrix());
  18557. _this.id = name + "." + source.id;
  18558. // Material
  18559. _this.material = source.material;
  18560. var index;
  18561. if (!doNotCloneChildren) {
  18562. // Children
  18563. for (index = 0; index < scene.meshes.length; index++) {
  18564. var mesh = scene.meshes[index];
  18565. if (mesh.parent === source) {
  18566. // doNotCloneChildren is always going to be False
  18567. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  18568. }
  18569. }
  18570. }
  18571. // Physics clone
  18572. var physicsEngine = _this.getScene().getPhysicsEngine();
  18573. if (clonePhysicsImpostor && physicsEngine) {
  18574. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  18575. if (impostor) {
  18576. _this.physicsImpostor = impostor.clone(_this);
  18577. }
  18578. }
  18579. // Particles
  18580. for (index = 0; index < scene.particleSystems.length; index++) {
  18581. var system = scene.particleSystems[index];
  18582. if (system.emitter === source) {
  18583. system.clone(system.name, _this);
  18584. }
  18585. }
  18586. _this.computeWorldMatrix(true);
  18587. }
  18588. // Parent
  18589. if (parent !== null) {
  18590. _this.parent = parent;
  18591. }
  18592. return _this;
  18593. }
  18594. Object.defineProperty(Mesh, "FRONTSIDE", {
  18595. /**
  18596. * Mesh side orientation : usually the external or front surface
  18597. */
  18598. get: function () {
  18599. return Mesh._FRONTSIDE;
  18600. },
  18601. enumerable: true,
  18602. configurable: true
  18603. });
  18604. Object.defineProperty(Mesh, "BACKSIDE", {
  18605. /**
  18606. * Mesh side orientation : usually the internal or back surface
  18607. */
  18608. get: function () {
  18609. return Mesh._BACKSIDE;
  18610. },
  18611. enumerable: true,
  18612. configurable: true
  18613. });
  18614. Object.defineProperty(Mesh, "DOUBLESIDE", {
  18615. /**
  18616. * Mesh side orientation : both internal and external or front and back surfaces
  18617. */
  18618. get: function () {
  18619. return Mesh._DOUBLESIDE;
  18620. },
  18621. enumerable: true,
  18622. configurable: true
  18623. });
  18624. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  18625. /**
  18626. * Mesh side orientation : by default, `FRONTSIDE`
  18627. */
  18628. get: function () {
  18629. return Mesh._DEFAULTSIDE;
  18630. },
  18631. enumerable: true,
  18632. configurable: true
  18633. });
  18634. Object.defineProperty(Mesh, "NO_CAP", {
  18635. /**
  18636. * Mesh cap setting : no cap
  18637. */
  18638. get: function () {
  18639. return Mesh._NO_CAP;
  18640. },
  18641. enumerable: true,
  18642. configurable: true
  18643. });
  18644. Object.defineProperty(Mesh, "CAP_START", {
  18645. /**
  18646. * Mesh cap setting : one cap at the beginning of the mesh
  18647. */
  18648. get: function () {
  18649. return Mesh._CAP_START;
  18650. },
  18651. enumerable: true,
  18652. configurable: true
  18653. });
  18654. Object.defineProperty(Mesh, "CAP_END", {
  18655. /**
  18656. * Mesh cap setting : one cap at the end of the mesh
  18657. */
  18658. get: function () {
  18659. return Mesh._CAP_END;
  18660. },
  18661. enumerable: true,
  18662. configurable: true
  18663. });
  18664. Object.defineProperty(Mesh, "CAP_ALL", {
  18665. /**
  18666. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  18667. */
  18668. get: function () {
  18669. return Mesh._CAP_ALL;
  18670. },
  18671. enumerable: true,
  18672. configurable: true
  18673. });
  18674. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  18675. set: function (callback) {
  18676. if (this._onBeforeDrawObserver) {
  18677. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  18678. }
  18679. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  18680. },
  18681. enumerable: true,
  18682. configurable: true
  18683. });
  18684. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  18685. get: function () {
  18686. return this._morphTargetManager;
  18687. },
  18688. set: function (value) {
  18689. if (this._morphTargetManager === value) {
  18690. return;
  18691. }
  18692. this._morphTargetManager = value;
  18693. this._syncGeometryWithMorphTargetManager();
  18694. },
  18695. enumerable: true,
  18696. configurable: true
  18697. });
  18698. Object.defineProperty(Mesh.prototype, "source", {
  18699. get: function () {
  18700. return this._source;
  18701. },
  18702. enumerable: true,
  18703. configurable: true
  18704. });
  18705. // Methods
  18706. /**
  18707. * Returns the string "Mesh".
  18708. */
  18709. Mesh.prototype.getClassName = function () {
  18710. return "Mesh";
  18711. };
  18712. /**
  18713. * Returns a string.
  18714. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18715. */
  18716. Mesh.prototype.toString = function (fullDetails) {
  18717. var ret = _super.prototype.toString.call(this, fullDetails);
  18718. ret += ", n vertices: " + this.getTotalVertices();
  18719. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  18720. if (this.animations) {
  18721. for (var i = 0; i < this.animations.length; i++) {
  18722. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18723. }
  18724. }
  18725. if (fullDetails) {
  18726. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  18727. }
  18728. return ret;
  18729. };
  18730. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  18731. /**
  18732. * True if the mesh has some Levels Of Details (LOD).
  18733. * Returns a boolean.
  18734. */
  18735. get: function () {
  18736. return this._LODLevels.length > 0;
  18737. },
  18738. enumerable: true,
  18739. configurable: true
  18740. });
  18741. Mesh.prototype._sortLODLevels = function () {
  18742. this._LODLevels.sort(function (a, b) {
  18743. if (a.distance < b.distance) {
  18744. return 1;
  18745. }
  18746. if (a.distance > b.distance) {
  18747. return -1;
  18748. }
  18749. return 0;
  18750. });
  18751. };
  18752. /**
  18753. * Add a mesh as LOD level triggered at the given distance.
  18754. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18755. * @param {number} distance The distance from the center of the object to show this level
  18756. * @param {Mesh} mesh The mesh to be added as LOD level
  18757. * @return {Mesh} This mesh (for chaining)
  18758. */
  18759. Mesh.prototype.addLODLevel = function (distance, mesh) {
  18760. if (mesh && mesh._masterMesh) {
  18761. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  18762. return this;
  18763. }
  18764. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  18765. this._LODLevels.push(level);
  18766. if (mesh) {
  18767. mesh._masterMesh = this;
  18768. }
  18769. this._sortLODLevels();
  18770. return this;
  18771. };
  18772. /**
  18773. * Returns the LOD level mesh at the passed distance or null if not found.
  18774. * It is related to the method `addLODLevel(distance, mesh)`.
  18775. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18776. * Returns an object Mesh or `null`.
  18777. */
  18778. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  18779. for (var index = 0; index < this._LODLevels.length; index++) {
  18780. var level = this._LODLevels[index];
  18781. if (level.distance === distance) {
  18782. return level.mesh;
  18783. }
  18784. }
  18785. return null;
  18786. };
  18787. /**
  18788. * Remove a mesh from the LOD array
  18789. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18790. * @param {Mesh} mesh The mesh to be removed.
  18791. * @return {Mesh} This mesh (for chaining)
  18792. */
  18793. Mesh.prototype.removeLODLevel = function (mesh) {
  18794. for (var index = 0; index < this._LODLevels.length; index++) {
  18795. if (this._LODLevels[index].mesh === mesh) {
  18796. this._LODLevels.splice(index, 1);
  18797. if (mesh) {
  18798. mesh._masterMesh = null;
  18799. }
  18800. }
  18801. }
  18802. this._sortLODLevels();
  18803. return this;
  18804. };
  18805. /**
  18806. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  18807. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18808. */
  18809. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  18810. if (!this._LODLevels || this._LODLevels.length === 0) {
  18811. return this;
  18812. }
  18813. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  18814. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  18815. if (this.onLODLevelSelection) {
  18816. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  18817. }
  18818. return this;
  18819. }
  18820. for (var index = 0; index < this._LODLevels.length; index++) {
  18821. var level = this._LODLevels[index];
  18822. if (level.distance < distanceToCamera) {
  18823. if (level.mesh) {
  18824. level.mesh._preActivate();
  18825. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18826. }
  18827. if (this.onLODLevelSelection) {
  18828. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  18829. }
  18830. return level.mesh;
  18831. }
  18832. }
  18833. if (this.onLODLevelSelection) {
  18834. this.onLODLevelSelection(distanceToCamera, this, this);
  18835. }
  18836. return this;
  18837. };
  18838. Object.defineProperty(Mesh.prototype, "geometry", {
  18839. /**
  18840. * Returns the mesh internal Geometry object.
  18841. */
  18842. get: function () {
  18843. return this._geometry;
  18844. },
  18845. enumerable: true,
  18846. configurable: true
  18847. });
  18848. /**
  18849. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  18850. */
  18851. Mesh.prototype.getTotalVertices = function () {
  18852. if (!this._geometry) {
  18853. return 0;
  18854. }
  18855. return this._geometry.getTotalVertices();
  18856. };
  18857. /**
  18858. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  18859. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  18860. * You can force the copy with forceCopy === true
  18861. * Returns null if the mesh has no geometry or no vertex buffer.
  18862. * Possible `kind` values :
  18863. * - BABYLON.VertexBuffer.PositionKind
  18864. * - BABYLON.VertexBuffer.UVKind
  18865. * - BABYLON.VertexBuffer.UV2Kind
  18866. * - BABYLON.VertexBuffer.UV3Kind
  18867. * - BABYLON.VertexBuffer.UV4Kind
  18868. * - BABYLON.VertexBuffer.UV5Kind
  18869. * - BABYLON.VertexBuffer.UV6Kind
  18870. * - BABYLON.VertexBuffer.ColorKind
  18871. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18872. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18873. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18874. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18875. */
  18876. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  18877. if (!this._geometry) {
  18878. return null;
  18879. }
  18880. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  18881. };
  18882. /**
  18883. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  18884. * Returns `undefined` if the mesh has no geometry.
  18885. * Possible `kind` values :
  18886. * - BABYLON.VertexBuffer.PositionKind
  18887. * - BABYLON.VertexBuffer.UVKind
  18888. * - BABYLON.VertexBuffer.UV2Kind
  18889. * - BABYLON.VertexBuffer.UV3Kind
  18890. * - BABYLON.VertexBuffer.UV4Kind
  18891. * - BABYLON.VertexBuffer.UV5Kind
  18892. * - BABYLON.VertexBuffer.UV6Kind
  18893. * - BABYLON.VertexBuffer.ColorKind
  18894. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18895. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18896. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18897. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18898. */
  18899. Mesh.prototype.getVertexBuffer = function (kind) {
  18900. if (!this._geometry) {
  18901. return undefined;
  18902. }
  18903. return this._geometry.getVertexBuffer(kind);
  18904. };
  18905. /**
  18906. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  18907. * Possible `kind` values :
  18908. * - BABYLON.VertexBuffer.PositionKind
  18909. * - BABYLON.VertexBuffer.UVKind
  18910. * - BABYLON.VertexBuffer.UV2Kind
  18911. * - BABYLON.VertexBuffer.UV3Kind
  18912. * - BABYLON.VertexBuffer.UV4Kind
  18913. * - BABYLON.VertexBuffer.UV5Kind
  18914. * - BABYLON.VertexBuffer.UV6Kind
  18915. * - BABYLON.VertexBuffer.ColorKind
  18916. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18917. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18918. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18919. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18920. */
  18921. Mesh.prototype.isVerticesDataPresent = function (kind) {
  18922. if (!this._geometry) {
  18923. if (this._delayInfo) {
  18924. return this._delayInfo.indexOf(kind) !== -1;
  18925. }
  18926. return false;
  18927. }
  18928. return this._geometry.isVerticesDataPresent(kind);
  18929. };
  18930. /**
  18931. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  18932. * Possible `kind` values :
  18933. * - BABYLON.VertexBuffer.PositionKind
  18934. * - BABYLON.VertexBuffer.UVKind
  18935. * - BABYLON.VertexBuffer.UV2Kind
  18936. * - BABYLON.VertexBuffer.UV3Kind
  18937. * - BABYLON.VertexBuffer.UV4Kind
  18938. * - BABYLON.VertexBuffer.UV5Kind
  18939. * - BABYLON.VertexBuffer.UV6Kind
  18940. * - BABYLON.VertexBuffer.ColorKind
  18941. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18942. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18943. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18944. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18945. */
  18946. Mesh.prototype.getVerticesDataKinds = function () {
  18947. if (!this._geometry) {
  18948. var result = [];
  18949. if (this._delayInfo) {
  18950. this._delayInfo.forEach(function (kind, index, array) {
  18951. result.push(kind);
  18952. });
  18953. }
  18954. return result;
  18955. }
  18956. return this._geometry.getVerticesDataKinds();
  18957. };
  18958. /**
  18959. * Returns a positive integer : the total number of indices in this mesh geometry.
  18960. * Returns zero if the mesh has no geometry.
  18961. */
  18962. Mesh.prototype.getTotalIndices = function () {
  18963. if (!this._geometry) {
  18964. return 0;
  18965. }
  18966. return this._geometry.getTotalIndices();
  18967. };
  18968. /**
  18969. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  18970. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  18971. * Returns an empty array if the mesh has no geometry.
  18972. */
  18973. Mesh.prototype.getIndices = function (copyWhenShared) {
  18974. if (!this._geometry) {
  18975. return [];
  18976. }
  18977. return this._geometry.getIndices(copyWhenShared);
  18978. };
  18979. Object.defineProperty(Mesh.prototype, "isBlocked", {
  18980. get: function () {
  18981. return this._masterMesh !== null && this._masterMesh !== undefined;
  18982. },
  18983. enumerable: true,
  18984. configurable: true
  18985. });
  18986. /**
  18987. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  18988. */
  18989. Mesh.prototype.isReady = function () {
  18990. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18991. return false;
  18992. }
  18993. return _super.prototype.isReady.call(this);
  18994. };
  18995. /**
  18996. * Boolean : true if the mesh has been disposed.
  18997. */
  18998. Mesh.prototype.isDisposed = function () {
  18999. return this._isDisposed;
  19000. };
  19001. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  19002. get: function () {
  19003. return this._sideOrientation;
  19004. },
  19005. /**
  19006. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  19007. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  19008. */
  19009. set: function (sideO) {
  19010. this._sideOrientation = sideO;
  19011. },
  19012. enumerable: true,
  19013. configurable: true
  19014. });
  19015. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  19016. /**
  19017. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  19018. * This property is pertinent only for updatable parametric shapes.
  19019. */
  19020. get: function () {
  19021. return this._areNormalsFrozen;
  19022. },
  19023. enumerable: true,
  19024. configurable: true
  19025. });
  19026. /**
  19027. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19028. * It has no effect at all on other shapes.
  19029. * It prevents the mesh normals from being recomputed on next `positions` array update.
  19030. * Returns the Mesh.
  19031. */
  19032. Mesh.prototype.freezeNormals = function () {
  19033. this._areNormalsFrozen = true;
  19034. return this;
  19035. };
  19036. /**
  19037. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19038. * It has no effect at all on other shapes.
  19039. * It reactivates the mesh normals computation if it was previously frozen.
  19040. * Returns the Mesh.
  19041. */
  19042. Mesh.prototype.unfreezeNormals = function () {
  19043. this._areNormalsFrozen = false;
  19044. return this;
  19045. };
  19046. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  19047. /**
  19048. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  19049. */
  19050. set: function (count) {
  19051. this._overridenInstanceCount = count;
  19052. },
  19053. enumerable: true,
  19054. configurable: true
  19055. });
  19056. // Methods
  19057. Mesh.prototype._preActivate = function () {
  19058. var sceneRenderId = this.getScene().getRenderId();
  19059. if (this._preActivateId === sceneRenderId) {
  19060. return this;
  19061. }
  19062. this._preActivateId = sceneRenderId;
  19063. this._visibleInstances = null;
  19064. return this;
  19065. };
  19066. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19067. if (this._visibleInstances) {
  19068. this._visibleInstances.intermediateDefaultRenderId = renderId;
  19069. }
  19070. return this;
  19071. };
  19072. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  19073. if (!this._visibleInstances) {
  19074. this._visibleInstances = {};
  19075. this._visibleInstances.defaultRenderId = renderId;
  19076. this._visibleInstances.selfDefaultRenderId = this._renderId;
  19077. }
  19078. if (!this._visibleInstances[renderId]) {
  19079. this._visibleInstances[renderId] = new Array();
  19080. }
  19081. this._visibleInstances[renderId].push(instance);
  19082. return this;
  19083. };
  19084. /**
  19085. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  19086. * This means the mesh underlying bounding box and sphere are recomputed.
  19087. * Returns the Mesh.
  19088. */
  19089. Mesh.prototype.refreshBoundingInfo = function () {
  19090. if (this._boundingInfo.isLocked) {
  19091. return;
  19092. }
  19093. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19094. if (data) {
  19095. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  19096. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19097. }
  19098. if (this.subMeshes) {
  19099. for (var index = 0; index < this.subMeshes.length; index++) {
  19100. this.subMeshes[index].refreshBoundingInfo();
  19101. }
  19102. }
  19103. this._updateBoundingInfo();
  19104. return this;
  19105. };
  19106. Mesh.prototype._createGlobalSubMesh = function () {
  19107. var totalVertices = this.getTotalVertices();
  19108. if (!totalVertices || !this.getIndices()) {
  19109. return null;
  19110. }
  19111. this.releaseSubMeshes();
  19112. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  19113. };
  19114. Mesh.prototype.subdivide = function (count) {
  19115. if (count < 1) {
  19116. return;
  19117. }
  19118. var totalIndices = this.getTotalIndices();
  19119. var subdivisionSize = (totalIndices / count) | 0;
  19120. var offset = 0;
  19121. // Ensure that subdivisionSize is a multiple of 3
  19122. while (subdivisionSize % 3 !== 0) {
  19123. subdivisionSize++;
  19124. }
  19125. this.releaseSubMeshes();
  19126. for (var index = 0; index < count; index++) {
  19127. if (offset >= totalIndices) {
  19128. break;
  19129. }
  19130. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  19131. offset += subdivisionSize;
  19132. }
  19133. this.synchronizeInstances();
  19134. };
  19135. /**
  19136. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19137. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19138. * The `data` are either a numeric array either a Float32Array.
  19139. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19140. * 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).
  19141. * Note that a new underlying VertexBuffer object is created each call.
  19142. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19143. *
  19144. * Possible `kind` values :
  19145. * - BABYLON.VertexBuffer.PositionKind
  19146. * - BABYLON.VertexBuffer.UVKind
  19147. * - BABYLON.VertexBuffer.UV2Kind
  19148. * - BABYLON.VertexBuffer.UV3Kind
  19149. * - BABYLON.VertexBuffer.UV4Kind
  19150. * - BABYLON.VertexBuffer.UV5Kind
  19151. * - BABYLON.VertexBuffer.UV6Kind
  19152. * - BABYLON.VertexBuffer.ColorKind
  19153. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19154. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19155. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19156. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19157. *
  19158. * Returns the Mesh.
  19159. */
  19160. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19161. if (!this._geometry) {
  19162. var vertexData = new BABYLON.VertexData();
  19163. vertexData.set(data, kind);
  19164. var scene = this.getScene();
  19165. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  19166. }
  19167. else {
  19168. this._geometry.setVerticesData(kind, data, updatable, stride);
  19169. }
  19170. return this;
  19171. };
  19172. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  19173. if (updatable === void 0) { updatable = true; }
  19174. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  19175. return;
  19176. }
  19177. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  19178. };
  19179. /**
  19180. * Sets the mesh VertexBuffer.
  19181. * Returns the Mesh.
  19182. */
  19183. Mesh.prototype.setVerticesBuffer = function (buffer) {
  19184. if (!this._geometry) {
  19185. var scene = this.getScene();
  19186. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  19187. }
  19188. this._geometry.setVerticesBuffer(buffer);
  19189. return this;
  19190. };
  19191. /**
  19192. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19193. * If the mesh has no geometry, it is simply returned as it is.
  19194. * The `data` are either a numeric array either a Float32Array.
  19195. * No new underlying VertexBuffer object is created.
  19196. * 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.
  19197. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19198. *
  19199. * Possible `kind` values :
  19200. * - BABYLON.VertexBuffer.PositionKind
  19201. * - BABYLON.VertexBuffer.UVKind
  19202. * - BABYLON.VertexBuffer.UV2Kind
  19203. * - BABYLON.VertexBuffer.UV3Kind
  19204. * - BABYLON.VertexBuffer.UV4Kind
  19205. * - BABYLON.VertexBuffer.UV5Kind
  19206. * - BABYLON.VertexBuffer.UV6Kind
  19207. * - BABYLON.VertexBuffer.ColorKind
  19208. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19209. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19210. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19211. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19212. *
  19213. * Returns the Mesh.
  19214. */
  19215. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19216. if (!this._geometry) {
  19217. return;
  19218. }
  19219. if (!makeItUnique) {
  19220. this._geometry.updateVerticesData(kind, data, updateExtends);
  19221. }
  19222. else {
  19223. this.makeGeometryUnique();
  19224. this.updateVerticesData(kind, data, updateExtends, false);
  19225. }
  19226. return this;
  19227. };
  19228. /**
  19229. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  19230. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  19231. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  19232. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  19233. * Returns the Mesh.
  19234. */
  19235. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  19236. if (computeNormals === void 0) { computeNormals = true; }
  19237. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19238. positionFunction(positions);
  19239. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19240. if (computeNormals) {
  19241. var indices = this.getIndices();
  19242. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19243. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19244. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19245. }
  19246. return this;
  19247. };
  19248. /**
  19249. * Creates a un-shared specific occurence of the geometry for the mesh.
  19250. * Returns the Mesh.
  19251. */
  19252. Mesh.prototype.makeGeometryUnique = function () {
  19253. if (!this._geometry) {
  19254. return;
  19255. }
  19256. var oldGeometry = this._geometry;
  19257. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  19258. oldGeometry.releaseForMesh(this, true);
  19259. geometry.applyToMesh(this);
  19260. return this;
  19261. };
  19262. /**
  19263. * Sets the mesh indices.
  19264. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  19265. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19266. * This method creates a new index buffer each call.
  19267. * Returns the Mesh.
  19268. */
  19269. Mesh.prototype.setIndices = function (indices, totalVertices) {
  19270. if (!this._geometry) {
  19271. var vertexData = new BABYLON.VertexData();
  19272. vertexData.indices = indices;
  19273. var scene = this.getScene();
  19274. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  19275. }
  19276. else {
  19277. this._geometry.setIndices(indices, totalVertices);
  19278. }
  19279. return this;
  19280. };
  19281. /**
  19282. * Invert the geometry to move from a right handed system to a left handed one.
  19283. * Returns the Mesh.
  19284. */
  19285. Mesh.prototype.toLeftHanded = function () {
  19286. if (!this._geometry) {
  19287. return;
  19288. }
  19289. this._geometry.toLeftHanded();
  19290. return this;
  19291. };
  19292. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  19293. var engine = this.getScene().getEngine();
  19294. // Wireframe
  19295. var indexToBind;
  19296. if (this._unIndexed) {
  19297. indexToBind = null;
  19298. }
  19299. else {
  19300. switch (fillMode) {
  19301. case BABYLON.Material.PointFillMode:
  19302. indexToBind = null;
  19303. break;
  19304. case BABYLON.Material.WireFrameFillMode:
  19305. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  19306. break;
  19307. default:
  19308. case BABYLON.Material.TriangleFillMode:
  19309. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  19310. break;
  19311. }
  19312. }
  19313. // VBOs
  19314. this._geometry._bind(effect, indexToBind);
  19315. return this;
  19316. };
  19317. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  19318. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19319. return this;
  19320. }
  19321. this.onBeforeDrawObservable.notifyObservers(this);
  19322. var engine = this.getScene().getEngine();
  19323. // Draw order
  19324. switch (fillMode) {
  19325. case BABYLON.Material.PointFillMode:
  19326. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19327. break;
  19328. case BABYLON.Material.WireFrameFillMode:
  19329. if (this._unIndexed) {
  19330. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19331. }
  19332. else {
  19333. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  19334. }
  19335. break;
  19336. default:
  19337. if (this._unIndexed) {
  19338. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19339. }
  19340. else {
  19341. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  19342. }
  19343. }
  19344. return this;
  19345. };
  19346. /**
  19347. * Registers for this mesh a javascript function called just before the rendering process.
  19348. * This function is passed the current mesh.
  19349. * Return the Mesh.
  19350. */
  19351. Mesh.prototype.registerBeforeRender = function (func) {
  19352. this.onBeforeRenderObservable.add(func);
  19353. return this;
  19354. };
  19355. /**
  19356. * Disposes a previously registered javascript function called before the rendering.
  19357. * This function is passed the current mesh.
  19358. * Returns the Mesh.
  19359. */
  19360. Mesh.prototype.unregisterBeforeRender = function (func) {
  19361. this.onBeforeRenderObservable.removeCallback(func);
  19362. return this;
  19363. };
  19364. /**
  19365. * Registers for this mesh a javascript function called just after the rendering is complete.
  19366. * This function is passed the current mesh.
  19367. * Returns the Mesh.
  19368. */
  19369. Mesh.prototype.registerAfterRender = function (func) {
  19370. this.onAfterRenderObservable.add(func);
  19371. return this;
  19372. };
  19373. /**
  19374. * Disposes a previously registered javascript function called after the rendering.
  19375. * This function is passed the current mesh.
  19376. * Return the Mesh.
  19377. */
  19378. Mesh.prototype.unregisterAfterRender = function (func) {
  19379. this.onAfterRenderObservable.removeCallback(func);
  19380. return this;
  19381. };
  19382. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  19383. var scene = this.getScene();
  19384. this._batchCache.mustReturn = false;
  19385. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  19386. this._batchCache.visibleInstances[subMeshId] = null;
  19387. if (this._visibleInstances) {
  19388. var currentRenderId = scene.getRenderId();
  19389. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  19390. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  19391. var selfRenderId = this._renderId;
  19392. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  19393. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  19394. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  19395. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  19396. }
  19397. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  19398. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  19399. this._batchCache.mustReturn = true;
  19400. return this._batchCache;
  19401. }
  19402. if (currentRenderId !== selfRenderId) {
  19403. this._batchCache.renderSelf[subMeshId] = false;
  19404. }
  19405. }
  19406. this._renderIdForInstances[subMeshId] = currentRenderId;
  19407. }
  19408. return this._batchCache;
  19409. };
  19410. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  19411. var visibleInstances = batch.visibleInstances[subMesh._id];
  19412. var matricesCount = visibleInstances.length + 1;
  19413. var bufferSize = matricesCount * 16 * 4;
  19414. var currentInstancesBufferSize = this._instancesBufferSize;
  19415. var instancesBuffer = this._instancesBuffer;
  19416. while (this._instancesBufferSize < bufferSize) {
  19417. this._instancesBufferSize *= 2;
  19418. }
  19419. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  19420. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  19421. }
  19422. var offset = 0;
  19423. var instancesCount = 0;
  19424. var world = this.getWorldMatrix();
  19425. if (batch.renderSelf[subMesh._id]) {
  19426. world.copyToArray(this._instancesData, offset);
  19427. offset += 16;
  19428. instancesCount++;
  19429. }
  19430. if (visibleInstances) {
  19431. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  19432. var instance = visibleInstances[instanceIndex];
  19433. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  19434. offset += 16;
  19435. instancesCount++;
  19436. }
  19437. }
  19438. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  19439. if (instancesBuffer) {
  19440. instancesBuffer.dispose();
  19441. }
  19442. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  19443. this._instancesBuffer = instancesBuffer;
  19444. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  19445. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  19446. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  19447. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  19448. }
  19449. else {
  19450. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  19451. }
  19452. this.geometry._bind(effect);
  19453. this._draw(subMesh, fillMode, instancesCount);
  19454. engine.unbindInstanceAttributes();
  19455. return this;
  19456. };
  19457. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  19458. var scene = this.getScene();
  19459. var engine = scene.getEngine();
  19460. if (hardwareInstancedRendering) {
  19461. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  19462. }
  19463. else {
  19464. if (batch.renderSelf[subMesh._id]) {
  19465. // Draw
  19466. if (onBeforeDraw) {
  19467. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  19468. }
  19469. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  19470. }
  19471. if (batch.visibleInstances[subMesh._id]) {
  19472. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  19473. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  19474. // World
  19475. var world = instance.getWorldMatrix();
  19476. if (onBeforeDraw) {
  19477. onBeforeDraw(true, world, effectiveMaterial);
  19478. }
  19479. // Draw
  19480. this._draw(subMesh, fillMode);
  19481. }
  19482. }
  19483. }
  19484. return this;
  19485. };
  19486. /**
  19487. * Triggers the draw call for the mesh.
  19488. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  19489. * Returns the Mesh.
  19490. */
  19491. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  19492. var scene = this.getScene();
  19493. // Managing instances
  19494. var batch = this._getInstancesRenderList(subMesh._id);
  19495. if (batch.mustReturn) {
  19496. return this;
  19497. }
  19498. // Checking geometry state
  19499. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19500. return this;
  19501. }
  19502. var callbackIndex;
  19503. this.onBeforeRenderObservable.notifyObservers(this);
  19504. var engine = scene.getEngine();
  19505. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  19506. // Material
  19507. var effectiveMaterial = subMesh.getMaterial();
  19508. if (!effectiveMaterial) {
  19509. return this;
  19510. }
  19511. if (effectiveMaterial.storeEffectOnSubMeshes) {
  19512. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  19513. return this;
  19514. }
  19515. }
  19516. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  19517. return this;
  19518. }
  19519. // Outline - step 1
  19520. var savedDepthWrite = engine.getDepthWrite();
  19521. if (this.renderOutline) {
  19522. engine.setDepthWrite(false);
  19523. scene.getOutlineRenderer().render(subMesh, batch);
  19524. engine.setDepthWrite(savedDepthWrite);
  19525. }
  19526. var effect;
  19527. if (effectiveMaterial.storeEffectOnSubMeshes) {
  19528. effect = subMesh.effect;
  19529. }
  19530. else {
  19531. effect = effectiveMaterial.getEffect();
  19532. }
  19533. effectiveMaterial._preBind(effect);
  19534. // Bind
  19535. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  19536. this._bind(subMesh, effect, fillMode);
  19537. var world = this.getWorldMatrix();
  19538. if (effectiveMaterial.storeEffectOnSubMeshes) {
  19539. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  19540. }
  19541. else {
  19542. effectiveMaterial.bind(world, this);
  19543. }
  19544. // Alpha mode
  19545. if (enableAlphaMode) {
  19546. engine.setAlphaMode(effectiveMaterial.alphaMode);
  19547. }
  19548. // Draw
  19549. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  19550. // Unbind
  19551. effectiveMaterial.unbind();
  19552. // Outline - step 2
  19553. if (this.renderOutline && savedDepthWrite) {
  19554. engine.setDepthWrite(true);
  19555. engine.setColorWrite(false);
  19556. scene.getOutlineRenderer().render(subMesh, batch);
  19557. engine.setColorWrite(true);
  19558. }
  19559. // Overlay
  19560. if (this.renderOverlay) {
  19561. var currentMode = engine.getAlphaMode();
  19562. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19563. scene.getOutlineRenderer().render(subMesh, batch, true);
  19564. engine.setAlphaMode(currentMode);
  19565. }
  19566. this.onAfterRenderObservable.notifyObservers(this);
  19567. return this;
  19568. };
  19569. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  19570. if (isInstance) {
  19571. effectiveMaterial.bindOnlyWorldMatrix(world);
  19572. }
  19573. return this;
  19574. };
  19575. /**
  19576. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  19577. */
  19578. Mesh.prototype.getEmittedParticleSystems = function () {
  19579. var results = new Array();
  19580. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19581. var particleSystem = this.getScene().particleSystems[index];
  19582. if (particleSystem.emitter === this) {
  19583. results.push(particleSystem);
  19584. }
  19585. }
  19586. return results;
  19587. };
  19588. /**
  19589. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  19590. */
  19591. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  19592. var results = new Array();
  19593. var descendants = this.getDescendants();
  19594. descendants.push(this);
  19595. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19596. var particleSystem = this.getScene().particleSystems[index];
  19597. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  19598. results.push(particleSystem);
  19599. }
  19600. }
  19601. return results;
  19602. };
  19603. Mesh.prototype._checkDelayState = function () {
  19604. var scene = this.getScene();
  19605. if (this._geometry) {
  19606. this._geometry.load(scene);
  19607. }
  19608. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19609. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  19610. this._queueLoad(this, scene);
  19611. }
  19612. return this;
  19613. };
  19614. Mesh.prototype._queueLoad = function (mesh, scene) {
  19615. var _this = this;
  19616. scene._addPendingData(mesh);
  19617. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  19618. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  19619. if (data instanceof ArrayBuffer) {
  19620. _this._delayLoadingFunction(data, _this);
  19621. }
  19622. else {
  19623. _this._delayLoadingFunction(JSON.parse(data), _this);
  19624. }
  19625. _this.instances.forEach(function (instance) {
  19626. instance._syncSubMeshes();
  19627. });
  19628. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19629. scene._removePendingData(_this);
  19630. }, function () { }, scene.database, getBinaryData);
  19631. return this;
  19632. };
  19633. /**
  19634. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  19635. */
  19636. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  19637. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19638. return false;
  19639. }
  19640. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  19641. return false;
  19642. }
  19643. this._checkDelayState();
  19644. return true;
  19645. };
  19646. /**
  19647. * Sets the mesh material by the material or multiMaterial `id` property.
  19648. * The material `id` is a string identifying the material or the multiMaterial.
  19649. * This method returns the Mesh.
  19650. */
  19651. Mesh.prototype.setMaterialByID = function (id) {
  19652. var materials = this.getScene().materials;
  19653. var index;
  19654. for (index = 0; index < materials.length; index++) {
  19655. if (materials[index].id === id) {
  19656. this.material = materials[index];
  19657. return this;
  19658. }
  19659. }
  19660. // Multi
  19661. var multiMaterials = this.getScene().multiMaterials;
  19662. for (index = 0; index < multiMaterials.length; index++) {
  19663. if (multiMaterials[index].id === id) {
  19664. this.material = multiMaterials[index];
  19665. return this;
  19666. }
  19667. }
  19668. return this;
  19669. };
  19670. /**
  19671. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  19672. */
  19673. Mesh.prototype.getAnimatables = function () {
  19674. var results = [];
  19675. if (this.material) {
  19676. results.push(this.material);
  19677. }
  19678. if (this.skeleton) {
  19679. results.push(this.skeleton);
  19680. }
  19681. return results;
  19682. };
  19683. /**
  19684. * Modifies the mesh geometry according to the passed transformation matrix.
  19685. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  19686. * The mesh normals are modified accordingly the same transformation.
  19687. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19688. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19689. * Returns the Mesh.
  19690. */
  19691. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  19692. // Position
  19693. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19694. return this;
  19695. }
  19696. var submeshes = this.subMeshes.splice(0);
  19697. this._resetPointsArrayCache();
  19698. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19699. var temp = [];
  19700. var index;
  19701. for (index = 0; index < data.length; index += 3) {
  19702. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  19703. }
  19704. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  19705. // Normals
  19706. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19707. return this;
  19708. }
  19709. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19710. temp = [];
  19711. for (index = 0; index < data.length; index += 3) {
  19712. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  19713. }
  19714. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  19715. // flip faces?
  19716. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  19717. this.flipFaces();
  19718. }
  19719. // Restore submeshes
  19720. this.releaseSubMeshes();
  19721. this.subMeshes = submeshes;
  19722. return this;
  19723. };
  19724. /**
  19725. * Modifies the mesh geometry according to its own current World Matrix.
  19726. * The mesh World Matrix is then reset.
  19727. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  19728. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19729. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19730. * Returns the Mesh.
  19731. */
  19732. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  19733. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  19734. this.scaling.copyFromFloats(1, 1, 1);
  19735. this.position.copyFromFloats(0, 0, 0);
  19736. this.rotation.copyFromFloats(0, 0, 0);
  19737. //only if quaternion is already set
  19738. if (this.rotationQuaternion) {
  19739. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  19740. }
  19741. this._worldMatrix = BABYLON.Matrix.Identity();
  19742. return this;
  19743. };
  19744. // Cache
  19745. Mesh.prototype._resetPointsArrayCache = function () {
  19746. this._positions = null;
  19747. return this;
  19748. };
  19749. Mesh.prototype._generatePointsArray = function () {
  19750. if (this._positions)
  19751. return true;
  19752. this._positions = [];
  19753. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19754. if (!data) {
  19755. return false;
  19756. }
  19757. for (var index = 0; index < data.length; index += 3) {
  19758. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  19759. }
  19760. return true;
  19761. };
  19762. /**
  19763. * Returns a new Mesh object generated from the current mesh properties.
  19764. * This method must not get confused with createInstance().
  19765. * The parameter `name` is a string, the name given to the new mesh.
  19766. * The optional parameter `newParent` can be any Node object (default `null`).
  19767. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  19768. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  19769. */
  19770. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  19771. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19772. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  19773. };
  19774. /**
  19775. * Disposes the mesh.
  19776. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  19777. */
  19778. Mesh.prototype.dispose = function (doNotRecurse) {
  19779. var _this = this;
  19780. this.morphTargetManager = undefined;
  19781. if (this._geometry) {
  19782. this._geometry.releaseForMesh(this, true);
  19783. }
  19784. // Sources
  19785. var meshes = this.getScene().meshes;
  19786. meshes.forEach(function (mesh) {
  19787. if (mesh._source && mesh._source === _this) {
  19788. mesh._source = null;
  19789. }
  19790. });
  19791. this._source = null;
  19792. // Instances
  19793. if (this._instancesBuffer) {
  19794. this._instancesBuffer.dispose();
  19795. this._instancesBuffer = null;
  19796. }
  19797. while (this.instances.length) {
  19798. this.instances[0].dispose();
  19799. }
  19800. // Highlight layers.
  19801. var highlightLayers = this.getScene().highlightLayers;
  19802. for (var i = 0; i < highlightLayers.length; i++) {
  19803. var highlightLayer = highlightLayers[i];
  19804. if (highlightLayer) {
  19805. highlightLayer.removeMesh(this);
  19806. highlightLayer.removeExcludedMesh(this);
  19807. }
  19808. }
  19809. _super.prototype.dispose.call(this, doNotRecurse);
  19810. };
  19811. /**
  19812. * Modifies the mesh geometry according to a displacement map.
  19813. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  19814. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19815. * This method returns nothing.
  19816. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  19817. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19818. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  19819. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  19820. * The parameter `uvScale` is an optional vector2 used to scale UV.
  19821. *
  19822. * Returns the Mesh.
  19823. */
  19824. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  19825. var _this = this;
  19826. var scene = this.getScene();
  19827. var onload = function (img) {
  19828. // Getting height map data
  19829. var canvas = document.createElement("canvas");
  19830. var context = canvas.getContext("2d");
  19831. var heightMapWidth = img.width;
  19832. var heightMapHeight = img.height;
  19833. canvas.width = heightMapWidth;
  19834. canvas.height = heightMapHeight;
  19835. context.drawImage(img, 0, 0);
  19836. // Create VertexData from map data
  19837. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  19838. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  19839. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  19840. //execute success callback, if set
  19841. if (onSuccess) {
  19842. onSuccess(_this);
  19843. }
  19844. };
  19845. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  19846. return this;
  19847. };
  19848. /**
  19849. * Modifies the mesh geometry according to a displacementMap buffer.
  19850. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  19851. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19852. * This method returns nothing.
  19853. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  19854. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  19855. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19856. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  19857. * The parameter `uvScale` is an optional vector2 used to scale UV.
  19858. *
  19859. * Returns the Mesh.
  19860. */
  19861. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  19862. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  19863. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  19864. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19865. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  19866. return this;
  19867. }
  19868. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19869. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19870. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19871. var position = BABYLON.Vector3.Zero();
  19872. var normal = BABYLON.Vector3.Zero();
  19873. var uv = BABYLON.Vector2.Zero();
  19874. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  19875. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  19876. for (var index = 0; index < positions.length; index += 3) {
  19877. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  19878. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  19879. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  19880. // Compute height
  19881. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  19882. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  19883. var pos = (u + v * heightMapWidth) * 4;
  19884. var r = buffer[pos] / 255.0;
  19885. var g = buffer[pos + 1] / 255.0;
  19886. var b = buffer[pos + 2] / 255.0;
  19887. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  19888. normal.normalize();
  19889. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  19890. position = position.add(normal);
  19891. position.toArray(positions, index);
  19892. }
  19893. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  19894. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  19895. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19896. return this;
  19897. };
  19898. /**
  19899. * Modify the mesh to get a flat shading rendering.
  19900. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  19901. * This method returns the Mesh.
  19902. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  19903. */
  19904. Mesh.prototype.convertToFlatShadedMesh = function () {
  19905. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  19906. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19907. var kinds = this.getVerticesDataKinds();
  19908. var vbs = [];
  19909. var data = [];
  19910. var newdata = [];
  19911. var updatableNormals = false;
  19912. var kindIndex;
  19913. var kind;
  19914. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19915. kind = kinds[kindIndex];
  19916. var vertexBuffer = this.getVertexBuffer(kind);
  19917. if (kind === BABYLON.VertexBuffer.NormalKind) {
  19918. updatableNormals = vertexBuffer.isUpdatable();
  19919. kinds.splice(kindIndex, 1);
  19920. kindIndex--;
  19921. continue;
  19922. }
  19923. vbs[kind] = vertexBuffer;
  19924. data[kind] = vbs[kind].getData();
  19925. newdata[kind] = [];
  19926. }
  19927. // Save previous submeshes
  19928. var previousSubmeshes = this.subMeshes.slice(0);
  19929. var indices = this.getIndices();
  19930. var totalIndices = this.getTotalIndices();
  19931. // Generating unique vertices per face
  19932. var index;
  19933. for (index = 0; index < totalIndices; index++) {
  19934. var vertexIndex = indices[index];
  19935. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19936. kind = kinds[kindIndex];
  19937. var stride = vbs[kind].getStrideSize();
  19938. for (var offset = 0; offset < stride; offset++) {
  19939. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19940. }
  19941. }
  19942. }
  19943. // Updating faces & normal
  19944. var normals = [];
  19945. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  19946. for (index = 0; index < totalIndices; index += 3) {
  19947. indices[index] = index;
  19948. indices[index + 1] = index + 1;
  19949. indices[index + 2] = index + 2;
  19950. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  19951. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  19952. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  19953. var p1p2 = p1.subtract(p2);
  19954. var p3p2 = p3.subtract(p2);
  19955. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  19956. // Store same normals for every vertex
  19957. for (var localIndex = 0; localIndex < 3; localIndex++) {
  19958. normals.push(normal.x);
  19959. normals.push(normal.y);
  19960. normals.push(normal.z);
  19961. }
  19962. }
  19963. this.setIndices(indices);
  19964. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  19965. // Updating vertex buffers
  19966. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19967. kind = kinds[kindIndex];
  19968. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19969. }
  19970. // Updating submeshes
  19971. this.releaseSubMeshes();
  19972. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19973. var previousOne = previousSubmeshes[submeshIndex];
  19974. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19975. }
  19976. this.synchronizeInstances();
  19977. return this;
  19978. };
  19979. /**
  19980. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  19981. * In other words, more vertices, no more indices and a single bigger VBO.
  19982. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  19983. * Returns the Mesh.
  19984. */
  19985. Mesh.prototype.convertToUnIndexedMesh = function () {
  19986. /// <summary>Remove indices by unfolding faces into buffers</summary>
  19987. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19988. var kinds = this.getVerticesDataKinds();
  19989. var vbs = [];
  19990. var data = [];
  19991. var newdata = [];
  19992. var updatableNormals = false;
  19993. var kindIndex;
  19994. var kind;
  19995. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19996. kind = kinds[kindIndex];
  19997. var vertexBuffer = this.getVertexBuffer(kind);
  19998. vbs[kind] = vertexBuffer;
  19999. data[kind] = vbs[kind].getData();
  20000. newdata[kind] = [];
  20001. }
  20002. // Save previous submeshes
  20003. var previousSubmeshes = this.subMeshes.slice(0);
  20004. var indices = this.getIndices();
  20005. var totalIndices = this.getTotalIndices();
  20006. // Generating unique vertices per face
  20007. var index;
  20008. for (index = 0; index < totalIndices; index++) {
  20009. var vertexIndex = indices[index];
  20010. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20011. kind = kinds[kindIndex];
  20012. var stride = vbs[kind].getStrideSize();
  20013. for (var offset = 0; offset < stride; offset++) {
  20014. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20015. }
  20016. }
  20017. }
  20018. // Updating indices
  20019. for (index = 0; index < totalIndices; index += 3) {
  20020. indices[index] = index;
  20021. indices[index + 1] = index + 1;
  20022. indices[index + 2] = index + 2;
  20023. }
  20024. this.setIndices(indices);
  20025. // Updating vertex buffers
  20026. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20027. kind = kinds[kindIndex];
  20028. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20029. }
  20030. // Updating submeshes
  20031. this.releaseSubMeshes();
  20032. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20033. var previousOne = previousSubmeshes[submeshIndex];
  20034. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20035. }
  20036. this._unIndexed = true;
  20037. this.synchronizeInstances();
  20038. return this;
  20039. };
  20040. /**
  20041. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  20042. * This method returns the Mesh.
  20043. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  20044. */
  20045. Mesh.prototype.flipFaces = function (flipNormals) {
  20046. if (flipNormals === void 0) { flipNormals = false; }
  20047. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  20048. var i;
  20049. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20050. for (i = 0; i < vertex_data.normals.length; i++) {
  20051. vertex_data.normals[i] *= -1;
  20052. }
  20053. }
  20054. var temp;
  20055. for (i = 0; i < vertex_data.indices.length; i += 3) {
  20056. // reassign indices
  20057. temp = vertex_data.indices[i + 1];
  20058. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  20059. vertex_data.indices[i + 2] = temp;
  20060. }
  20061. vertex_data.applyToMesh(this);
  20062. return this;
  20063. };
  20064. // Instances
  20065. /**
  20066. * Creates a new InstancedMesh object from the mesh model.
  20067. * An instance shares the same properties and the same material than its model.
  20068. * Only these properties of each instance can then be set individually :
  20069. * - position
  20070. * - rotation
  20071. * - rotationQuaternion
  20072. * - setPivotMatrix
  20073. * - scaling
  20074. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  20075. * Warning : this method is not supported for Line mesh and LineSystem
  20076. */
  20077. Mesh.prototype.createInstance = function (name) {
  20078. return new BABYLON.InstancedMesh(name, this);
  20079. };
  20080. /**
  20081. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  20082. * After this call, all the mesh instances have the same submeshes than the current mesh.
  20083. * This method returns the Mesh.
  20084. */
  20085. Mesh.prototype.synchronizeInstances = function () {
  20086. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  20087. var instance = this.instances[instanceIndex];
  20088. instance._syncSubMeshes();
  20089. }
  20090. return this;
  20091. };
  20092. /**
  20093. * Simplify the mesh according to the given array of settings.
  20094. * Function will return immediately and will simplify async. It returns the Mesh.
  20095. * @param settings a collection of simplification settings.
  20096. * @param parallelProcessing should all levels calculate parallel or one after the other.
  20097. * @param type the type of simplification to run.
  20098. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  20099. */
  20100. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  20101. if (parallelProcessing === void 0) { parallelProcessing = true; }
  20102. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  20103. this.getScene().simplificationQueue.addTask({
  20104. settings: settings,
  20105. parallelProcessing: parallelProcessing,
  20106. mesh: this,
  20107. simplificationType: simplificationType,
  20108. successCallback: successCallback
  20109. });
  20110. return this;
  20111. };
  20112. /**
  20113. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  20114. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  20115. * This should be used together with the simplification to avoid disappearing triangles.
  20116. * Returns the Mesh.
  20117. * @param successCallback an optional success callback to be called after the optimization finished.
  20118. */
  20119. Mesh.prototype.optimizeIndices = function (successCallback) {
  20120. var _this = this;
  20121. var indices = this.getIndices();
  20122. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20123. var vectorPositions = [];
  20124. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  20125. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  20126. }
  20127. var dupes = [];
  20128. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  20129. var realPos = vectorPositions.length - 1 - iteration;
  20130. var testedPosition = vectorPositions[realPos];
  20131. for (var j = 0; j < realPos; ++j) {
  20132. var againstPosition = vectorPositions[j];
  20133. if (testedPosition.equals(againstPosition)) {
  20134. dupes[realPos] = j;
  20135. break;
  20136. }
  20137. }
  20138. }, function () {
  20139. for (var i = 0; i < indices.length; ++i) {
  20140. indices[i] = dupes[indices[i]] || indices[i];
  20141. }
  20142. //indices are now reordered
  20143. var originalSubMeshes = _this.subMeshes.slice(0);
  20144. _this.setIndices(indices);
  20145. _this.subMeshes = originalSubMeshes;
  20146. if (successCallback) {
  20147. successCallback(_this);
  20148. }
  20149. });
  20150. return this;
  20151. };
  20152. Mesh.prototype.serialize = function (serializationObject) {
  20153. serializationObject.name = this.name;
  20154. serializationObject.id = this.id;
  20155. serializationObject.type = this.getClassName();
  20156. if (BABYLON.Tags.HasTags(this)) {
  20157. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20158. }
  20159. serializationObject.position = this.position.asArray();
  20160. if (this.rotationQuaternion) {
  20161. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  20162. }
  20163. else if (this.rotation) {
  20164. serializationObject.rotation = this.rotation.asArray();
  20165. }
  20166. serializationObject.scaling = this.scaling.asArray();
  20167. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  20168. serializationObject.isEnabled = this.isEnabled();
  20169. serializationObject.isVisible = this.isVisible;
  20170. serializationObject.infiniteDistance = this.infiniteDistance;
  20171. serializationObject.pickable = this.isPickable;
  20172. serializationObject.receiveShadows = this.receiveShadows;
  20173. serializationObject.billboardMode = this.billboardMode;
  20174. serializationObject.visibility = this.visibility;
  20175. serializationObject.checkCollisions = this.checkCollisions;
  20176. serializationObject.isBlocker = this.isBlocker;
  20177. // Parent
  20178. if (this.parent) {
  20179. serializationObject.parentId = this.parent.id;
  20180. }
  20181. // Geometry
  20182. var geometry = this._geometry;
  20183. if (geometry) {
  20184. var geometryId = geometry.id;
  20185. serializationObject.geometryId = geometryId;
  20186. // SubMeshes
  20187. serializationObject.subMeshes = [];
  20188. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20189. var subMesh = this.subMeshes[subIndex];
  20190. serializationObject.subMeshes.push({
  20191. materialIndex: subMesh.materialIndex,
  20192. verticesStart: subMesh.verticesStart,
  20193. verticesCount: subMesh.verticesCount,
  20194. indexStart: subMesh.indexStart,
  20195. indexCount: subMesh.indexCount
  20196. });
  20197. }
  20198. }
  20199. // Material
  20200. if (this.material) {
  20201. serializationObject.materialId = this.material.id;
  20202. }
  20203. else {
  20204. this.material = null;
  20205. }
  20206. // Morph targets
  20207. if (this.morphTargetManager) {
  20208. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  20209. }
  20210. // Skeleton
  20211. if (this.skeleton) {
  20212. serializationObject.skeletonId = this.skeleton.id;
  20213. }
  20214. // Physics
  20215. //TODO implement correct serialization for physics impostors.
  20216. if (this.getPhysicsImpostor()) {
  20217. var impostor = this.getPhysicsImpostor();
  20218. serializationObject.physicsMass = impostor.getParam("mass");
  20219. serializationObject.physicsFriction = impostor.getParam("friction");
  20220. serializationObject.physicsRestitution = impostor.getParam("mass");
  20221. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  20222. }
  20223. // Metadata
  20224. if (this.metadata) {
  20225. serializationObject.metadata = this.metadata;
  20226. }
  20227. // Instances
  20228. serializationObject.instances = [];
  20229. for (var index = 0; index < this.instances.length; index++) {
  20230. var instance = this.instances[index];
  20231. var serializationInstance = {
  20232. name: instance.name,
  20233. position: instance.position.asArray(),
  20234. scaling: instance.scaling.asArray()
  20235. };
  20236. if (instance.rotationQuaternion) {
  20237. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  20238. }
  20239. else if (instance.rotation) {
  20240. serializationInstance.rotation = instance.rotation.asArray();
  20241. }
  20242. serializationObject.instances.push(serializationInstance);
  20243. // Animations
  20244. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  20245. serializationInstance.ranges = instance.serializeAnimationRanges();
  20246. }
  20247. //
  20248. // Animations
  20249. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20250. serializationObject.ranges = this.serializeAnimationRanges();
  20251. // Layer mask
  20252. serializationObject.layerMask = this.layerMask;
  20253. // Alpha
  20254. serializationObject.alphaIndex = this.alphaIndex;
  20255. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  20256. // Overlay
  20257. serializationObject.overlayAlpha = this.overlayAlpha;
  20258. serializationObject.overlayColor = this.overlayColor.asArray();
  20259. serializationObject.renderOverlay = this.renderOverlay;
  20260. // Fog
  20261. serializationObject.applyFog = this.applyFog;
  20262. // Action Manager
  20263. if (this.actionManager) {
  20264. serializationObject.actions = this.actionManager.serialize(this.name);
  20265. }
  20266. };
  20267. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  20268. if (!this.geometry) {
  20269. return;
  20270. }
  20271. this._markSubMeshesAsAttributesDirty();
  20272. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  20273. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  20274. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  20275. this.morphTargetManager = undefined;
  20276. return;
  20277. }
  20278. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  20279. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  20280. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  20281. if (morphTarget.hasNormals) {
  20282. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  20283. }
  20284. if (morphTarget.hasTangents) {
  20285. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  20286. }
  20287. }
  20288. }
  20289. else {
  20290. var index = 0;
  20291. // Positions
  20292. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  20293. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  20294. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  20295. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  20296. }
  20297. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  20298. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  20299. }
  20300. index++;
  20301. }
  20302. }
  20303. };
  20304. // Statics
  20305. /**
  20306. * Returns a new Mesh object what is a deep copy of the passed mesh.
  20307. * The parameter `parsedMesh` is the mesh to be copied.
  20308. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20309. */
  20310. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  20311. var mesh;
  20312. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  20313. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  20314. }
  20315. else {
  20316. mesh = new Mesh(parsedMesh.name, scene);
  20317. }
  20318. mesh.id = parsedMesh.id;
  20319. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20320. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20321. if (parsedMesh.metadata !== undefined) {
  20322. mesh.metadata = parsedMesh.metadata;
  20323. }
  20324. if (parsedMesh.rotationQuaternion) {
  20325. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20326. }
  20327. else if (parsedMesh.rotation) {
  20328. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20329. }
  20330. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20331. if (parsedMesh.localMatrix) {
  20332. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20333. }
  20334. else if (parsedMesh.pivotMatrix) {
  20335. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20336. }
  20337. mesh.setEnabled(parsedMesh.isEnabled);
  20338. mesh.isVisible = parsedMesh.isVisible;
  20339. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20340. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20341. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20342. if (parsedMesh.applyFog !== undefined) {
  20343. mesh.applyFog = parsedMesh.applyFog;
  20344. }
  20345. if (parsedMesh.pickable !== undefined) {
  20346. mesh.isPickable = parsedMesh.pickable;
  20347. }
  20348. if (parsedMesh.alphaIndex !== undefined) {
  20349. mesh.alphaIndex = parsedMesh.alphaIndex;
  20350. }
  20351. mesh.receiveShadows = parsedMesh.receiveShadows;
  20352. mesh.billboardMode = parsedMesh.billboardMode;
  20353. if (parsedMesh.visibility !== undefined) {
  20354. mesh.visibility = parsedMesh.visibility;
  20355. }
  20356. mesh.checkCollisions = parsedMesh.checkCollisions;
  20357. if (parsedMesh.isBlocker !== undefined) {
  20358. mesh.isBlocker = parsedMesh.isBlocker;
  20359. }
  20360. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20361. // freezeWorldMatrix
  20362. if (parsedMesh.freezeWorldMatrix) {
  20363. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20364. }
  20365. // Parent
  20366. if (parsedMesh.parentId) {
  20367. mesh._waitingParentId = parsedMesh.parentId;
  20368. }
  20369. // Actions
  20370. if (parsedMesh.actions !== undefined) {
  20371. mesh._waitingActions = parsedMesh.actions;
  20372. }
  20373. // Overlay
  20374. if (parsedMesh.overlayAlpha !== undefined) {
  20375. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  20376. }
  20377. if (parsedMesh.overlayColor !== undefined) {
  20378. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  20379. }
  20380. if (parsedMesh.renderOverlay !== undefined) {
  20381. mesh.renderOverlay = parsedMesh.renderOverlay;
  20382. }
  20383. // Geometry
  20384. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20385. if (parsedMesh.delayLoadingFile) {
  20386. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20387. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20388. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20389. if (parsedMesh._binaryInfo) {
  20390. mesh._binaryInfo = parsedMesh._binaryInfo;
  20391. }
  20392. mesh._delayInfo = [];
  20393. if (parsedMesh.hasUVs) {
  20394. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20395. }
  20396. if (parsedMesh.hasUVs2) {
  20397. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20398. }
  20399. if (parsedMesh.hasUVs3) {
  20400. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20401. }
  20402. if (parsedMesh.hasUVs4) {
  20403. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20404. }
  20405. if (parsedMesh.hasUVs5) {
  20406. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20407. }
  20408. if (parsedMesh.hasUVs6) {
  20409. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20410. }
  20411. if (parsedMesh.hasColors) {
  20412. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20413. }
  20414. if (parsedMesh.hasMatricesIndices) {
  20415. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20416. }
  20417. if (parsedMesh.hasMatricesWeights) {
  20418. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20419. }
  20420. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  20421. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20422. mesh._checkDelayState();
  20423. }
  20424. }
  20425. else {
  20426. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  20427. }
  20428. // Material
  20429. if (parsedMesh.materialId) {
  20430. mesh.setMaterialByID(parsedMesh.materialId);
  20431. }
  20432. else {
  20433. mesh.material = null;
  20434. }
  20435. // Morph targets
  20436. if (parsedMesh.morphTargetManagerId > -1) {
  20437. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  20438. }
  20439. // Skeleton
  20440. if (parsedMesh.skeletonId > -1) {
  20441. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20442. if (parsedMesh.numBoneInfluencers) {
  20443. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  20444. }
  20445. }
  20446. // Animations
  20447. if (parsedMesh.animations) {
  20448. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20449. var parsedAnimation = parsedMesh.animations[animationIndex];
  20450. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20451. }
  20452. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  20453. }
  20454. if (parsedMesh.autoAnimate) {
  20455. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  20456. }
  20457. // Layer Mask
  20458. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20459. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20460. }
  20461. else {
  20462. mesh.layerMask = 0x0FFFFFFF;
  20463. }
  20464. // Physics
  20465. if (parsedMesh.physicsImpostor) {
  20466. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  20467. mass: parsedMesh.physicsMass,
  20468. friction: parsedMesh.physicsFriction,
  20469. restitution: parsedMesh.physicsRestitution
  20470. }, scene);
  20471. }
  20472. // Instances
  20473. if (parsedMesh.instances) {
  20474. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20475. var parsedInstance = parsedMesh.instances[index];
  20476. var instance = mesh.createInstance(parsedInstance.name);
  20477. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20478. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20479. if (parsedInstance.parentId) {
  20480. instance._waitingParentId = parsedInstance.parentId;
  20481. }
  20482. if (parsedInstance.rotationQuaternion) {
  20483. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20484. }
  20485. else if (parsedInstance.rotation) {
  20486. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20487. }
  20488. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20489. instance.checkCollisions = mesh.checkCollisions;
  20490. if (parsedMesh.animations) {
  20491. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20492. parsedAnimation = parsedMesh.animations[animationIndex];
  20493. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20494. }
  20495. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  20496. }
  20497. }
  20498. }
  20499. return mesh;
  20500. };
  20501. /**
  20502. * Creates a ribbon mesh.
  20503. * Please consider using the same method from the MeshBuilder class instead.
  20504. * 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.
  20505. *
  20506. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20507. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20508. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20509. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20510. * 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.
  20511. * 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.
  20512. * 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
  20513. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20514. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20515. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20516. */
  20517. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  20518. return BABYLON.MeshBuilder.CreateRibbon(name, {
  20519. pathArray: pathArray,
  20520. closeArray: closeArray,
  20521. closePath: closePath,
  20522. offset: offset,
  20523. updatable: updatable,
  20524. sideOrientation: sideOrientation,
  20525. instance: instance
  20526. }, scene);
  20527. };
  20528. /**
  20529. * Creates a plane polygonal mesh. By default, this is a disc.
  20530. * Please consider using the same method from the MeshBuilder class instead.
  20531. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20532. * 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.
  20533. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20534. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20535. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20536. */
  20537. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  20538. var options = {
  20539. radius: radius,
  20540. tessellation: tessellation,
  20541. sideOrientation: sideOrientation,
  20542. updatable: updatable
  20543. };
  20544. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  20545. };
  20546. /**
  20547. * Creates a box mesh.
  20548. * Please consider using the same method from the MeshBuilder class instead.
  20549. * The parameter `size` sets the size (float) of each box side (default 1).
  20550. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20551. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20552. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20553. */
  20554. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  20555. var options = {
  20556. size: size,
  20557. sideOrientation: sideOrientation,
  20558. updatable: updatable
  20559. };
  20560. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  20561. };
  20562. /**
  20563. * Creates a sphere mesh.
  20564. * Please consider using the same method from the MeshBuilder class instead.
  20565. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20566. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20567. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20568. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20569. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20570. */
  20571. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  20572. var options = {
  20573. segments: segments,
  20574. diameterX: diameter,
  20575. diameterY: diameter,
  20576. diameterZ: diameter,
  20577. sideOrientation: sideOrientation,
  20578. updatable: updatable
  20579. };
  20580. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  20581. };
  20582. /**
  20583. * Creates a cylinder or a cone mesh.
  20584. * Please consider using the same method from the MeshBuilder class instead.
  20585. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20586. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20587. * 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.
  20588. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20589. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20590. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20591. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20592. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20593. */
  20594. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  20595. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  20596. if (scene !== undefined) {
  20597. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  20598. updatable = scene;
  20599. }
  20600. scene = subdivisions;
  20601. subdivisions = 1;
  20602. }
  20603. var options = {
  20604. height: height,
  20605. diameterTop: diameterTop,
  20606. diameterBottom: diameterBottom,
  20607. tessellation: tessellation,
  20608. subdivisions: subdivisions,
  20609. sideOrientation: sideOrientation,
  20610. updatable: updatable
  20611. };
  20612. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  20613. };
  20614. // Torus (Code from SharpDX.org)
  20615. /**
  20616. * Creates a torus mesh.
  20617. * Please consider using the same method from the MeshBuilder class instead.
  20618. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  20619. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  20620. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  20621. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20622. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20623. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20624. */
  20625. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  20626. var options = {
  20627. diameter: diameter,
  20628. thickness: thickness,
  20629. tessellation: tessellation,
  20630. sideOrientation: sideOrientation,
  20631. updatable: updatable
  20632. };
  20633. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  20634. };
  20635. /**
  20636. * Creates a torus knot mesh.
  20637. * Please consider using the same method from the MeshBuilder class instead.
  20638. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  20639. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  20640. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  20641. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  20642. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20643. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20644. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20645. */
  20646. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  20647. var options = {
  20648. radius: radius,
  20649. tube: tube,
  20650. radialSegments: radialSegments,
  20651. tubularSegments: tubularSegments,
  20652. p: p,
  20653. q: q,
  20654. sideOrientation: sideOrientation,
  20655. updatable: updatable
  20656. };
  20657. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  20658. };
  20659. /**
  20660. * Creates a line mesh.
  20661. * Please consider using the same method from the MeshBuilder class instead.
  20662. * 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.
  20663. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20664. * The parameter `points` is an array successive Vector3.
  20665. * 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
  20666. * When updating an instance, remember that only point positions can change, not the number of points.
  20667. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20668. */
  20669. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  20670. var options = {
  20671. points: points,
  20672. updatable: updatable,
  20673. instance: instance
  20674. };
  20675. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  20676. };
  20677. /**
  20678. * Creates a dashed line mesh.
  20679. * Please consider using the same method from the MeshBuilder class instead.
  20680. * 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.
  20681. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20682. * The parameter `points` is an array successive Vector3.
  20683. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  20684. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  20685. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  20686. * 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
  20687. * When updating an instance, remember that only point positions can change, not the number of points.
  20688. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20689. */
  20690. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  20691. var options = {
  20692. points: points,
  20693. dashSize: dashSize,
  20694. gapSize: gapSize,
  20695. dashNb: dashNb,
  20696. updatable: updatable,
  20697. instance: instance
  20698. };
  20699. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  20700. };
  20701. /**
  20702. * Creates an extruded shape mesh.
  20703. * 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.
  20704. * Please consider using the same method from the MeshBuilder class instead.
  20705. *
  20706. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20707. * 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
  20708. * extruded along the Z axis.
  20709. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20710. * 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.
  20711. * The parameter `scale` (float, default 1) is the value to scale the shape.
  20712. * 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
  20713. * 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
  20714. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20715. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20716. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20717. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20718. */
  20719. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  20720. var options = {
  20721. shape: shape,
  20722. path: path,
  20723. scale: scale,
  20724. rotation: rotation,
  20725. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20726. sideOrientation: sideOrientation,
  20727. instance: instance,
  20728. updatable: updatable
  20729. };
  20730. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  20731. };
  20732. /**
  20733. * Creates an custom extruded shape mesh.
  20734. * 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.
  20735. * Please consider using the same method from the MeshBuilder class instead.
  20736. *
  20737. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20738. * 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
  20739. * extruded along the Z axis.
  20740. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20741. * 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
  20742. * and the distance of this point from the begining of the path :
  20743. * ```javascript
  20744. * var rotationFunction = function(i, distance) {
  20745. * // do things
  20746. * return rotationValue; }
  20747. * ```
  20748. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  20749. * 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
  20750. * and the distance of this point from the begining of the path :
  20751. * ```javascript
  20752. * var scaleFunction = function(i, distance) {
  20753. * // do things
  20754. * return scaleValue;}
  20755. * ```
  20756. * It must returns a float value that will be the scale value applied to the shape on each path point.
  20757. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  20758. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  20759. * 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
  20760. * 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
  20761. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20762. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20763. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20764. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20765. */
  20766. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  20767. var options = {
  20768. shape: shape,
  20769. path: path,
  20770. scaleFunction: scaleFunction,
  20771. rotationFunction: rotationFunction,
  20772. ribbonCloseArray: ribbonCloseArray,
  20773. ribbonClosePath: ribbonClosePath,
  20774. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20775. sideOrientation: sideOrientation,
  20776. instance: instance,
  20777. updatable: updatable
  20778. };
  20779. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  20780. };
  20781. /**
  20782. * Creates lathe mesh.
  20783. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  20784. * Please consider using the same method from the MeshBuilder class instead.
  20785. * 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
  20786. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  20787. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  20788. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  20789. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20790. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20791. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20792. */
  20793. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  20794. var options = {
  20795. shape: shape,
  20796. radius: radius,
  20797. tessellation: tessellation,
  20798. sideOrientation: sideOrientation,
  20799. updatable: updatable
  20800. };
  20801. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  20802. };
  20803. /**
  20804. * Creates a plane mesh.
  20805. * Please consider using the same method from the MeshBuilder class instead.
  20806. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  20807. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20808. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20809. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20810. */
  20811. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  20812. var options = {
  20813. size: size,
  20814. width: size,
  20815. height: size,
  20816. sideOrientation: sideOrientation,
  20817. updatable: updatable
  20818. };
  20819. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  20820. };
  20821. /**
  20822. * Creates a ground mesh.
  20823. * Please consider using the same method from the MeshBuilder class instead.
  20824. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  20825. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  20826. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20827. */
  20828. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  20829. var options = {
  20830. width: width,
  20831. height: height,
  20832. subdivisions: subdivisions,
  20833. updatable: updatable
  20834. };
  20835. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  20836. };
  20837. /**
  20838. * Creates a tiled ground mesh.
  20839. * Please consider using the same method from the MeshBuilder class instead.
  20840. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  20841. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  20842. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  20843. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  20844. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  20845. * numbers of subdivisions on the ground width and height of each tile.
  20846. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20847. */
  20848. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  20849. var options = {
  20850. xmin: xmin,
  20851. zmin: zmin,
  20852. xmax: xmax,
  20853. zmax: zmax,
  20854. subdivisions: subdivisions,
  20855. precision: precision,
  20856. updatable: updatable
  20857. };
  20858. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  20859. };
  20860. /**
  20861. * Creates a ground mesh from a height map.
  20862. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  20863. * Please consider using the same method from the MeshBuilder class instead.
  20864. * The parameter `url` sets the URL of the height map image resource.
  20865. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  20866. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  20867. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  20868. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  20869. * 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).
  20870. * This function is passed the newly built mesh :
  20871. * ```javascript
  20872. * function(mesh) { // do things
  20873. * return; }
  20874. * ```
  20875. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20876. */
  20877. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  20878. var options = {
  20879. width: width,
  20880. height: height,
  20881. subdivisions: subdivisions,
  20882. minHeight: minHeight,
  20883. maxHeight: maxHeight,
  20884. updatable: updatable,
  20885. onReady: onReady
  20886. };
  20887. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  20888. };
  20889. /**
  20890. * Creates a tube mesh.
  20891. * 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.
  20892. * Please consider using the same method from the MeshBuilder class instead.
  20893. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  20894. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  20895. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  20896. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  20897. * 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.
  20898. * It must return a radius value (positive float) :
  20899. * ```javascript
  20900. * var radiusFunction = function(i, distance) {
  20901. * // do things
  20902. * return radius; }
  20903. * ```
  20904. * 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
  20905. * 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
  20906. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20907. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20908. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20909. */
  20910. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  20911. var options = {
  20912. path: path,
  20913. radius: radius,
  20914. tessellation: tessellation,
  20915. radiusFunction: radiusFunction,
  20916. arc: 1,
  20917. cap: cap,
  20918. updatable: updatable,
  20919. sideOrientation: sideOrientation,
  20920. instance: instance
  20921. };
  20922. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  20923. };
  20924. /**
  20925. * Creates a polyhedron mesh.
  20926. * Please consider using the same method from the MeshBuilder class instead.
  20927. * 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
  20928. * to choose the wanted type.
  20929. * The parameter `size` (positive float, default 1) sets the polygon size.
  20930. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  20931. * 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`.
  20932. * 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
  20933. * 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)`).
  20934. * 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
  20935. * 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.
  20936. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20937. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20938. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20939. */
  20940. Mesh.CreatePolyhedron = function (name, options, scene) {
  20941. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  20942. };
  20943. /**
  20944. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  20945. * Please consider using the same method from the MeshBuilder class instead.
  20946. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  20947. * 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`).
  20948. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  20949. * 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.
  20950. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20951. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20952. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20953. */
  20954. Mesh.CreateIcoSphere = function (name, options, scene) {
  20955. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  20956. };
  20957. /**
  20958. * Creates a decal mesh.
  20959. * Please consider using the same method from the MeshBuilder class instead.
  20960. * 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.
  20961. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  20962. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  20963. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  20964. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  20965. */
  20966. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  20967. var options = {
  20968. position: position,
  20969. normal: normal,
  20970. size: size,
  20971. angle: angle
  20972. };
  20973. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  20974. };
  20975. // Skeletons
  20976. /**
  20977. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20978. */
  20979. Mesh.prototype.setPositionsForCPUSkinning = function () {
  20980. var source;
  20981. if (!this._sourcePositions) {
  20982. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20983. this._sourcePositions = new Float32Array(source);
  20984. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  20985. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  20986. }
  20987. }
  20988. return this._sourcePositions;
  20989. };
  20990. /**
  20991. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20992. */
  20993. Mesh.prototype.setNormalsForCPUSkinning = function () {
  20994. var source;
  20995. if (!this._sourceNormals) {
  20996. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20997. this._sourceNormals = new Float32Array(source);
  20998. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  20999. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  21000. }
  21001. }
  21002. return this._sourceNormals;
  21003. };
  21004. /**
  21005. * Updates the vertex buffer by applying transformation from the bones.
  21006. * Returns the Mesh.
  21007. *
  21008. * @param {skeleton} skeleton to apply
  21009. */
  21010. Mesh.prototype.applySkeleton = function (skeleton) {
  21011. if (!this.geometry) {
  21012. return this;
  21013. }
  21014. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  21015. return this;
  21016. }
  21017. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  21018. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21019. return this;
  21020. }
  21021. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21022. return this;
  21023. }
  21024. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21025. return this;
  21026. }
  21027. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21028. return this;
  21029. }
  21030. if (!this._sourcePositions) {
  21031. var submeshes = this.subMeshes.slice();
  21032. this.setPositionsForCPUSkinning();
  21033. this.subMeshes = submeshes;
  21034. }
  21035. if (!this._sourceNormals) {
  21036. this.setNormalsForCPUSkinning();
  21037. }
  21038. // positionsData checks for not being Float32Array will only pass at most once
  21039. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21040. if (!(positionsData instanceof Float32Array)) {
  21041. positionsData = new Float32Array(positionsData);
  21042. }
  21043. // normalsData checks for not being Float32Array will only pass at most once
  21044. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21045. if (!(normalsData instanceof Float32Array)) {
  21046. normalsData = new Float32Array(normalsData);
  21047. }
  21048. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21049. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21050. var needExtras = this.numBoneInfluencers > 4;
  21051. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  21052. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  21053. var skeletonMatrices = skeleton.getTransformMatrices(this);
  21054. var tempVector3 = BABYLON.Vector3.Zero();
  21055. var finalMatrix = new BABYLON.Matrix();
  21056. var tempMatrix = new BABYLON.Matrix();
  21057. var matWeightIdx = 0;
  21058. var inf;
  21059. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  21060. var weight;
  21061. for (inf = 0; inf < 4; inf++) {
  21062. weight = matricesWeightsData[matWeightIdx + inf];
  21063. if (weight > 0) {
  21064. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21065. finalMatrix.addToSelf(tempMatrix);
  21066. }
  21067. else
  21068. break;
  21069. }
  21070. if (needExtras) {
  21071. for (inf = 0; inf < 4; inf++) {
  21072. weight = matricesWeightsExtraData[matWeightIdx + inf];
  21073. if (weight > 0) {
  21074. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21075. finalMatrix.addToSelf(tempMatrix);
  21076. }
  21077. else
  21078. break;
  21079. }
  21080. }
  21081. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  21082. tempVector3.toArray(positionsData, index);
  21083. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  21084. tempVector3.toArray(normalsData, index);
  21085. finalMatrix.reset();
  21086. }
  21087. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  21088. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  21089. return this;
  21090. };
  21091. // Tools
  21092. /**
  21093. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  21094. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  21095. */
  21096. Mesh.MinMax = function (meshes) {
  21097. var minVector = null;
  21098. var maxVector = null;
  21099. meshes.forEach(function (mesh, index, array) {
  21100. var boundingBox = mesh.getBoundingInfo().boundingBox;
  21101. if (!minVector) {
  21102. minVector = boundingBox.minimumWorld;
  21103. maxVector = boundingBox.maximumWorld;
  21104. }
  21105. else {
  21106. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  21107. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  21108. }
  21109. });
  21110. return {
  21111. min: minVector,
  21112. max: maxVector
  21113. };
  21114. };
  21115. /**
  21116. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  21117. */
  21118. Mesh.Center = function (meshesOrMinMaxVector) {
  21119. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  21120. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  21121. };
  21122. /**
  21123. * Merge the array of meshes into a single mesh for performance reasons.
  21124. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  21125. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  21126. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  21127. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  21128. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  21129. */
  21130. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  21131. if (disposeSource === void 0) { disposeSource = true; }
  21132. var index;
  21133. if (!allow32BitsIndices) {
  21134. var totalVertices = 0;
  21135. // Counting vertices
  21136. for (index = 0; index < meshes.length; index++) {
  21137. if (meshes[index]) {
  21138. totalVertices += meshes[index].getTotalVertices();
  21139. if (totalVertices > 65536) {
  21140. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  21141. return null;
  21142. }
  21143. }
  21144. }
  21145. }
  21146. // Merge
  21147. var vertexData;
  21148. var otherVertexData;
  21149. var indiceArray = new Array();
  21150. var source;
  21151. for (index = 0; index < meshes.length; index++) {
  21152. if (meshes[index]) {
  21153. meshes[index].computeWorldMatrix(true);
  21154. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], false, true);
  21155. otherVertexData.transform(meshes[index].getWorldMatrix());
  21156. if (vertexData) {
  21157. vertexData.merge(otherVertexData);
  21158. }
  21159. else {
  21160. vertexData = otherVertexData;
  21161. source = meshes[index];
  21162. }
  21163. if (subdivideWithSubMeshes) {
  21164. indiceArray.push(meshes[index].getTotalIndices());
  21165. }
  21166. }
  21167. }
  21168. if (!meshSubclass) {
  21169. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  21170. }
  21171. vertexData.applyToMesh(meshSubclass);
  21172. // Setting properties
  21173. meshSubclass.material = source.material;
  21174. meshSubclass.checkCollisions = source.checkCollisions;
  21175. // Cleaning
  21176. if (disposeSource) {
  21177. for (index = 0; index < meshes.length; index++) {
  21178. if (meshes[index]) {
  21179. meshes[index].dispose();
  21180. }
  21181. }
  21182. }
  21183. // Subdivide
  21184. if (subdivideWithSubMeshes) {
  21185. //-- Suppresions du submesh global
  21186. meshSubclass.releaseSubMeshes();
  21187. index = 0;
  21188. var offset = 0;
  21189. //-- aplique la subdivision en fonction du tableau d'indices
  21190. while (index < indiceArray.length) {
  21191. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  21192. offset += indiceArray[index];
  21193. index++;
  21194. }
  21195. }
  21196. return meshSubclass;
  21197. };
  21198. return Mesh;
  21199. }(BABYLON.AbstractMesh));
  21200. // Consts
  21201. Mesh._FRONTSIDE = 0;
  21202. Mesh._BACKSIDE = 1;
  21203. Mesh._DOUBLESIDE = 2;
  21204. Mesh._DEFAULTSIDE = 0;
  21205. Mesh._NO_CAP = 0;
  21206. Mesh._CAP_START = 1;
  21207. Mesh._CAP_END = 2;
  21208. Mesh._CAP_ALL = 3;
  21209. BABYLON.Mesh = Mesh;
  21210. })(BABYLON || (BABYLON = {}));
  21211. //# sourceMappingURL=babylon.mesh.js.map
  21212. var BABYLON;
  21213. (function (BABYLON) {
  21214. var SubMesh = (function () {
  21215. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  21216. if (createBoundingBox === void 0) { createBoundingBox = true; }
  21217. this.materialIndex = materialIndex;
  21218. this.verticesStart = verticesStart;
  21219. this.verticesCount = verticesCount;
  21220. this.indexStart = indexStart;
  21221. this.indexCount = indexCount;
  21222. this._renderId = 0;
  21223. this._mesh = mesh;
  21224. this._renderingMesh = renderingMesh || mesh;
  21225. mesh.subMeshes.push(this);
  21226. this._trianglePlanes = [];
  21227. this._id = mesh.subMeshes.length - 1;
  21228. if (createBoundingBox) {
  21229. this.refreshBoundingInfo();
  21230. mesh.computeWorldMatrix(true);
  21231. }
  21232. }
  21233. Object.defineProperty(SubMesh.prototype, "effect", {
  21234. get: function () {
  21235. return this._materialEffect;
  21236. },
  21237. enumerable: true,
  21238. configurable: true
  21239. });
  21240. SubMesh.prototype.setEffect = function (effect, defines) {
  21241. if (this._materialEffect === effect) {
  21242. return;
  21243. }
  21244. this._materialDefines = defines;
  21245. this._materialEffect = effect;
  21246. };
  21247. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  21248. get: function () {
  21249. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  21250. },
  21251. enumerable: true,
  21252. configurable: true
  21253. });
  21254. /**
  21255. * Returns the submesh BoudingInfo object.
  21256. */
  21257. SubMesh.prototype.getBoundingInfo = function () {
  21258. if (this.IsGlobal) {
  21259. return this._mesh.getBoundingInfo();
  21260. }
  21261. return this._boundingInfo;
  21262. };
  21263. /**
  21264. * Sets the submesh BoundingInfo.
  21265. * Return the SubMesh.
  21266. */
  21267. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  21268. this._boundingInfo = boundingInfo;
  21269. return this;
  21270. };
  21271. /**
  21272. * Returns the mesh of the current submesh.
  21273. */
  21274. SubMesh.prototype.getMesh = function () {
  21275. return this._mesh;
  21276. };
  21277. /**
  21278. * Returns the rendering mesh of the submesh.
  21279. */
  21280. SubMesh.prototype.getRenderingMesh = function () {
  21281. return this._renderingMesh;
  21282. };
  21283. /**
  21284. * Returns the submesh material.
  21285. */
  21286. SubMesh.prototype.getMaterial = function () {
  21287. var rootMaterial = this._renderingMesh.material;
  21288. if (rootMaterial && rootMaterial.getSubMaterial) {
  21289. var multiMaterial = rootMaterial;
  21290. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  21291. if (this._currentMaterial !== effectiveMaterial) {
  21292. this._currentMaterial = effectiveMaterial;
  21293. if (this._materialDefines) {
  21294. this._materialDefines.markAllAsDirty();
  21295. }
  21296. }
  21297. return effectiveMaterial;
  21298. }
  21299. if (!rootMaterial) {
  21300. return this._mesh.getScene().defaultMaterial;
  21301. }
  21302. return rootMaterial;
  21303. };
  21304. // Methods
  21305. /**
  21306. * Sets a new updated BoundingInfo object to the submesh.
  21307. * Returns the SubMesh.
  21308. */
  21309. SubMesh.prototype.refreshBoundingInfo = function () {
  21310. this._lastColliderWorldVertices = null;
  21311. if (this.IsGlobal) {
  21312. return;
  21313. }
  21314. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21315. if (!data) {
  21316. this._boundingInfo = this._mesh._boundingInfo;
  21317. return;
  21318. }
  21319. var indices = this._renderingMesh.getIndices();
  21320. var extend;
  21321. //is this the only submesh?
  21322. if (this.indexStart === 0 && this.indexCount === indices.length) {
  21323. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  21324. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  21325. }
  21326. else {
  21327. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  21328. }
  21329. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21330. return this;
  21331. };
  21332. SubMesh.prototype._checkCollision = function (collider) {
  21333. return this.getBoundingInfo()._checkCollision(collider);
  21334. };
  21335. /**
  21336. * Updates the submesh BoundingInfo.
  21337. * Returns the Submesh.
  21338. */
  21339. SubMesh.prototype.updateBoundingInfo = function (world) {
  21340. if (!this.getBoundingInfo()) {
  21341. this.refreshBoundingInfo();
  21342. }
  21343. this.getBoundingInfo().update(world);
  21344. return this;
  21345. };
  21346. /**
  21347. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  21348. * Boolean returned.
  21349. */
  21350. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  21351. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  21352. };
  21353. /**
  21354. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  21355. * Boolean returned.
  21356. */
  21357. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21358. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  21359. };
  21360. /**
  21361. * Renders the submesh.
  21362. * Returns it.
  21363. */
  21364. SubMesh.prototype.render = function (enableAlphaMode) {
  21365. this._renderingMesh.render(this, enableAlphaMode);
  21366. return this;
  21367. };
  21368. /**
  21369. * Returns a new Index Buffer.
  21370. * Type returned : WebGLBuffer.
  21371. */
  21372. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  21373. if (!this._linesIndexBuffer) {
  21374. var linesIndices = [];
  21375. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21376. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  21377. }
  21378. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  21379. this.linesIndexCount = linesIndices.length;
  21380. }
  21381. return this._linesIndexBuffer;
  21382. };
  21383. /**
  21384. * True is the passed Ray intersects the submesh bounding box.
  21385. * Boolean returned.
  21386. */
  21387. SubMesh.prototype.canIntersects = function (ray) {
  21388. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  21389. };
  21390. /**
  21391. * Returns an object IntersectionInfo.
  21392. */
  21393. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  21394. var intersectInfo = null;
  21395. // LineMesh first as it's also a Mesh...
  21396. if (this._mesh instanceof BABYLON.LinesMesh) {
  21397. var lineMesh = this._mesh;
  21398. // Line test
  21399. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  21400. var p0 = positions[indices[index]];
  21401. var p1 = positions[indices[index + 1]];
  21402. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  21403. if (length < 0) {
  21404. continue;
  21405. }
  21406. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  21407. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  21408. if (fastCheck) {
  21409. break;
  21410. }
  21411. }
  21412. }
  21413. }
  21414. else {
  21415. // Triangles test
  21416. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21417. var p0 = positions[indices[index]];
  21418. var p1 = positions[indices[index + 1]];
  21419. var p2 = positions[indices[index + 2]];
  21420. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  21421. if (currentIntersectInfo) {
  21422. if (currentIntersectInfo.distance < 0) {
  21423. continue;
  21424. }
  21425. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21426. intersectInfo = currentIntersectInfo;
  21427. intersectInfo.faceId = index / 3;
  21428. if (fastCheck) {
  21429. break;
  21430. }
  21431. }
  21432. }
  21433. }
  21434. }
  21435. return intersectInfo;
  21436. };
  21437. // Clone
  21438. /**
  21439. * Creates a new Submesh from the passed Mesh.
  21440. */
  21441. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  21442. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  21443. if (!this.IsGlobal) {
  21444. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  21445. }
  21446. return result;
  21447. };
  21448. // Dispose
  21449. /**
  21450. * Disposes the Submesh.
  21451. * Returns nothing.
  21452. */
  21453. SubMesh.prototype.dispose = function () {
  21454. if (this._linesIndexBuffer) {
  21455. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  21456. this._linesIndexBuffer = null;
  21457. }
  21458. // Remove from mesh
  21459. var index = this._mesh.subMeshes.indexOf(this);
  21460. this._mesh.subMeshes.splice(index, 1);
  21461. };
  21462. // Statics
  21463. /**
  21464. * Creates a new Submesh from the passed parameters :
  21465. * - materialIndex (integer) : the index of the main mesh material.
  21466. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  21467. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  21468. * - mesh (Mesh) : the main mesh to create the submesh from.
  21469. * - renderingMesh (optional Mesh) : rendering mesh.
  21470. */
  21471. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  21472. var minVertexIndex = Number.MAX_VALUE;
  21473. var maxVertexIndex = -Number.MAX_VALUE;
  21474. renderingMesh = renderingMesh || mesh;
  21475. var indices = renderingMesh.getIndices();
  21476. for (var index = startIndex; index < startIndex + indexCount; index++) {
  21477. var vertexIndex = indices[index];
  21478. if (vertexIndex < minVertexIndex)
  21479. minVertexIndex = vertexIndex;
  21480. if (vertexIndex > maxVertexIndex)
  21481. maxVertexIndex = vertexIndex;
  21482. }
  21483. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  21484. };
  21485. return SubMesh;
  21486. }());
  21487. BABYLON.SubMesh = SubMesh;
  21488. })(BABYLON || (BABYLON = {}));
  21489. //# sourceMappingURL=babylon.subMesh.js.map
  21490. var BABYLON;
  21491. (function (BABYLON) {
  21492. var EffectFallbacks = (function () {
  21493. function EffectFallbacks() {
  21494. this._defines = {};
  21495. this._currentRank = 32;
  21496. this._maxRank = -1;
  21497. }
  21498. EffectFallbacks.prototype.addFallback = function (rank, define) {
  21499. if (!this._defines[rank]) {
  21500. if (rank < this._currentRank) {
  21501. this._currentRank = rank;
  21502. }
  21503. if (rank > this._maxRank) {
  21504. this._maxRank = rank;
  21505. }
  21506. this._defines[rank] = new Array();
  21507. }
  21508. this._defines[rank].push(define);
  21509. };
  21510. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  21511. this._meshRank = rank;
  21512. this._mesh = mesh;
  21513. if (rank < this._currentRank) {
  21514. this._currentRank = rank;
  21515. }
  21516. if (rank > this._maxRank) {
  21517. this._maxRank = rank;
  21518. }
  21519. };
  21520. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  21521. get: function () {
  21522. return this._currentRank <= this._maxRank;
  21523. },
  21524. enumerable: true,
  21525. configurable: true
  21526. });
  21527. EffectFallbacks.prototype.reduce = function (currentDefines) {
  21528. // First we try to switch to CPU skinning
  21529. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  21530. this._mesh.computeBonesUsingShaders = false;
  21531. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  21532. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  21533. var scene = this._mesh.getScene();
  21534. for (var index = 0; index < scene.meshes.length; index++) {
  21535. var otherMesh = scene.meshes[index];
  21536. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  21537. otherMesh.computeBonesUsingShaders = false;
  21538. }
  21539. }
  21540. }
  21541. else {
  21542. var currentFallbacks = this._defines[this._currentRank];
  21543. if (currentFallbacks) {
  21544. for (var index = 0; index < currentFallbacks.length; index++) {
  21545. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  21546. }
  21547. }
  21548. this._currentRank++;
  21549. }
  21550. return currentDefines;
  21551. };
  21552. return EffectFallbacks;
  21553. }());
  21554. BABYLON.EffectFallbacks = EffectFallbacks;
  21555. var EffectCreationOptions = (function () {
  21556. function EffectCreationOptions() {
  21557. }
  21558. return EffectCreationOptions;
  21559. }());
  21560. BABYLON.EffectCreationOptions = EffectCreationOptions;
  21561. var Effect = (function () {
  21562. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  21563. var _this = this;
  21564. this.uniqueId = 0;
  21565. this._uniformBuffersNames = {};
  21566. this._isReady = false;
  21567. this._compilationError = "";
  21568. this._valueCache = {};
  21569. this.name = baseName;
  21570. if (attributesNamesOrOptions.attributes) {
  21571. var options = attributesNamesOrOptions;
  21572. this._engine = uniformsNamesOrEngine;
  21573. this._attributesNames = options.attributes;
  21574. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  21575. this._samplers = options.samplers;
  21576. this.defines = options.defines;
  21577. this.onError = options.onError;
  21578. this.onCompiled = options.onCompiled;
  21579. this._fallbacks = options.fallbacks;
  21580. this._indexParameters = options.indexParameters;
  21581. if (options.uniformBuffersNames) {
  21582. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  21583. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  21584. }
  21585. }
  21586. }
  21587. else {
  21588. this._engine = engine;
  21589. this.defines = defines;
  21590. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  21591. this._samplers = samplers;
  21592. this._attributesNames = attributesNamesOrOptions;
  21593. this.onError = onError;
  21594. this.onCompiled = onCompiled;
  21595. this._indexParameters = indexParameters;
  21596. this._fallbacks = fallbacks;
  21597. }
  21598. this.uniqueId = Effect._uniqueIdSeed++;
  21599. var vertexSource;
  21600. var fragmentSource;
  21601. if (baseName.vertexElement) {
  21602. vertexSource = document.getElementById(baseName.vertexElement);
  21603. if (!vertexSource) {
  21604. vertexSource = baseName.vertexElement;
  21605. }
  21606. }
  21607. else {
  21608. vertexSource = baseName.vertex || baseName;
  21609. }
  21610. if (baseName.fragmentElement) {
  21611. fragmentSource = document.getElementById(baseName.fragmentElement);
  21612. if (!fragmentSource) {
  21613. fragmentSource = baseName.fragmentElement;
  21614. }
  21615. }
  21616. else {
  21617. fragmentSource = baseName.fragment || baseName;
  21618. }
  21619. this._loadVertexShader(vertexSource, function (vertexCode) {
  21620. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  21621. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  21622. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  21623. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  21624. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  21625. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks);
  21626. });
  21627. });
  21628. });
  21629. });
  21630. });
  21631. });
  21632. }
  21633. Object.defineProperty(Effect.prototype, "key", {
  21634. get: function () {
  21635. return this._key;
  21636. },
  21637. enumerable: true,
  21638. configurable: true
  21639. });
  21640. // Properties
  21641. Effect.prototype.isReady = function () {
  21642. return this._isReady;
  21643. };
  21644. Effect.prototype.getProgram = function () {
  21645. return this._program;
  21646. };
  21647. Effect.prototype.getAttributesNames = function () {
  21648. return this._attributesNames;
  21649. };
  21650. Effect.prototype.getAttributeLocation = function (index) {
  21651. return this._attributes[index];
  21652. };
  21653. Effect.prototype.getAttributeLocationByName = function (name) {
  21654. var index = this._attributesNames.indexOf(name);
  21655. return this._attributes[index];
  21656. };
  21657. Effect.prototype.getAttributesCount = function () {
  21658. return this._attributes.length;
  21659. };
  21660. Effect.prototype.getUniformIndex = function (uniformName) {
  21661. return this._uniformsNames.indexOf(uniformName);
  21662. };
  21663. Effect.prototype.getUniform = function (uniformName) {
  21664. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  21665. };
  21666. Effect.prototype.getSamplers = function () {
  21667. return this._samplers;
  21668. };
  21669. Effect.prototype.getCompilationError = function () {
  21670. return this._compilationError;
  21671. };
  21672. Effect.prototype.getVertexShaderSource = function () {
  21673. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  21674. };
  21675. Effect.prototype.getFragmentShaderSource = function () {
  21676. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  21677. };
  21678. // Methods
  21679. Effect.prototype._loadVertexShader = function (vertex, callback) {
  21680. // DOM element ?
  21681. if (vertex instanceof HTMLElement) {
  21682. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  21683. callback(vertexCode);
  21684. return;
  21685. }
  21686. // Base64 encoded ?
  21687. if (vertex.substr(0, 7) === "base64:") {
  21688. var vertexBinary = window.atob(vertex.substr(7));
  21689. callback(vertexBinary);
  21690. return;
  21691. }
  21692. // Is in local store ?
  21693. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  21694. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  21695. return;
  21696. }
  21697. var vertexShaderUrl;
  21698. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  21699. vertexShaderUrl = vertex;
  21700. }
  21701. else {
  21702. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  21703. }
  21704. // Vertex shader
  21705. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  21706. };
  21707. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  21708. // DOM element ?
  21709. if (fragment instanceof HTMLElement) {
  21710. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  21711. callback(fragmentCode);
  21712. return;
  21713. }
  21714. // Base64 encoded ?
  21715. if (fragment.substr(0, 7) === "base64:") {
  21716. var fragmentBinary = window.atob(fragment.substr(7));
  21717. callback(fragmentBinary);
  21718. return;
  21719. }
  21720. // Is in local store ?
  21721. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  21722. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  21723. return;
  21724. }
  21725. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  21726. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  21727. return;
  21728. }
  21729. var fragmentShaderUrl;
  21730. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  21731. fragmentShaderUrl = fragment;
  21732. }
  21733. else {
  21734. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  21735. }
  21736. // Fragment shader
  21737. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  21738. };
  21739. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  21740. // Rebuild shaders source code
  21741. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  21742. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  21743. vertexCode = prefix + vertexCode;
  21744. fragmentCode = prefix + fragmentCode;
  21745. // Number lines of shaders source code
  21746. var i = 2;
  21747. var regex = /\n/gm;
  21748. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  21749. i = 2;
  21750. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  21751. // Dump shaders name and formatted source code
  21752. if (this.name.vertexElement) {
  21753. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  21754. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  21755. }
  21756. else if (this.name.vertex) {
  21757. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  21758. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  21759. }
  21760. else {
  21761. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  21762. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  21763. }
  21764. };
  21765. ;
  21766. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  21767. var preparedSourceCode = this._processPrecision(sourceCode);
  21768. if (this._engine.webGLVersion == 1) {
  21769. callback(preparedSourceCode);
  21770. return;
  21771. }
  21772. // Already converted
  21773. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  21774. callback(preparedSourceCode);
  21775. return;
  21776. }
  21777. // Remove extensions
  21778. // #extension GL_OES_standard_derivatives : enable
  21779. // #extension GL_EXT_shader_texture_lod : enable
  21780. // #extension GL_EXT_frag_depth : enable
  21781. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  21782. var result = preparedSourceCode.replace(regex, "");
  21783. // Migrate to GLSL v300
  21784. result = result.replace(/varying\s/g, isFragment ? "in " : "out ");
  21785. result = result.replace(/attribute[ \t]/g, "in ");
  21786. result = result.replace(/[ \t]attribute/g, " in");
  21787. if (isFragment) {
  21788. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  21789. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  21790. result = result.replace(/texture2D\(/g, "texture(");
  21791. result = result.replace(/textureCube\(/g, "texture(");
  21792. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  21793. result = result.replace(/gl_FragColor/g, "glFragColor");
  21794. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  21795. }
  21796. callback(result);
  21797. };
  21798. Effect.prototype._processIncludes = function (sourceCode, callback) {
  21799. var _this = this;
  21800. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  21801. var match = regex.exec(sourceCode);
  21802. var returnValue = new String(sourceCode);
  21803. while (match != null) {
  21804. var includeFile = match[1];
  21805. // Uniform declaration
  21806. if (includeFile.indexOf("__decl__") !== -1) {
  21807. includeFile = includeFile.replace(/__decl__/, "");
  21808. if (this._engine.webGLVersion != 1) {
  21809. includeFile = includeFile.replace(/Vertex/, "Ubo");
  21810. includeFile = includeFile.replace(/Fragment/, "Ubo");
  21811. }
  21812. includeFile = includeFile + "Declaration";
  21813. }
  21814. if (Effect.IncludesShadersStore[includeFile]) {
  21815. // Substitution
  21816. var includeContent = Effect.IncludesShadersStore[includeFile];
  21817. if (match[2]) {
  21818. var splits = match[3].split(",");
  21819. for (var index = 0; index < splits.length; index += 2) {
  21820. var source = new RegExp(splits[index], "g");
  21821. var dest = splits[index + 1];
  21822. includeContent = includeContent.replace(source, dest);
  21823. }
  21824. }
  21825. if (match[4]) {
  21826. var indexString = match[5];
  21827. if (indexString.indexOf("..") !== -1) {
  21828. var indexSplits = indexString.split("..");
  21829. var minIndex = parseInt(indexSplits[0]);
  21830. var maxIndex = parseInt(indexSplits[1]);
  21831. var sourceIncludeContent = includeContent.slice(0);
  21832. includeContent = "";
  21833. if (isNaN(maxIndex)) {
  21834. maxIndex = this._indexParameters[indexSplits[1]];
  21835. }
  21836. for (var i = minIndex; i < maxIndex; i++) {
  21837. if (this._engine.webGLVersion === 1) {
  21838. // Ubo replacement
  21839. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  21840. return p1 + "{X}";
  21841. });
  21842. }
  21843. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  21844. }
  21845. }
  21846. else {
  21847. if (this._engine.webGLVersion === 1) {
  21848. // Ubo replacement
  21849. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  21850. return p1 + "{X}";
  21851. });
  21852. }
  21853. includeContent = includeContent.replace(/\{X\}/g, indexString);
  21854. }
  21855. }
  21856. // Replace
  21857. returnValue = returnValue.replace(match[0], includeContent);
  21858. }
  21859. else {
  21860. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  21861. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  21862. Effect.IncludesShadersStore[includeFile] = fileContent;
  21863. _this._processIncludes(returnValue, callback);
  21864. });
  21865. return;
  21866. }
  21867. match = regex.exec(sourceCode);
  21868. }
  21869. callback(returnValue);
  21870. };
  21871. Effect.prototype._processPrecision = function (source) {
  21872. if (source.indexOf("precision highp float") === -1) {
  21873. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21874. source = "precision mediump float;\n" + source;
  21875. }
  21876. else {
  21877. source = "precision highp float;\n" + source;
  21878. }
  21879. }
  21880. else {
  21881. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21882. source = source.replace("precision highp float", "precision mediump float");
  21883. }
  21884. }
  21885. return source;
  21886. };
  21887. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  21888. try {
  21889. var engine = this._engine;
  21890. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  21891. if (engine.webGLVersion > 1) {
  21892. for (var name in this._uniformBuffersNames) {
  21893. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  21894. }
  21895. }
  21896. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  21897. this._attributes = engine.getAttributes(this._program, attributesNames);
  21898. var index;
  21899. for (index = 0; index < this._samplers.length; index++) {
  21900. var sampler = this.getUniform(this._samplers[index]);
  21901. if (sampler == null) {
  21902. this._samplers.splice(index, 1);
  21903. index--;
  21904. }
  21905. }
  21906. engine.bindSamplers(this);
  21907. this._compilationError = "";
  21908. this._isReady = true;
  21909. if (this.onCompiled) {
  21910. this.onCompiled(this);
  21911. }
  21912. }
  21913. catch (e) {
  21914. this._compilationError = e.message;
  21915. // Let's go through fallbacks then
  21916. BABYLON.Tools.Error("Unable to compile effect:");
  21917. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  21918. return " " + uniform;
  21919. }));
  21920. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  21921. return " " + attribute;
  21922. }));
  21923. this._dumpShadersSource(vertexSourceCode, fragmentSourceCode, defines);
  21924. BABYLON.Tools.Error("Error: " + this._compilationError);
  21925. if (fallbacks && fallbacks.isMoreFallbacks) {
  21926. BABYLON.Tools.Error("Trying next fallback.");
  21927. defines = fallbacks.reduce(defines);
  21928. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  21929. }
  21930. else {
  21931. if (this.onError) {
  21932. this.onError(this, this._compilationError);
  21933. }
  21934. }
  21935. }
  21936. };
  21937. Object.defineProperty(Effect.prototype, "isSupported", {
  21938. get: function () {
  21939. return this._compilationError === "";
  21940. },
  21941. enumerable: true,
  21942. configurable: true
  21943. });
  21944. Effect.prototype._bindTexture = function (channel, texture) {
  21945. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  21946. };
  21947. Effect.prototype.setTexture = function (channel, texture) {
  21948. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  21949. };
  21950. Effect.prototype.setTextureArray = function (channel, textures) {
  21951. if (this._samplers.indexOf(channel + "Ex") === -1) {
  21952. var initialPos = this._samplers.indexOf(channel);
  21953. for (var index = 1; index < textures.length; index++) {
  21954. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  21955. }
  21956. }
  21957. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  21958. };
  21959. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  21960. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  21961. };
  21962. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  21963. var cache = this._valueCache[uniformName];
  21964. var flag = matrix.updateFlag;
  21965. if (cache !== undefined && cache === flag) {
  21966. return false;
  21967. }
  21968. this._valueCache[uniformName] = flag;
  21969. return true;
  21970. };
  21971. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  21972. var cache = this._valueCache[uniformName];
  21973. if (!cache) {
  21974. cache = [x, y];
  21975. this._valueCache[uniformName] = cache;
  21976. return true;
  21977. }
  21978. var changed = false;
  21979. if (cache[0] !== x) {
  21980. cache[0] = x;
  21981. changed = true;
  21982. }
  21983. if (cache[1] !== y) {
  21984. cache[1] = y;
  21985. changed = true;
  21986. }
  21987. return changed;
  21988. };
  21989. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  21990. var cache = this._valueCache[uniformName];
  21991. if (!cache) {
  21992. cache = [x, y, z];
  21993. this._valueCache[uniformName] = cache;
  21994. return true;
  21995. }
  21996. var changed = false;
  21997. if (cache[0] !== x) {
  21998. cache[0] = x;
  21999. changed = true;
  22000. }
  22001. if (cache[1] !== y) {
  22002. cache[1] = y;
  22003. changed = true;
  22004. }
  22005. if (cache[2] !== z) {
  22006. cache[2] = z;
  22007. changed = true;
  22008. }
  22009. return changed;
  22010. };
  22011. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  22012. var cache = this._valueCache[uniformName];
  22013. if (!cache) {
  22014. cache = [x, y, z, w];
  22015. this._valueCache[uniformName] = cache;
  22016. return true;
  22017. }
  22018. var changed = false;
  22019. if (cache[0] !== x) {
  22020. cache[0] = x;
  22021. changed = true;
  22022. }
  22023. if (cache[1] !== y) {
  22024. cache[1] = y;
  22025. changed = true;
  22026. }
  22027. if (cache[2] !== z) {
  22028. cache[2] = z;
  22029. changed = true;
  22030. }
  22031. if (cache[3] !== w) {
  22032. cache[3] = w;
  22033. changed = true;
  22034. }
  22035. return changed;
  22036. };
  22037. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  22038. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  22039. return;
  22040. }
  22041. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  22042. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  22043. };
  22044. Effect.prototype.bindUniformBlock = function (blockName, index) {
  22045. this._engine.bindUniformBlock(this._program, blockName, index);
  22046. };
  22047. Effect.prototype.setIntArray = function (uniformName, array) {
  22048. this._valueCache[uniformName] = null;
  22049. this._engine.setIntArray(this.getUniform(uniformName), array);
  22050. return this;
  22051. };
  22052. Effect.prototype.setIntArray2 = function (uniformName, array) {
  22053. this._valueCache[uniformName] = null;
  22054. this._engine.setIntArray2(this.getUniform(uniformName), array);
  22055. return this;
  22056. };
  22057. Effect.prototype.setIntArray3 = function (uniformName, array) {
  22058. this._valueCache[uniformName] = null;
  22059. this._engine.setIntArray3(this.getUniform(uniformName), array);
  22060. return this;
  22061. };
  22062. Effect.prototype.setIntArray4 = function (uniformName, array) {
  22063. this._valueCache[uniformName] = null;
  22064. this._engine.setIntArray4(this.getUniform(uniformName), array);
  22065. return this;
  22066. };
  22067. Effect.prototype.setFloatArray = function (uniformName, array) {
  22068. this._valueCache[uniformName] = null;
  22069. this._engine.setFloatArray(this.getUniform(uniformName), array);
  22070. return this;
  22071. };
  22072. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  22073. this._valueCache[uniformName] = null;
  22074. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  22075. return this;
  22076. };
  22077. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  22078. this._valueCache[uniformName] = null;
  22079. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  22080. return this;
  22081. };
  22082. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  22083. this._valueCache[uniformName] = null;
  22084. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  22085. return this;
  22086. };
  22087. Effect.prototype.setArray = function (uniformName, array) {
  22088. this._valueCache[uniformName] = null;
  22089. this._engine.setArray(this.getUniform(uniformName), array);
  22090. return this;
  22091. };
  22092. Effect.prototype.setArray2 = function (uniformName, array) {
  22093. this._valueCache[uniformName] = null;
  22094. this._engine.setArray2(this.getUniform(uniformName), array);
  22095. return this;
  22096. };
  22097. Effect.prototype.setArray3 = function (uniformName, array) {
  22098. this._valueCache[uniformName] = null;
  22099. this._engine.setArray3(this.getUniform(uniformName), array);
  22100. return this;
  22101. };
  22102. Effect.prototype.setArray4 = function (uniformName, array) {
  22103. this._valueCache[uniformName] = null;
  22104. this._engine.setArray4(this.getUniform(uniformName), array);
  22105. return this;
  22106. };
  22107. Effect.prototype.setMatrices = function (uniformName, matrices) {
  22108. if (!matrices) {
  22109. return;
  22110. }
  22111. this._valueCache[uniformName] = null;
  22112. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  22113. return this;
  22114. };
  22115. Effect.prototype.setMatrix = function (uniformName, matrix) {
  22116. if (this._cacheMatrix(uniformName, matrix)) {
  22117. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  22118. }
  22119. return this;
  22120. };
  22121. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  22122. this._valueCache[uniformName] = null;
  22123. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  22124. return this;
  22125. };
  22126. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  22127. this._valueCache[uniformName] = null;
  22128. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  22129. return this;
  22130. };
  22131. Effect.prototype.setFloat = function (uniformName, value) {
  22132. var cache = this._valueCache[uniformName];
  22133. if (cache !== undefined && cache === value)
  22134. return this;
  22135. this._valueCache[uniformName] = value;
  22136. this._engine.setFloat(this.getUniform(uniformName), value);
  22137. return this;
  22138. };
  22139. Effect.prototype.setBool = function (uniformName, bool) {
  22140. var cache = this._valueCache[uniformName];
  22141. if (cache !== undefined && cache === bool)
  22142. return this;
  22143. this._valueCache[uniformName] = bool;
  22144. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  22145. return this;
  22146. };
  22147. Effect.prototype.setVector2 = function (uniformName, vector2) {
  22148. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  22149. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  22150. }
  22151. return this;
  22152. };
  22153. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  22154. if (this._cacheFloat2(uniformName, x, y)) {
  22155. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  22156. }
  22157. return this;
  22158. };
  22159. Effect.prototype.setVector3 = function (uniformName, vector3) {
  22160. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  22161. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  22162. }
  22163. return this;
  22164. };
  22165. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  22166. if (this._cacheFloat3(uniformName, x, y, z)) {
  22167. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  22168. }
  22169. return this;
  22170. };
  22171. Effect.prototype.setVector4 = function (uniformName, vector4) {
  22172. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  22173. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  22174. }
  22175. return this;
  22176. };
  22177. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  22178. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  22179. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  22180. }
  22181. return this;
  22182. };
  22183. Effect.prototype.setColor3 = function (uniformName, color3) {
  22184. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  22185. this._engine.setColor3(this.getUniform(uniformName), color3);
  22186. }
  22187. return this;
  22188. };
  22189. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  22190. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  22191. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  22192. }
  22193. return this;
  22194. };
  22195. Effect.prototype._recombineShader = function (node) {
  22196. if (node.define) {
  22197. if (node.condition) {
  22198. var defineIndex = this.defines.indexOf("#define " + node.define);
  22199. if (defineIndex === -1) {
  22200. return null;
  22201. }
  22202. var nextComma = this.defines.indexOf("\n", defineIndex);
  22203. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  22204. var condition = defineValue + node.condition;
  22205. if (!eval(condition)) {
  22206. return null;
  22207. }
  22208. }
  22209. else if (node.ndef) {
  22210. if (this.defines.indexOf("#define " + node.define) !== -1) {
  22211. return null;
  22212. }
  22213. }
  22214. else if (this.defines.indexOf("#define " + node.define) === -1) {
  22215. return null;
  22216. }
  22217. }
  22218. var result = "";
  22219. for (var index = 0; index < node.children.length; index++) {
  22220. var line = node.children[index];
  22221. if (line.children) {
  22222. var combined = this._recombineShader(line);
  22223. if (combined !== null) {
  22224. result += combined + "\r\n";
  22225. }
  22226. continue;
  22227. }
  22228. if (line.length > 0) {
  22229. result += line + "\r\n";
  22230. }
  22231. }
  22232. return result;
  22233. };
  22234. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  22235. var root = {
  22236. children: []
  22237. };
  22238. var currentNode = root;
  22239. var lines = shaderString.split("\n");
  22240. for (var index = 0; index < lines.length; index++) {
  22241. var line = lines[index].trim();
  22242. // #ifdef
  22243. var pos = line.indexOf("#ifdef ");
  22244. if (pos !== -1) {
  22245. var define = line.substr(pos + 7);
  22246. var newNode = {
  22247. condition: null,
  22248. ndef: false,
  22249. define: define,
  22250. children: [],
  22251. parent: currentNode
  22252. };
  22253. currentNode.children.push(newNode);
  22254. currentNode = newNode;
  22255. continue;
  22256. }
  22257. // #ifndef
  22258. var pos = line.indexOf("#ifndef ");
  22259. if (pos !== -1) {
  22260. var define = line.substr(pos + 8);
  22261. newNode = {
  22262. condition: null,
  22263. define: define,
  22264. ndef: true,
  22265. children: [],
  22266. parent: currentNode
  22267. };
  22268. currentNode.children.push(newNode);
  22269. currentNode = newNode;
  22270. continue;
  22271. }
  22272. // #if
  22273. var pos = line.indexOf("#if ");
  22274. if (pos !== -1) {
  22275. var define = line.substr(pos + 4).trim();
  22276. var conditionPos = define.indexOf(" ");
  22277. newNode = {
  22278. condition: define.substr(conditionPos + 1),
  22279. define: define.substr(0, conditionPos),
  22280. ndef: false,
  22281. children: [],
  22282. parent: currentNode
  22283. };
  22284. currentNode.children.push(newNode);
  22285. currentNode = newNode;
  22286. continue;
  22287. }
  22288. // #endif
  22289. pos = line.indexOf("#endif");
  22290. if (pos !== -1) {
  22291. currentNode = currentNode.parent;
  22292. continue;
  22293. }
  22294. currentNode.children.push(line);
  22295. }
  22296. // Recombine
  22297. return this._recombineShader(root);
  22298. };
  22299. return Effect;
  22300. }());
  22301. Effect._uniqueIdSeed = 0;
  22302. Effect._baseCache = {};
  22303. // Statics
  22304. Effect.ShadersStore = {};
  22305. Effect.IncludesShadersStore = {};
  22306. BABYLON.Effect = Effect;
  22307. })(BABYLON || (BABYLON = {}));
  22308. //# sourceMappingURL=babylon.effect.js.map
  22309. var BABYLON;
  22310. (function (BABYLON) {
  22311. var MaterialHelper = (function () {
  22312. function MaterialHelper() {
  22313. }
  22314. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  22315. if (defines._areMiscDirty) {
  22316. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  22317. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  22318. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  22319. }
  22320. };
  22321. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances) {
  22322. var changed = false;
  22323. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  22324. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  22325. changed = true;
  22326. }
  22327. if (defines["ALPHATEST"] !== engine.getAlphaTesting()) {
  22328. defines["ALPHATEST"] = !defines["ALPHATEST"];
  22329. changed = true;
  22330. }
  22331. if (defines["INSTANCES"] !== useInstances) {
  22332. defines["INSTANCES"] = useInstances;
  22333. changed = true;
  22334. }
  22335. if (changed) {
  22336. defines.markAsUnprocessed();
  22337. }
  22338. };
  22339. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  22340. if (useMorphTargets === void 0) { useMorphTargets = false; }
  22341. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  22342. return;
  22343. }
  22344. defines._normals = defines._needNormals;
  22345. defines._uvs = defines._needUVs;
  22346. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  22347. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  22348. defines["TANGENT"] = true;
  22349. }
  22350. if (defines._needUVs) {
  22351. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  22352. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  22353. }
  22354. else {
  22355. defines["UV1"] = false;
  22356. defines["UV2"] = false;
  22357. }
  22358. if (useVertexColor) {
  22359. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  22360. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  22361. }
  22362. if (useBones) {
  22363. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  22364. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  22365. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  22366. }
  22367. else {
  22368. defines["NUM_BONE_INFLUENCERS"] = 0;
  22369. defines["BonesPerMesh"] = 0;
  22370. }
  22371. }
  22372. if (useMorphTargets) {
  22373. if (mesh.morphTargetManager) {
  22374. var manager = mesh.morphTargetManager;
  22375. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  22376. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  22377. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  22378. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  22379. }
  22380. else {
  22381. defines["MORPHTARGETS_TANGENT"] = false;
  22382. defines["MORPHTARGETS_NORMAL"] = false;
  22383. defines["MORPHTARGETS"] = false;
  22384. defines["NUM_MORPH_INFLUENCERS"] = 0;
  22385. }
  22386. }
  22387. };
  22388. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  22389. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22390. if (disableLighting === void 0) { disableLighting = false; }
  22391. if (!defines._areLightsDirty) {
  22392. return defines._needNormals;
  22393. }
  22394. var lightIndex = 0;
  22395. var needNormals = false;
  22396. var needRebuild = false;
  22397. var lightmapMode = false;
  22398. var shadowEnabled = false;
  22399. var specularEnabled = false;
  22400. if (scene.lightsEnabled && !disableLighting) {
  22401. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  22402. var light = _a[_i];
  22403. needNormals = true;
  22404. if (defines["LIGHT" + lightIndex] === undefined) {
  22405. needRebuild = true;
  22406. }
  22407. defines["LIGHT" + lightIndex] = true;
  22408. defines["SPOTLIGHT" + lightIndex] = false;
  22409. defines["HEMILIGHT" + lightIndex] = false;
  22410. defines["POINTLIGHT" + lightIndex] = false;
  22411. defines["DIRLIGHT" + lightIndex] = false;
  22412. var type;
  22413. if (light.getTypeID() === 2) {
  22414. type = "SPOTLIGHT" + lightIndex;
  22415. }
  22416. else if (light.getTypeID() === 3) {
  22417. type = "HEMILIGHT" + lightIndex;
  22418. }
  22419. else if (light.getTypeID() === 0) {
  22420. type = "POINTLIGHT" + lightIndex;
  22421. }
  22422. else {
  22423. type = "DIRLIGHT" + lightIndex;
  22424. }
  22425. defines[type] = true;
  22426. // Specular
  22427. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  22428. specularEnabled = true;
  22429. }
  22430. // Shadows
  22431. defines["SHADOW" + lightIndex] = false;
  22432. if (scene.shadowsEnabled) {
  22433. var shadowGenerator = light.getShadowGenerator();
  22434. if (mesh && mesh.receiveShadows && shadowGenerator) {
  22435. defines["SHADOW" + lightIndex] = true;
  22436. shadowEnabled = true;
  22437. defines["SHADOWPCF" + lightIndex] = false;
  22438. defines["SHADOWESM" + lightIndex] = false;
  22439. if (shadowGenerator.usePoissonSampling) {
  22440. defines["SHADOWPCF" + lightIndex] = true;
  22441. }
  22442. else if (shadowGenerator.useExponentialShadowMap || shadowGenerator.useBlurExponentialShadowMap) {
  22443. defines["SHADOWESM" + lightIndex] = true;
  22444. }
  22445. }
  22446. }
  22447. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  22448. lightmapMode = true;
  22449. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  22450. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  22451. }
  22452. else {
  22453. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  22454. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  22455. }
  22456. lightIndex++;
  22457. if (lightIndex === maxSimultaneousLights)
  22458. break;
  22459. }
  22460. }
  22461. defines["SPECULARTERM"] = specularEnabled;
  22462. defines["SHADOWS"] = shadowEnabled;
  22463. // Resetting all other lights if any
  22464. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  22465. if (defines["LIGHT" + index] !== undefined) {
  22466. defines["LIGHT" + index] = false;
  22467. }
  22468. }
  22469. var caps = scene.getEngine().getCaps();
  22470. if (defines["SHADOWFULLFLOAT"] === undefined) {
  22471. needRebuild = true;
  22472. }
  22473. defines["SHADOWFULLFLOAT"] = (shadowEnabled && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender);
  22474. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  22475. if (needRebuild) {
  22476. defines.rebuild();
  22477. }
  22478. return needNormals;
  22479. };
  22480. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  22481. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22482. var uniformsList, uniformBuffersList, samplersList, defines;
  22483. if (uniformsListOrOptions.uniformsNames) {
  22484. var options = uniformsListOrOptions;
  22485. uniformsList = options.uniformsNames;
  22486. uniformBuffersList = options.uniformBuffersNames;
  22487. samplersList = options.samplers;
  22488. defines = options.defines;
  22489. maxSimultaneousLights = options.maxSimultaneousLights;
  22490. }
  22491. else {
  22492. uniformsList = uniformsListOrOptions;
  22493. }
  22494. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22495. if (!defines["LIGHT" + lightIndex]) {
  22496. break;
  22497. }
  22498. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  22499. if (uniformBuffersList) {
  22500. uniformBuffersList.push("Light" + lightIndex);
  22501. }
  22502. samplersList.push("shadowSampler" + lightIndex);
  22503. }
  22504. if (defines["NUM_MORPH_INFLUENCERS"]) {
  22505. uniformsList.push("morphTargetInfluences");
  22506. }
  22507. };
  22508. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  22509. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22510. if (!defines["SHADOWS"]) {
  22511. return;
  22512. }
  22513. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22514. if (!defines["LIGHT" + lightIndex]) {
  22515. break;
  22516. }
  22517. if (lightIndex > 0) {
  22518. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  22519. }
  22520. if (defines["SHADOW" + lightIndex]) {
  22521. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  22522. }
  22523. if (defines["SHADOWPCF" + lightIndex]) {
  22524. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  22525. }
  22526. if (defines["SHADOWESM" + lightIndex]) {
  22527. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  22528. }
  22529. }
  22530. };
  22531. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  22532. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  22533. if (influencers > 0) {
  22534. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  22535. var manager = mesh.morphTargetManager;
  22536. var normal = manager.supportsNormals && defines["NORMAL"];
  22537. var tangent = manager.supportsTangents && defines["TANGENT"];
  22538. for (var index = 0; index < influencers; index++) {
  22539. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  22540. if (normal) {
  22541. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  22542. }
  22543. if (tangent) {
  22544. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  22545. }
  22546. if (attribs.length > maxAttributesCount) {
  22547. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  22548. }
  22549. }
  22550. }
  22551. };
  22552. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  22553. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  22554. fallbacks.addCPUSkinningFallback(0, mesh);
  22555. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22556. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22557. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  22558. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  22559. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  22560. }
  22561. }
  22562. };
  22563. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  22564. if (defines["INSTANCES"]) {
  22565. attribs.push("world0");
  22566. attribs.push("world1");
  22567. attribs.push("world2");
  22568. attribs.push("world3");
  22569. }
  22570. };
  22571. // Bindings
  22572. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  22573. var shadowGenerator = light.getShadowGenerator();
  22574. if (mesh.receiveShadows && shadowGenerator) {
  22575. if (!light.needCube()) {
  22576. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  22577. }
  22578. else {
  22579. if (!depthValuesAlreadySet) {
  22580. depthValuesAlreadySet = true;
  22581. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  22582. }
  22583. }
  22584. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  22585. light._uniformBuffer.updateFloat3("shadowsInfo", shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.depthScale, lightIndex);
  22586. }
  22587. return depthValuesAlreadySet;
  22588. };
  22589. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  22590. light.transferToEffect(effect, lightIndex + "");
  22591. };
  22592. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  22593. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22594. var lightIndex = 0;
  22595. var depthValuesAlreadySet = false;
  22596. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  22597. var light = _a[_i];
  22598. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  22599. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  22600. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  22601. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], light.range, lightIndex + "");
  22602. if (defines["SPECULARTERM"]) {
  22603. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  22604. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  22605. }
  22606. // Shadows
  22607. if (scene.shadowsEnabled) {
  22608. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex + "", effect, depthValuesAlreadySet);
  22609. }
  22610. light._uniformBuffer.update();
  22611. lightIndex++;
  22612. if (lightIndex === maxSimultaneousLights)
  22613. break;
  22614. }
  22615. };
  22616. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  22617. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  22618. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  22619. effect.setColor3("vFogColor", scene.fogColor);
  22620. }
  22621. };
  22622. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  22623. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  22624. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  22625. if (matrices) {
  22626. effect.setMatrices("mBones", matrices);
  22627. }
  22628. }
  22629. };
  22630. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  22631. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  22632. return;
  22633. }
  22634. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  22635. };
  22636. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  22637. if (defines["LOGARITHMICDEPTH"]) {
  22638. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  22639. }
  22640. };
  22641. MaterialHelper.BindClipPlane = function (effect, scene) {
  22642. if (scene.clipPlane) {
  22643. var clipPlane = scene.clipPlane;
  22644. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22645. }
  22646. };
  22647. return MaterialHelper;
  22648. }());
  22649. BABYLON.MaterialHelper = MaterialHelper;
  22650. })(BABYLON || (BABYLON = {}));
  22651. //# sourceMappingURL=babylon.materialHelper.js.map
  22652. var BABYLON;
  22653. (function (BABYLON) {
  22654. var MaterialDefines = (function () {
  22655. function MaterialDefines() {
  22656. this._isDirty = true;
  22657. this._areLightsDirty = true;
  22658. this._areAttributesDirty = true;
  22659. this._areTexturesDirty = true;
  22660. this._areFresnelDirty = true;
  22661. this._areMiscDirty = true;
  22662. this._normals = false;
  22663. this._uvs = false;
  22664. this._needNormals = false;
  22665. this._needUVs = false;
  22666. }
  22667. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  22668. get: function () {
  22669. return this._isDirty;
  22670. },
  22671. enumerable: true,
  22672. configurable: true
  22673. });
  22674. MaterialDefines.prototype.markAsProcessed = function () {
  22675. this._isDirty = false;
  22676. this._areAttributesDirty = false;
  22677. this._areTexturesDirty = false;
  22678. this._areFresnelDirty = false;
  22679. this._areLightsDirty = false;
  22680. this._areMiscDirty = false;
  22681. };
  22682. MaterialDefines.prototype.markAsUnprocessed = function () {
  22683. this._isDirty = true;
  22684. };
  22685. MaterialDefines.prototype.markAllAsDirty = function () {
  22686. this._areTexturesDirty = true;
  22687. this._areAttributesDirty = true;
  22688. this._areLightsDirty = true;
  22689. this._areFresnelDirty = true;
  22690. this._areMiscDirty = true;
  22691. this._isDirty = true;
  22692. };
  22693. MaterialDefines.prototype.markAsLightDirty = function () {
  22694. this._areLightsDirty = true;
  22695. this._isDirty = true;
  22696. };
  22697. MaterialDefines.prototype.markAsAttributesDirty = function () {
  22698. this._areAttributesDirty = true;
  22699. this._isDirty = true;
  22700. };
  22701. MaterialDefines.prototype.markAsTexturesDirty = function () {
  22702. this._areTexturesDirty = true;
  22703. this._isDirty = true;
  22704. };
  22705. MaterialDefines.prototype.markAsFresnelDirty = function () {
  22706. this._areFresnelDirty = true;
  22707. this._isDirty = true;
  22708. };
  22709. MaterialDefines.prototype.markAsMiscDirty = function () {
  22710. this._areMiscDirty = true;
  22711. this._isDirty = true;
  22712. };
  22713. MaterialDefines.prototype.rebuild = function () {
  22714. if (this._keys) {
  22715. delete this._keys;
  22716. }
  22717. this._keys = [];
  22718. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  22719. var key = _a[_i];
  22720. if (key[0] === "_") {
  22721. continue;
  22722. }
  22723. this._keys.push(key);
  22724. }
  22725. };
  22726. MaterialDefines.prototype.isEqual = function (other) {
  22727. if (this._keys.length !== other._keys.length) {
  22728. return false;
  22729. }
  22730. for (var index = 0; index < this._keys.length; index++) {
  22731. var prop = this._keys[index];
  22732. if (this[prop] !== other[prop]) {
  22733. return false;
  22734. }
  22735. }
  22736. return true;
  22737. };
  22738. MaterialDefines.prototype.cloneTo = function (other) {
  22739. if (this._keys.length !== other._keys.length) {
  22740. other._keys = this._keys.slice(0);
  22741. }
  22742. for (var index = 0; index < this._keys.length; index++) {
  22743. var prop = this._keys[index];
  22744. other[prop] = this[prop];
  22745. }
  22746. };
  22747. MaterialDefines.prototype.reset = function () {
  22748. for (var index = 0; index < this._keys.length; index++) {
  22749. var prop = this._keys[index];
  22750. if (typeof (this[prop]) === "number") {
  22751. this[prop] = 0;
  22752. }
  22753. else {
  22754. this[prop] = false;
  22755. }
  22756. }
  22757. };
  22758. MaterialDefines.prototype.toString = function () {
  22759. var result = "";
  22760. for (var index = 0; index < this._keys.length; index++) {
  22761. var prop = this._keys[index];
  22762. var value = this[prop];
  22763. if (typeof (value) === "number") {
  22764. result += "#define " + prop + " " + this[prop] + "\n";
  22765. }
  22766. else if (value) {
  22767. result += "#define " + prop + "\n";
  22768. }
  22769. }
  22770. return result;
  22771. };
  22772. return MaterialDefines;
  22773. }());
  22774. BABYLON.MaterialDefines = MaterialDefines;
  22775. var Material = (function () {
  22776. function Material(name, scene, doNotAdd) {
  22777. this.checkReadyOnEveryCall = false;
  22778. this.checkReadyOnlyOnce = false;
  22779. this.state = "";
  22780. this.alpha = 1.0;
  22781. this._backFaceCulling = true;
  22782. this.doNotSerialize = false;
  22783. this.storeEffectOnSubMeshes = false;
  22784. /**
  22785. * An event triggered when the material is disposed.
  22786. * @type {BABYLON.Observable}
  22787. */
  22788. this.onDisposeObservable = new BABYLON.Observable();
  22789. /**
  22790. * An event triggered when the material is bound.
  22791. * @type {BABYLON.Observable}
  22792. */
  22793. this.onBindObservable = new BABYLON.Observable();
  22794. /**
  22795. * An event triggered when the material is unbound.
  22796. * @type {BABYLON.Observable}
  22797. */
  22798. this.onUnBindObservable = new BABYLON.Observable();
  22799. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  22800. this.disableDepthWrite = false;
  22801. this._fogEnabled = true;
  22802. this.pointSize = 1.0;
  22803. this.zOffset = 0;
  22804. this._wasPreviouslyReady = false;
  22805. this._fillMode = Material.TriangleFillMode;
  22806. this.name = name;
  22807. this.id = name;
  22808. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  22809. if (this._scene.useRightHandedSystem) {
  22810. this.sideOrientation = Material.ClockWiseSideOrientation;
  22811. }
  22812. else {
  22813. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  22814. }
  22815. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  22816. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  22817. if (!doNotAdd) {
  22818. this._scene.materials.push(this);
  22819. }
  22820. }
  22821. Object.defineProperty(Material, "TriangleFillMode", {
  22822. get: function () {
  22823. return Material._TriangleFillMode;
  22824. },
  22825. enumerable: true,
  22826. configurable: true
  22827. });
  22828. Object.defineProperty(Material, "WireFrameFillMode", {
  22829. get: function () {
  22830. return Material._WireFrameFillMode;
  22831. },
  22832. enumerable: true,
  22833. configurable: true
  22834. });
  22835. Object.defineProperty(Material, "PointFillMode", {
  22836. get: function () {
  22837. return Material._PointFillMode;
  22838. },
  22839. enumerable: true,
  22840. configurable: true
  22841. });
  22842. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  22843. get: function () {
  22844. return Material._ClockWiseSideOrientation;
  22845. },
  22846. enumerable: true,
  22847. configurable: true
  22848. });
  22849. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  22850. get: function () {
  22851. return Material._CounterClockWiseSideOrientation;
  22852. },
  22853. enumerable: true,
  22854. configurable: true
  22855. });
  22856. Object.defineProperty(Material, "TextureDirtyFlag", {
  22857. get: function () {
  22858. return Material._TextureDirtyFlag;
  22859. },
  22860. enumerable: true,
  22861. configurable: true
  22862. });
  22863. Object.defineProperty(Material, "LightDirtyFlag", {
  22864. get: function () {
  22865. return Material._LightDirtyFlag;
  22866. },
  22867. enumerable: true,
  22868. configurable: true
  22869. });
  22870. Object.defineProperty(Material, "FresnelDirtyFlag", {
  22871. get: function () {
  22872. return Material._FresnelDirtyFlag;
  22873. },
  22874. enumerable: true,
  22875. configurable: true
  22876. });
  22877. Object.defineProperty(Material, "AttributesDirtyFlag", {
  22878. get: function () {
  22879. return Material._AttributesDirtyFlag;
  22880. },
  22881. enumerable: true,
  22882. configurable: true
  22883. });
  22884. Object.defineProperty(Material, "MiscDirtyFlag", {
  22885. get: function () {
  22886. return Material._MiscDirtyFlag;
  22887. },
  22888. enumerable: true,
  22889. configurable: true
  22890. });
  22891. Object.defineProperty(Material.prototype, "backFaceCulling", {
  22892. get: function () {
  22893. return this._backFaceCulling;
  22894. },
  22895. set: function (value) {
  22896. if (this._backFaceCulling === value) {
  22897. return;
  22898. }
  22899. this._backFaceCulling = value;
  22900. this.markAsDirty(Material.TextureDirtyFlag);
  22901. },
  22902. enumerable: true,
  22903. configurable: true
  22904. });
  22905. Object.defineProperty(Material.prototype, "onDispose", {
  22906. set: function (callback) {
  22907. if (this._onDisposeObserver) {
  22908. this.onDisposeObservable.remove(this._onDisposeObserver);
  22909. }
  22910. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22911. },
  22912. enumerable: true,
  22913. configurable: true
  22914. });
  22915. Object.defineProperty(Material.prototype, "onBind", {
  22916. set: function (callback) {
  22917. if (this._onBindObserver) {
  22918. this.onBindObservable.remove(this._onBindObserver);
  22919. }
  22920. this._onBindObserver = this.onBindObservable.add(callback);
  22921. },
  22922. enumerable: true,
  22923. configurable: true
  22924. });
  22925. Object.defineProperty(Material.prototype, "fogEnabled", {
  22926. get: function () {
  22927. return this._fogEnabled;
  22928. },
  22929. set: function (value) {
  22930. if (this._fogEnabled === value) {
  22931. return;
  22932. }
  22933. this._fogEnabled = value;
  22934. this.markAsDirty(Material.MiscDirtyFlag);
  22935. },
  22936. enumerable: true,
  22937. configurable: true
  22938. });
  22939. Object.defineProperty(Material.prototype, "wireframe", {
  22940. get: function () {
  22941. return this._fillMode === Material.WireFrameFillMode;
  22942. },
  22943. set: function (value) {
  22944. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  22945. },
  22946. enumerable: true,
  22947. configurable: true
  22948. });
  22949. Object.defineProperty(Material.prototype, "pointsCloud", {
  22950. get: function () {
  22951. return this._fillMode === Material.PointFillMode;
  22952. },
  22953. set: function (value) {
  22954. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  22955. },
  22956. enumerable: true,
  22957. configurable: true
  22958. });
  22959. Object.defineProperty(Material.prototype, "fillMode", {
  22960. get: function () {
  22961. return this._fillMode;
  22962. },
  22963. set: function (value) {
  22964. if (this._fillMode === value) {
  22965. return;
  22966. }
  22967. this._fillMode = value;
  22968. this.markAsDirty(Material.MiscDirtyFlag);
  22969. },
  22970. enumerable: true,
  22971. configurable: true
  22972. });
  22973. /**
  22974. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22975. * subclasses should override adding information pertainent to themselves
  22976. */
  22977. Material.prototype.toString = function (fullDetails) {
  22978. var ret = "Name: " + this.name;
  22979. if (fullDetails) {
  22980. }
  22981. return ret;
  22982. };
  22983. /**
  22984. * Child classes can use it to update shaders
  22985. */
  22986. Material.prototype.markAsDirty = function (flag) {
  22987. };
  22988. Material.prototype.getClassName = function () {
  22989. return "Material";
  22990. };
  22991. Object.defineProperty(Material.prototype, "isFrozen", {
  22992. get: function () {
  22993. return this.checkReadyOnlyOnce;
  22994. },
  22995. enumerable: true,
  22996. configurable: true
  22997. });
  22998. Material.prototype.freeze = function () {
  22999. this.checkReadyOnlyOnce = true;
  23000. };
  23001. Material.prototype.unfreeze = function () {
  23002. this.checkReadyOnlyOnce = false;
  23003. };
  23004. Material.prototype.isReady = function (mesh, useInstances) {
  23005. return true;
  23006. };
  23007. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  23008. return false;
  23009. };
  23010. Material.prototype.getEffect = function () {
  23011. return this._effect;
  23012. };
  23013. Material.prototype.getScene = function () {
  23014. return this._scene;
  23015. };
  23016. Material.prototype.needAlphaBlending = function () {
  23017. return (this.alpha < 1.0);
  23018. };
  23019. Material.prototype.needAlphaTesting = function () {
  23020. return false;
  23021. };
  23022. Material.prototype.getAlphaTestTexture = function () {
  23023. return null;
  23024. };
  23025. Material.prototype.markDirty = function () {
  23026. this._wasPreviouslyReady = false;
  23027. };
  23028. Material.prototype._preBind = function (effect) {
  23029. var engine = this._scene.getEngine();
  23030. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  23031. engine.enableEffect(effect ? effect : this._effect);
  23032. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  23033. };
  23034. Material.prototype.bind = function (world, mesh) {
  23035. };
  23036. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  23037. };
  23038. Material.prototype.bindOnlyWorldMatrix = function (world) {
  23039. };
  23040. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  23041. sceneUbo.bindToEffect(effect, "Scene");
  23042. };
  23043. Material.prototype.bindView = function (effect) {
  23044. if (!this._useUBO) {
  23045. effect.setMatrix("view", this.getScene().getViewMatrix());
  23046. }
  23047. else {
  23048. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  23049. }
  23050. };
  23051. Material.prototype.bindViewProjection = function (effect) {
  23052. if (!this._useUBO) {
  23053. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  23054. }
  23055. else {
  23056. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  23057. }
  23058. };
  23059. Material.prototype._afterBind = function (mesh) {
  23060. this._scene._cachedMaterial = this;
  23061. this.onBindObservable.notifyObservers(mesh);
  23062. if (this.disableDepthWrite) {
  23063. var engine = this._scene.getEngine();
  23064. this._cachedDepthWriteState = engine.getDepthWrite();
  23065. engine.setDepthWrite(false);
  23066. }
  23067. };
  23068. Material.prototype.unbind = function () {
  23069. this.onUnBindObservable.notifyObservers(this);
  23070. if (this.disableDepthWrite) {
  23071. var engine = this._scene.getEngine();
  23072. engine.setDepthWrite(this._cachedDepthWriteState);
  23073. }
  23074. };
  23075. Material.prototype.clone = function (name) {
  23076. return null;
  23077. };
  23078. Material.prototype.getBindedMeshes = function () {
  23079. var result = new Array();
  23080. for (var index = 0; index < this._scene.meshes.length; index++) {
  23081. var mesh = this._scene.meshes[index];
  23082. if (mesh.material === this) {
  23083. result.push(mesh);
  23084. }
  23085. }
  23086. return result;
  23087. };
  23088. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  23089. // Animations
  23090. this.getScene().stopAnimation(this);
  23091. // Remove from scene
  23092. var index = this._scene.materials.indexOf(this);
  23093. if (index >= 0) {
  23094. this._scene.materials.splice(index, 1);
  23095. }
  23096. // Remove from meshes
  23097. for (index = 0; index < this._scene.meshes.length; index++) {
  23098. var mesh = this._scene.meshes[index];
  23099. if (mesh.material === this) {
  23100. mesh.material = null;
  23101. if (mesh.geometry) {
  23102. var geometry = mesh.geometry;
  23103. if (this.storeEffectOnSubMeshes) {
  23104. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  23105. var subMesh = _a[_i];
  23106. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  23107. }
  23108. }
  23109. else {
  23110. geometry._releaseVertexArrayObject(this._effect);
  23111. }
  23112. }
  23113. }
  23114. }
  23115. this._uniformBuffer.dispose();
  23116. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  23117. if (forceDisposeEffect && this._effect) {
  23118. if (this.storeEffectOnSubMeshes) {
  23119. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23120. var subMesh = _c[_b];
  23121. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  23122. }
  23123. }
  23124. else {
  23125. this._scene.getEngine()._releaseEffect(this._effect);
  23126. }
  23127. this._effect = null;
  23128. }
  23129. // Callback
  23130. this.onDisposeObservable.notifyObservers(this);
  23131. this.onDisposeObservable.clear();
  23132. this.onBindObservable.clear();
  23133. this.onUnBindObservable.clear();
  23134. };
  23135. Material.prototype.serialize = function () {
  23136. return BABYLON.SerializationHelper.Serialize(this);
  23137. };
  23138. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  23139. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  23140. multiMaterial.id = parsedMultiMaterial.id;
  23141. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  23142. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  23143. var subMatId = parsedMultiMaterial.materials[matIndex];
  23144. if (subMatId) {
  23145. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  23146. }
  23147. else {
  23148. multiMaterial.subMaterials.push(null);
  23149. }
  23150. }
  23151. return multiMaterial;
  23152. };
  23153. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  23154. if (!parsedMaterial.customType) {
  23155. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  23156. }
  23157. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  23158. return materialType.Parse(parsedMaterial, scene, rootUrl);
  23159. ;
  23160. };
  23161. return Material;
  23162. }());
  23163. Material._TriangleFillMode = 0;
  23164. Material._WireFrameFillMode = 1;
  23165. Material._PointFillMode = 2;
  23166. Material._ClockWiseSideOrientation = 0;
  23167. Material._CounterClockWiseSideOrientation = 1;
  23168. Material._TextureDirtyFlag = 0;
  23169. Material._LightDirtyFlag = 1;
  23170. Material._FresnelDirtyFlag = 2;
  23171. Material._AttributesDirtyFlag = 4;
  23172. Material._MiscDirtyFlag = 8;
  23173. __decorate([
  23174. BABYLON.serialize()
  23175. ], Material.prototype, "id", void 0);
  23176. __decorate([
  23177. BABYLON.serialize()
  23178. ], Material.prototype, "name", void 0);
  23179. __decorate([
  23180. BABYLON.serialize()
  23181. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  23182. __decorate([
  23183. BABYLON.serialize()
  23184. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  23185. __decorate([
  23186. BABYLON.serialize()
  23187. ], Material.prototype, "state", void 0);
  23188. __decorate([
  23189. BABYLON.serialize()
  23190. ], Material.prototype, "alpha", void 0);
  23191. __decorate([
  23192. BABYLON.serialize("backFaceCulling")
  23193. ], Material.prototype, "_backFaceCulling", void 0);
  23194. __decorate([
  23195. BABYLON.serialize()
  23196. ], Material.prototype, "sideOrientation", void 0);
  23197. __decorate([
  23198. BABYLON.serialize()
  23199. ], Material.prototype, "alphaMode", void 0);
  23200. __decorate([
  23201. BABYLON.serialize()
  23202. ], Material.prototype, "disableDepthWrite", void 0);
  23203. __decorate([
  23204. BABYLON.serialize("fogEnabled")
  23205. ], Material.prototype, "_fogEnabled", void 0);
  23206. __decorate([
  23207. BABYLON.serialize()
  23208. ], Material.prototype, "pointSize", void 0);
  23209. __decorate([
  23210. BABYLON.serialize()
  23211. ], Material.prototype, "zOffset", void 0);
  23212. __decorate([
  23213. BABYLON.serialize()
  23214. ], Material.prototype, "wireframe", null);
  23215. __decorate([
  23216. BABYLON.serialize()
  23217. ], Material.prototype, "pointsCloud", null);
  23218. __decorate([
  23219. BABYLON.serialize()
  23220. ], Material.prototype, "fillMode", null);
  23221. BABYLON.Material = Material;
  23222. })(BABYLON || (BABYLON = {}));
  23223. //# sourceMappingURL=babylon.material.js.map
  23224. var BABYLON;
  23225. (function (BABYLON) {
  23226. var UniformBuffer = (function () {
  23227. /**
  23228. * Uniform buffer objects.
  23229. *
  23230. * Handles blocks of uniform on the GPU.
  23231. *
  23232. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  23233. *
  23234. * For more information, please refer to :
  23235. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  23236. */
  23237. function UniformBuffer(engine, data, dynamic) {
  23238. this._engine = engine;
  23239. this._noUBO = engine.webGLVersion === 1;
  23240. this._dynamic = dynamic;
  23241. this._data = data || [];
  23242. this._uniformLocations = {};
  23243. this._uniformSizes = {};
  23244. this._uniformLocationPointer = 0;
  23245. this._needSync = false;
  23246. if (this._noUBO) {
  23247. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  23248. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  23249. this.updateFloat = this._updateFloatForEffect;
  23250. this.updateFloat2 = this._updateFloat2ForEffect;
  23251. this.updateFloat3 = this._updateFloat3ForEffect;
  23252. this.updateFloat4 = this._updateFloat4ForEffect;
  23253. this.updateMatrix = this._updateMatrixForEffect;
  23254. this.updateVector3 = this._updateVector3ForEffect;
  23255. this.updateVector4 = this._updateVector4ForEffect;
  23256. this.updateColor3 = this._updateColor3ForEffect;
  23257. this.updateColor4 = this._updateColor4ForEffect;
  23258. }
  23259. else {
  23260. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  23261. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  23262. this.updateFloat = this._updateFloatForUniform;
  23263. this.updateFloat2 = this._updateFloat2ForUniform;
  23264. this.updateFloat3 = this._updateFloat3ForUniform;
  23265. this.updateFloat4 = this._updateFloat4ForUniform;
  23266. this.updateMatrix = this._updateMatrixForUniform;
  23267. this.updateVector3 = this._updateVector3ForUniform;
  23268. this.updateVector4 = this._updateVector4ForUniform;
  23269. this.updateColor3 = this._updateColor3ForUniform;
  23270. this.updateColor4 = this._updateColor4ForUniform;
  23271. }
  23272. }
  23273. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  23274. // Properties
  23275. /**
  23276. * Indicates if the buffer is using the WebGL2 UBO implementation,
  23277. * or just falling back on setUniformXXX calls.
  23278. */
  23279. get: function () {
  23280. return !this._noUBO;
  23281. },
  23282. enumerable: true,
  23283. configurable: true
  23284. });
  23285. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  23286. /**
  23287. * Indicates if the WebGL underlying uniform buffer is in sync
  23288. * with the javascript cache data.
  23289. */
  23290. get: function () {
  23291. return !this._needSync;
  23292. },
  23293. enumerable: true,
  23294. configurable: true
  23295. });
  23296. /**
  23297. * Indicates if the WebGL underlying uniform buffer is dynamic.
  23298. * Also, a dynamic UniformBuffer will disable cache verification and always
  23299. * update the underlying WebGL uniform buffer to the GPU.
  23300. */
  23301. UniformBuffer.prototype.isDynamic = function () {
  23302. return this._dynamic;
  23303. };
  23304. /**
  23305. * The data cache on JS side.
  23306. */
  23307. UniformBuffer.prototype.getData = function () {
  23308. return this._bufferData;
  23309. };
  23310. /**
  23311. * The underlying WebGL Uniform buffer.
  23312. */
  23313. UniformBuffer.prototype.getBuffer = function () {
  23314. return this._buffer;
  23315. };
  23316. /**
  23317. * std140 layout specifies how to align data within an UBO structure.
  23318. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  23319. * for specs.
  23320. */
  23321. UniformBuffer.prototype._fillAlignment = function (size) {
  23322. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  23323. // and 4x4 matrices
  23324. // TODO : change if other types are used
  23325. var alignment;
  23326. if (size <= 2) {
  23327. alignment = size;
  23328. }
  23329. else {
  23330. alignment = 4;
  23331. }
  23332. if ((this._uniformLocationPointer % alignment) !== 0) {
  23333. var oldPointer = this._uniformLocationPointer;
  23334. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  23335. var diff = this._uniformLocationPointer - oldPointer;
  23336. for (var i = 0; i < diff; i++) {
  23337. this._data.push(0);
  23338. }
  23339. }
  23340. };
  23341. /**
  23342. * Adds an uniform in the buffer.
  23343. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  23344. * for the layout to be correct !
  23345. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23346. * @param {number|number[]} size Data size, or data directly.
  23347. */
  23348. UniformBuffer.prototype.addUniform = function (name, size) {
  23349. if (this._noUBO) {
  23350. return;
  23351. }
  23352. if (this._uniformLocations[name] !== undefined) {
  23353. // Already existing uniform
  23354. return;
  23355. }
  23356. // This function must be called in the order of the shader layout !
  23357. // size can be the size of the uniform, or data directly
  23358. var data;
  23359. if (size instanceof Array) {
  23360. data = size;
  23361. size = data.length;
  23362. }
  23363. else {
  23364. size = size;
  23365. data = [];
  23366. // Fill with zeros
  23367. for (var i = 0; i < size; i++) {
  23368. data.push(0);
  23369. }
  23370. }
  23371. this._fillAlignment(size);
  23372. this._uniformSizes[name] = size;
  23373. this._uniformLocations[name] = this._uniformLocationPointer;
  23374. this._uniformLocationPointer += size;
  23375. for (var i = 0; i < size; i++) {
  23376. this._data.push(data[i]);
  23377. }
  23378. this._needSync = true;
  23379. };
  23380. /**
  23381. * Wrapper for addUniform.
  23382. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23383. * @param {Matrix} mat A 4x4 matrix.
  23384. */
  23385. UniformBuffer.prototype.addMatrix = function (name, mat) {
  23386. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  23387. };
  23388. /**
  23389. * Wrapper for addUniform.
  23390. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23391. * @param {number} x
  23392. * @param {number} y
  23393. */
  23394. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  23395. var temp = [x, y];
  23396. this.addUniform(name, temp);
  23397. };
  23398. /**
  23399. * Wrapper for addUniform.
  23400. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23401. * @param {number} x
  23402. * @param {number} y
  23403. * @param {number} z
  23404. */
  23405. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  23406. var temp = [x, y, z];
  23407. this.addUniform(name, temp);
  23408. };
  23409. /**
  23410. * Wrapper for addUniform.
  23411. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23412. * @param {Color3} color
  23413. */
  23414. UniformBuffer.prototype.addColor3 = function (name, color) {
  23415. var temp = [];
  23416. color.toArray(temp);
  23417. this.addUniform(name, temp);
  23418. };
  23419. /**
  23420. * Wrapper for addUniform.
  23421. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23422. * @param {Color3} color
  23423. * @param {number} alpha
  23424. */
  23425. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  23426. var temp = [];
  23427. color.toArray(temp);
  23428. temp.push(alpha);
  23429. this.addUniform(name, temp);
  23430. };
  23431. /**
  23432. * Wrapper for addUniform.
  23433. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23434. * @param {Vector3} vector
  23435. */
  23436. UniformBuffer.prototype.addVector3 = function (name, vector) {
  23437. var temp = [];
  23438. vector.toArray(temp);
  23439. this.addUniform(name, temp);
  23440. };
  23441. /**
  23442. * Wrapper for addUniform.
  23443. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23444. */
  23445. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  23446. this.addUniform(name, 12);
  23447. };
  23448. /**
  23449. * Wrapper for addUniform.
  23450. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23451. */
  23452. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  23453. this.addUniform(name, 8);
  23454. };
  23455. /**
  23456. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  23457. */
  23458. UniformBuffer.prototype.create = function () {
  23459. if (this._noUBO) {
  23460. return;
  23461. }
  23462. if (this._buffer) {
  23463. return; // nothing to do
  23464. }
  23465. // See spec, alignment must be filled as a vec4
  23466. this._fillAlignment(4);
  23467. this._bufferData = new Float32Array(this._data);
  23468. if (this._dynamic) {
  23469. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  23470. }
  23471. else {
  23472. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  23473. }
  23474. this._needSync = true;
  23475. };
  23476. /**
  23477. * Updates the WebGL Uniform Buffer on the GPU.
  23478. * If the `dynamic` flag is set to true, no cache comparison is done.
  23479. * Otherwise, the buffer will be updated only if the cache differs.
  23480. */
  23481. UniformBuffer.prototype.update = function () {
  23482. if (!this._buffer) {
  23483. this.create();
  23484. return;
  23485. }
  23486. if (!this._dynamic && !this._needSync) {
  23487. return;
  23488. }
  23489. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  23490. this._needSync = false;
  23491. };
  23492. /**
  23493. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  23494. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  23495. * @param {number[]|Float32Array} data Flattened data
  23496. * @param {number} size Size of the data.
  23497. */
  23498. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  23499. var location = this._uniformLocations[uniformName];
  23500. if (location === undefined) {
  23501. if (this._buffer) {
  23502. // Cannot add an uniform if the buffer is already created
  23503. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  23504. return;
  23505. }
  23506. this.addUniform(uniformName, size);
  23507. location = this._uniformLocations[uniformName];
  23508. }
  23509. if (!this._buffer) {
  23510. this.create();
  23511. }
  23512. if (!this._dynamic) {
  23513. // Cache for static uniform buffers
  23514. var changed = false;
  23515. for (var i = 0; i < size; i++) {
  23516. if (this._bufferData[location + i] !== data[i]) {
  23517. changed = true;
  23518. this._bufferData[location + i] = data[i];
  23519. }
  23520. }
  23521. this._needSync = this._needSync || changed;
  23522. }
  23523. else {
  23524. // No cache for dynamic
  23525. for (var i = 0; i < size; i++) {
  23526. this._bufferData[location + i] = data[i];
  23527. }
  23528. }
  23529. };
  23530. // Update methods
  23531. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  23532. // To match std140, matrix must be realigned
  23533. for (var i = 0; i < 3; i++) {
  23534. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  23535. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  23536. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  23537. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  23538. }
  23539. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  23540. };
  23541. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  23542. this._currentEffect.setMatrix3x3(name, matrix);
  23543. };
  23544. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  23545. this._currentEffect.setMatrix2x2(name, matrix);
  23546. };
  23547. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  23548. // To match std140, matrix must be realigned
  23549. for (var i = 0; i < 2; i++) {
  23550. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  23551. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  23552. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  23553. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  23554. }
  23555. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  23556. };
  23557. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  23558. this._currentEffect.setFloat(name, x);
  23559. };
  23560. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  23561. UniformBuffer._tempBuffer[0] = x;
  23562. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  23563. };
  23564. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y) {
  23565. this._currentEffect.setFloat2(name, x, y);
  23566. };
  23567. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y) {
  23568. UniformBuffer._tempBuffer[0] = x;
  23569. UniformBuffer._tempBuffer[1] = y;
  23570. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  23571. };
  23572. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  23573. if (suffix === void 0) { suffix = ""; }
  23574. this._currentEffect.setFloat3(name + suffix, x, y, z);
  23575. };
  23576. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  23577. if (suffix === void 0) { suffix = ""; }
  23578. UniformBuffer._tempBuffer[0] = x;
  23579. UniformBuffer._tempBuffer[1] = y;
  23580. UniformBuffer._tempBuffer[2] = z;
  23581. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  23582. };
  23583. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  23584. if (suffix === void 0) { suffix = ""; }
  23585. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  23586. };
  23587. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  23588. if (suffix === void 0) { suffix = ""; }
  23589. UniformBuffer._tempBuffer[0] = x;
  23590. UniformBuffer._tempBuffer[1] = y;
  23591. UniformBuffer._tempBuffer[2] = z;
  23592. UniformBuffer._tempBuffer[3] = w;
  23593. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  23594. };
  23595. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  23596. this._currentEffect.setMatrix(name, mat);
  23597. };
  23598. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  23599. this.updateUniform(name, mat.toArray(), 16);
  23600. };
  23601. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  23602. this._currentEffect.setVector3(name, vector);
  23603. };
  23604. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  23605. vector.toArray(UniformBuffer._tempBuffer);
  23606. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  23607. };
  23608. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  23609. this._currentEffect.setVector4(name, vector);
  23610. };
  23611. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  23612. vector.toArray(UniformBuffer._tempBuffer);
  23613. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  23614. };
  23615. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  23616. if (suffix === void 0) { suffix = ""; }
  23617. this._currentEffect.setColor3(name + suffix, color);
  23618. };
  23619. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  23620. if (suffix === void 0) { suffix = ""; }
  23621. color.toArray(UniformBuffer._tempBuffer);
  23622. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  23623. };
  23624. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  23625. if (suffix === void 0) { suffix = ""; }
  23626. this._currentEffect.setColor4(name + suffix, color, alpha);
  23627. };
  23628. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  23629. if (suffix === void 0) { suffix = ""; }
  23630. color.toArray(UniformBuffer._tempBuffer);
  23631. UniformBuffer._tempBuffer[3] = alpha;
  23632. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  23633. };
  23634. /**
  23635. * Sets a sampler uniform on the effect.
  23636. * @param {string} name Name of the sampler.
  23637. * @param {Texture} texture
  23638. */
  23639. UniformBuffer.prototype.setTexture = function (name, texture) {
  23640. this._currentEffect.setTexture(name, texture);
  23641. };
  23642. /**
  23643. * Directly updates the value of the uniform in the cache AND on the GPU.
  23644. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  23645. * @param {number[]|Float32Array} data Flattened data
  23646. */
  23647. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  23648. this.updateUniform(uniformName, data, data.length);
  23649. this.update();
  23650. };
  23651. /**
  23652. * Binds this uniform buffer to an effect.
  23653. * @param {Effect} effect
  23654. * @param {string} name Name of the uniform block in the shader.
  23655. */
  23656. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  23657. this._currentEffect = effect;
  23658. if (this._noUBO) {
  23659. return;
  23660. }
  23661. effect.bindUniformBuffer(this._buffer, name);
  23662. };
  23663. /**
  23664. * Disposes the uniform buffer.
  23665. */
  23666. UniformBuffer.prototype.dispose = function () {
  23667. if (!this._buffer) {
  23668. return;
  23669. }
  23670. if (this._engine._releaseBuffer(this._buffer)) {
  23671. this._buffer = null;
  23672. }
  23673. };
  23674. return UniformBuffer;
  23675. }());
  23676. // Pool for avoiding memory leaks
  23677. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  23678. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  23679. BABYLON.UniformBuffer = UniformBuffer;
  23680. })(BABYLON || (BABYLON = {}));
  23681. //# sourceMappingURL=babylon.uniformBuffer.js.map
  23682. var BABYLON;
  23683. (function (BABYLON) {
  23684. var PushMaterial = (function (_super) {
  23685. __extends(PushMaterial, _super);
  23686. function PushMaterial(name, scene) {
  23687. var _this = _super.call(this, name, scene) || this;
  23688. _this.storeEffectOnSubMeshes = true;
  23689. return _this;
  23690. }
  23691. PushMaterial.prototype.getEffect = function () {
  23692. return this._activeEffect;
  23693. };
  23694. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  23695. if (!mesh) {
  23696. return false;
  23697. }
  23698. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  23699. return true;
  23700. }
  23701. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  23702. };
  23703. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  23704. this._activeEffect.setMatrix("world", world);
  23705. };
  23706. PushMaterial.prototype.bind = function (world, mesh) {
  23707. if (!mesh) {
  23708. return;
  23709. }
  23710. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  23711. };
  23712. PushMaterial.prototype._afterBind = function (mesh, effect) {
  23713. _super.prototype._afterBind.call(this, mesh);
  23714. this.getScene()._cachedEffect = effect;
  23715. };
  23716. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  23717. if (visibility === void 0) { visibility = 0; }
  23718. return scene.isCachedMaterialValid(this, effect, visibility);
  23719. };
  23720. PushMaterial.prototype.markAsDirty = function (flag) {
  23721. if (flag & BABYLON.Material.TextureDirtyFlag) {
  23722. this._markAllSubMeshesAsTexturesDirty();
  23723. }
  23724. if (flag & BABYLON.Material.LightDirtyFlag) {
  23725. this._markAllSubMeshesAsLightsDirty();
  23726. }
  23727. if (flag & BABYLON.Material.FresnelDirtyFlag) {
  23728. this._markAllSubMeshesAsFresnelDirty();
  23729. }
  23730. if (flag & BABYLON.Material.AttributesDirtyFlag) {
  23731. this._markAllSubMeshesAsAttributesDirty();
  23732. }
  23733. if (flag & BABYLON.Material.MiscDirtyFlag) {
  23734. this._markAllSubMeshesAsMiscDirty();
  23735. }
  23736. };
  23737. PushMaterial.prototype._markAllSubMeshesAsDirty = function (func) {
  23738. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  23739. var mesh = _a[_i];
  23740. if (!mesh.subMeshes) {
  23741. continue;
  23742. }
  23743. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23744. var subMesh = _c[_b];
  23745. if (subMesh.getMaterial() !== this) {
  23746. continue;
  23747. }
  23748. if (!subMesh._materialDefines) {
  23749. return;
  23750. }
  23751. func(subMesh._materialDefines);
  23752. }
  23753. }
  23754. };
  23755. PushMaterial.prototype._markAllSubMeshesAsTexturesDirty = function () {
  23756. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  23757. };
  23758. PushMaterial.prototype._markAllSubMeshesAsFresnelDirty = function () {
  23759. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  23760. };
  23761. PushMaterial.prototype._markAllSubMeshesAsLightsDirty = function () {
  23762. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  23763. };
  23764. PushMaterial.prototype._markAllSubMeshesAsAttributesDirty = function () {
  23765. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  23766. };
  23767. PushMaterial.prototype._markAllSubMeshesAsMiscDirty = function () {
  23768. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  23769. };
  23770. return PushMaterial;
  23771. }(BABYLON.Material));
  23772. BABYLON.PushMaterial = PushMaterial;
  23773. })(BABYLON || (BABYLON = {}));
  23774. //# sourceMappingURL=babylon.pushMaterial.js.map
  23775. var BABYLON;
  23776. (function (BABYLON) {
  23777. var VertexData = (function () {
  23778. function VertexData() {
  23779. }
  23780. VertexData.prototype.set = function (data, kind) {
  23781. switch (kind) {
  23782. case BABYLON.VertexBuffer.PositionKind:
  23783. this.positions = data;
  23784. break;
  23785. case BABYLON.VertexBuffer.NormalKind:
  23786. this.normals = data;
  23787. break;
  23788. case BABYLON.VertexBuffer.TangentKind:
  23789. this.tangents = data;
  23790. break;
  23791. case BABYLON.VertexBuffer.UVKind:
  23792. this.uvs = data;
  23793. break;
  23794. case BABYLON.VertexBuffer.UV2Kind:
  23795. this.uvs2 = data;
  23796. break;
  23797. case BABYLON.VertexBuffer.UV3Kind:
  23798. this.uvs3 = data;
  23799. break;
  23800. case BABYLON.VertexBuffer.UV4Kind:
  23801. this.uvs4 = data;
  23802. break;
  23803. case BABYLON.VertexBuffer.UV5Kind:
  23804. this.uvs5 = data;
  23805. break;
  23806. case BABYLON.VertexBuffer.UV6Kind:
  23807. this.uvs6 = data;
  23808. break;
  23809. case BABYLON.VertexBuffer.ColorKind:
  23810. this.colors = data;
  23811. break;
  23812. case BABYLON.VertexBuffer.MatricesIndicesKind:
  23813. this.matricesIndices = data;
  23814. break;
  23815. case BABYLON.VertexBuffer.MatricesWeightsKind:
  23816. this.matricesWeights = data;
  23817. break;
  23818. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  23819. this.matricesIndicesExtra = data;
  23820. break;
  23821. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  23822. this.matricesWeightsExtra = data;
  23823. break;
  23824. }
  23825. };
  23826. /**
  23827. * Associates the vertexData to the passed Mesh.
  23828. * Sets it as updatable or not (default `false`).
  23829. * Returns the VertexData.
  23830. */
  23831. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  23832. this._applyTo(mesh, updatable);
  23833. return this;
  23834. };
  23835. /**
  23836. * Associates the vertexData to the passed Geometry.
  23837. * Sets it as updatable or not (default `false`).
  23838. * Returns the VertexData.
  23839. */
  23840. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  23841. this._applyTo(geometry, updatable);
  23842. return this;
  23843. };
  23844. /**
  23845. * Updates the associated mesh.
  23846. * Returns the VertexData.
  23847. */
  23848. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  23849. this._update(mesh);
  23850. return this;
  23851. };
  23852. /**
  23853. * Updates the associated geometry.
  23854. * Returns the VertexData.
  23855. */
  23856. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  23857. this._update(geometry);
  23858. return this;
  23859. };
  23860. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  23861. if (this.positions) {
  23862. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  23863. }
  23864. if (this.normals) {
  23865. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  23866. }
  23867. if (this.tangents) {
  23868. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  23869. }
  23870. if (this.uvs) {
  23871. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  23872. }
  23873. if (this.uvs2) {
  23874. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  23875. }
  23876. if (this.uvs3) {
  23877. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  23878. }
  23879. if (this.uvs4) {
  23880. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  23881. }
  23882. if (this.uvs5) {
  23883. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  23884. }
  23885. if (this.uvs6) {
  23886. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  23887. }
  23888. if (this.colors) {
  23889. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  23890. }
  23891. if (this.matricesIndices) {
  23892. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  23893. }
  23894. if (this.matricesWeights) {
  23895. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  23896. }
  23897. if (this.matricesIndicesExtra) {
  23898. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  23899. }
  23900. if (this.matricesWeightsExtra) {
  23901. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  23902. }
  23903. if (this.indices) {
  23904. meshOrGeometry.setIndices(this.indices);
  23905. }
  23906. return this;
  23907. };
  23908. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  23909. if (this.positions) {
  23910. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  23911. }
  23912. if (this.normals) {
  23913. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  23914. }
  23915. if (this.tangents) {
  23916. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  23917. }
  23918. if (this.uvs) {
  23919. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  23920. }
  23921. if (this.uvs2) {
  23922. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  23923. }
  23924. if (this.uvs3) {
  23925. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  23926. }
  23927. if (this.uvs4) {
  23928. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  23929. }
  23930. if (this.uvs5) {
  23931. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  23932. }
  23933. if (this.uvs6) {
  23934. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  23935. }
  23936. if (this.colors) {
  23937. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  23938. }
  23939. if (this.matricesIndices) {
  23940. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  23941. }
  23942. if (this.matricesWeights) {
  23943. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  23944. }
  23945. if (this.matricesIndicesExtra) {
  23946. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  23947. }
  23948. if (this.matricesWeightsExtra) {
  23949. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  23950. }
  23951. if (this.indices) {
  23952. meshOrGeometry.setIndices(this.indices);
  23953. }
  23954. return this;
  23955. };
  23956. /**
  23957. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  23958. * Returns the VertexData.
  23959. */
  23960. VertexData.prototype.transform = function (matrix) {
  23961. var transformed = BABYLON.Vector3.Zero();
  23962. var index;
  23963. if (this.positions) {
  23964. var position = BABYLON.Vector3.Zero();
  23965. for (index = 0; index < this.positions.length; index += 3) {
  23966. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  23967. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  23968. this.positions[index] = transformed.x;
  23969. this.positions[index + 1] = transformed.y;
  23970. this.positions[index + 2] = transformed.z;
  23971. }
  23972. }
  23973. if (this.normals) {
  23974. var normal = BABYLON.Vector3.Zero();
  23975. for (index = 0; index < this.normals.length; index += 3) {
  23976. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  23977. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  23978. this.normals[index] = transformed.x;
  23979. this.normals[index + 1] = transformed.y;
  23980. this.normals[index + 2] = transformed.z;
  23981. }
  23982. }
  23983. if (this.tangents) {
  23984. var tangent = BABYLON.Vector4.Zero();
  23985. var tangentTransformed = BABYLON.Vector4.Zero();
  23986. for (index = 0; index < this.tangents.length; index += 4) {
  23987. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  23988. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  23989. this.tangents[index] = tangentTransformed.x;
  23990. this.tangents[index + 1] = tangentTransformed.y;
  23991. this.tangents[index + 2] = tangentTransformed.z;
  23992. this.tangents[index + 3] = tangentTransformed.w;
  23993. }
  23994. }
  23995. return this;
  23996. };
  23997. /**
  23998. * Merges the passed VertexData into the current one.
  23999. * Returns the modified VertexData.
  24000. */
  24001. VertexData.prototype.merge = function (other) {
  24002. if (other.indices) {
  24003. if (!this.indices) {
  24004. this.indices = [];
  24005. }
  24006. var offset = this.positions ? this.positions.length / 3 : 0;
  24007. for (var index = 0; index < other.indices.length; index++) {
  24008. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  24009. this.indices.push(other.indices[index] + offset);
  24010. }
  24011. }
  24012. this.positions = this._mergeElement(this.positions, other.positions);
  24013. this.normals = this._mergeElement(this.normals, other.normals);
  24014. this.tangents = this._mergeElement(this.tangents, other.tangents);
  24015. this.uvs = this._mergeElement(this.uvs, other.uvs);
  24016. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  24017. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  24018. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  24019. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  24020. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  24021. this.colors = this._mergeElement(this.colors, other.colors);
  24022. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  24023. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  24024. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  24025. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  24026. return this;
  24027. };
  24028. VertexData.prototype._mergeElement = function (source, other) {
  24029. if (!other)
  24030. return source;
  24031. if (!source)
  24032. return other;
  24033. var len = other.length + source.length;
  24034. var isSrcTypedArray = source instanceof Float32Array;
  24035. var isOthTypedArray = other instanceof Float32Array;
  24036. // use non-loop method when the source is Float32Array
  24037. if (isSrcTypedArray) {
  24038. var ret32 = new Float32Array(len);
  24039. ret32.set(source);
  24040. ret32.set(other, source.length);
  24041. return ret32;
  24042. // source is number[], when other is also use concat
  24043. }
  24044. else if (!isOthTypedArray) {
  24045. return source.concat(other);
  24046. // source is a number[], but other is a Float32Array, loop required
  24047. }
  24048. else {
  24049. var ret = source.slice(0); // copy source to a separate array
  24050. for (var i = 0, len = other.length; i < len; i++) {
  24051. ret.push(other[i]);
  24052. }
  24053. return ret;
  24054. }
  24055. };
  24056. /**
  24057. * Serializes the VertexData.
  24058. * Returns a serialized object.
  24059. */
  24060. VertexData.prototype.serialize = function () {
  24061. var serializationObject = this.serialize();
  24062. if (this.positions) {
  24063. serializationObject.positions = this.positions;
  24064. }
  24065. if (this.normals) {
  24066. serializationObject.normals = this.normals;
  24067. }
  24068. if (this.tangents) {
  24069. serializationObject.tangents = this.tangents;
  24070. }
  24071. if (this.uvs) {
  24072. serializationObject.uvs = this.uvs;
  24073. }
  24074. if (this.uvs2) {
  24075. serializationObject.uvs2 = this.uvs2;
  24076. }
  24077. if (this.uvs3) {
  24078. serializationObject.uvs3 = this.uvs3;
  24079. }
  24080. if (this.uvs4) {
  24081. serializationObject.uvs4 = this.uvs4;
  24082. }
  24083. if (this.uvs5) {
  24084. serializationObject.uvs5 = this.uvs5;
  24085. }
  24086. if (this.uvs6) {
  24087. serializationObject.uvs6 = this.uvs6;
  24088. }
  24089. if (this.colors) {
  24090. serializationObject.colors = this.colors;
  24091. }
  24092. if (this.matricesIndices) {
  24093. serializationObject.matricesIndices = this.matricesIndices;
  24094. serializationObject.matricesIndices._isExpanded = true;
  24095. }
  24096. if (this.matricesWeights) {
  24097. serializationObject.matricesWeights = this.matricesWeights;
  24098. }
  24099. if (this.matricesIndicesExtra) {
  24100. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  24101. serializationObject.matricesIndicesExtra._isExpanded = true;
  24102. }
  24103. if (this.matricesWeightsExtra) {
  24104. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  24105. }
  24106. serializationObject.indices = this.indices;
  24107. return serializationObject;
  24108. };
  24109. // Statics
  24110. /**
  24111. * Returns the object VertexData associated to the passed mesh.
  24112. */
  24113. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  24114. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  24115. };
  24116. /**
  24117. * Returns the object VertexData associated to the passed geometry.
  24118. */
  24119. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  24120. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  24121. };
  24122. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  24123. var result = new VertexData();
  24124. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24125. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  24126. }
  24127. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24128. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  24129. }
  24130. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  24131. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  24132. }
  24133. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24134. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  24135. }
  24136. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24137. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  24138. }
  24139. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  24140. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  24141. }
  24142. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  24143. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  24144. }
  24145. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  24146. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  24147. }
  24148. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  24149. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  24150. }
  24151. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24152. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  24153. }
  24154. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24155. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  24156. }
  24157. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24158. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  24159. }
  24160. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  24161. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  24162. }
  24163. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  24164. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  24165. }
  24166. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  24167. return result;
  24168. };
  24169. /**
  24170. * Creates the vertexData of the Ribbon.
  24171. */
  24172. VertexData.CreateRibbon = function (options) {
  24173. var pathArray = options.pathArray;
  24174. var closeArray = options.closeArray || false;
  24175. var closePath = options.closePath || false;
  24176. var invertUV = options.invertUV || false;
  24177. var defaultOffset = Math.floor(pathArray[0].length / 2);
  24178. var offset = options.offset || defaultOffset;
  24179. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  24180. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24181. var customUV = options.uvs;
  24182. var customColors = options.colors;
  24183. var positions = [];
  24184. var indices = [];
  24185. var normals = [];
  24186. var uvs = [];
  24187. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  24188. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  24189. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  24190. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  24191. var minlg; // minimal length among all paths from pathArray
  24192. var lg = []; // array of path lengths : nb of vertex per path
  24193. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  24194. var p; // path iterator
  24195. var i; // point iterator
  24196. var j; // point iterator
  24197. // if single path in pathArray
  24198. if (pathArray.length < 2) {
  24199. var ar1 = [];
  24200. var ar2 = [];
  24201. for (i = 0; i < pathArray[0].length - offset; i++) {
  24202. ar1.push(pathArray[0][i]);
  24203. ar2.push(pathArray[0][i + offset]);
  24204. }
  24205. pathArray = [ar1, ar2];
  24206. }
  24207. // positions and horizontal distances (u)
  24208. var idc = 0;
  24209. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  24210. var path;
  24211. var l;
  24212. minlg = pathArray[0].length;
  24213. var vectlg;
  24214. var dist;
  24215. for (p = 0; p < pathArray.length; p++) {
  24216. uTotalDistance[p] = 0;
  24217. us[p] = [0];
  24218. path = pathArray[p];
  24219. l = path.length;
  24220. minlg = (minlg < l) ? minlg : l;
  24221. j = 0;
  24222. while (j < l) {
  24223. positions.push(path[j].x, path[j].y, path[j].z);
  24224. if (j > 0) {
  24225. vectlg = path[j].subtract(path[j - 1]).length();
  24226. dist = vectlg + uTotalDistance[p];
  24227. us[p].push(dist);
  24228. uTotalDistance[p] = dist;
  24229. }
  24230. j++;
  24231. }
  24232. if (closePath) {
  24233. j--;
  24234. positions.push(path[0].x, path[0].y, path[0].z);
  24235. vectlg = path[j].subtract(path[0]).length();
  24236. dist = vectlg + uTotalDistance[p];
  24237. us[p].push(dist);
  24238. uTotalDistance[p] = dist;
  24239. }
  24240. lg[p] = l + closePathCorr;
  24241. idx[p] = idc;
  24242. idc += (l + closePathCorr);
  24243. }
  24244. // vertical distances (v)
  24245. var path1;
  24246. var path2;
  24247. var vertex1;
  24248. var vertex2;
  24249. for (i = 0; i < minlg + closePathCorr; i++) {
  24250. vTotalDistance[i] = 0;
  24251. vs[i] = [0];
  24252. for (p = 0; p < pathArray.length - 1; p++) {
  24253. path1 = pathArray[p];
  24254. path2 = pathArray[p + 1];
  24255. if (i === minlg) {
  24256. vertex1 = path1[0];
  24257. vertex2 = path2[0];
  24258. }
  24259. else {
  24260. vertex1 = path1[i];
  24261. vertex2 = path2[i];
  24262. }
  24263. vectlg = vertex2.subtract(vertex1).length();
  24264. dist = vectlg + vTotalDistance[i];
  24265. vs[i].push(dist);
  24266. vTotalDistance[i] = dist;
  24267. }
  24268. if (closeArray) {
  24269. path1 = pathArray[p];
  24270. path2 = pathArray[0];
  24271. if (i === minlg) {
  24272. vertex2 = path2[0];
  24273. }
  24274. vectlg = vertex2.subtract(vertex1).length();
  24275. dist = vectlg + vTotalDistance[i];
  24276. vTotalDistance[i] = dist;
  24277. }
  24278. }
  24279. // uvs
  24280. var u;
  24281. var v;
  24282. if (customUV) {
  24283. for (p = 0; p < customUV.length; p++) {
  24284. uvs.push(customUV[p].x, customUV[p].y);
  24285. }
  24286. }
  24287. else {
  24288. for (p = 0; p < pathArray.length; p++) {
  24289. for (i = 0; i < minlg + closePathCorr; i++) {
  24290. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  24291. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  24292. if (invertUV) {
  24293. uvs.push(v, u);
  24294. }
  24295. else {
  24296. uvs.push(u, v);
  24297. }
  24298. }
  24299. }
  24300. }
  24301. // indices
  24302. p = 0; // path index
  24303. var pi = 0; // positions array index
  24304. var l1 = lg[p] - 1; // path1 length
  24305. var l2 = lg[p + 1] - 1; // path2 length
  24306. var min = (l1 < l2) ? l1 : l2; // current path stop index
  24307. var shft = idx[1] - idx[0]; // shift
  24308. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  24309. while (pi <= min && p < path1nb) {
  24310. // 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
  24311. indices.push(pi, pi + shft, pi + 1);
  24312. indices.push(pi + shft + 1, pi + 1, pi + shft);
  24313. pi += 1;
  24314. if (pi === min) {
  24315. p++;
  24316. if (p === lg.length - 1) {
  24317. shft = idx[0] - idx[p];
  24318. l1 = lg[p] - 1;
  24319. l2 = lg[0] - 1;
  24320. }
  24321. else {
  24322. shft = idx[p + 1] - idx[p];
  24323. l1 = lg[p] - 1;
  24324. l2 = lg[p + 1] - 1;
  24325. }
  24326. pi = idx[p];
  24327. min = (l1 < l2) ? l1 + pi : l2 + pi;
  24328. }
  24329. }
  24330. // normals
  24331. VertexData.ComputeNormals(positions, indices, normals);
  24332. if (closePath) {
  24333. var indexFirst = 0;
  24334. var indexLast = 0;
  24335. for (p = 0; p < pathArray.length; p++) {
  24336. indexFirst = idx[p] * 3;
  24337. if (p + 1 < pathArray.length) {
  24338. indexLast = (idx[p + 1] - 1) * 3;
  24339. }
  24340. else {
  24341. indexLast = normals.length - 3;
  24342. }
  24343. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  24344. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  24345. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  24346. normals[indexLast] = normals[indexFirst];
  24347. normals[indexLast + 1] = normals[indexFirst + 1];
  24348. normals[indexLast + 2] = normals[indexFirst + 2];
  24349. }
  24350. }
  24351. // sides
  24352. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24353. // Colors
  24354. if (customColors) {
  24355. var colors = new Float32Array(customColors.length * 4);
  24356. for (var c = 0; c < customColors.length; c++) {
  24357. colors[c * 4] = customColors[c].r;
  24358. colors[c * 4 + 1] = customColors[c].g;
  24359. colors[c * 4 + 2] = customColors[c].b;
  24360. colors[c * 4 + 3] = customColors[c].a;
  24361. }
  24362. }
  24363. // Result
  24364. var vertexData = new VertexData();
  24365. var positions32 = new Float32Array(positions);
  24366. var normals32 = new Float32Array(normals);
  24367. var uvs32 = new Float32Array(uvs);
  24368. vertexData.indices = indices;
  24369. vertexData.positions = positions32;
  24370. vertexData.normals = normals32;
  24371. vertexData.uvs = uvs32;
  24372. if (customColors) {
  24373. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  24374. }
  24375. if (closePath) {
  24376. vertexData._idx = idx;
  24377. }
  24378. return vertexData;
  24379. };
  24380. /**
  24381. * Creates the VertexData of the Box.
  24382. */
  24383. VertexData.CreateBox = function (options) {
  24384. var normalsSource = [
  24385. new BABYLON.Vector3(0, 0, 1),
  24386. new BABYLON.Vector3(0, 0, -1),
  24387. new BABYLON.Vector3(1, 0, 0),
  24388. new BABYLON.Vector3(-1, 0, 0),
  24389. new BABYLON.Vector3(0, 1, 0),
  24390. new BABYLON.Vector3(0, -1, 0)
  24391. ];
  24392. var indices = [];
  24393. var positions = [];
  24394. var normals = [];
  24395. var uvs = [];
  24396. var width = options.width || options.size || 1;
  24397. var height = options.height || options.size || 1;
  24398. var depth = options.depth || options.size || 1;
  24399. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24400. var faceUV = options.faceUV || new Array(6);
  24401. var faceColors = options.faceColors;
  24402. var colors = [];
  24403. // default face colors and UV if undefined
  24404. for (var f = 0; f < 6; f++) {
  24405. if (faceUV[f] === undefined) {
  24406. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24407. }
  24408. if (faceColors && faceColors[f] === undefined) {
  24409. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24410. }
  24411. }
  24412. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  24413. // Create each face in turn.
  24414. for (var index = 0; index < normalsSource.length; index++) {
  24415. var normal = normalsSource[index];
  24416. // Get two vectors perpendicular to the face normal and to each other.
  24417. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  24418. var side2 = BABYLON.Vector3.Cross(normal, side1);
  24419. // Six indices (two triangles) per face.
  24420. var verticesLength = positions.length / 3;
  24421. indices.push(verticesLength);
  24422. indices.push(verticesLength + 1);
  24423. indices.push(verticesLength + 2);
  24424. indices.push(verticesLength);
  24425. indices.push(verticesLength + 2);
  24426. indices.push(verticesLength + 3);
  24427. // Four vertices per face.
  24428. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  24429. positions.push(vertex.x, vertex.y, vertex.z);
  24430. normals.push(normal.x, normal.y, normal.z);
  24431. uvs.push(faceUV[index].z, faceUV[index].w);
  24432. if (faceColors) {
  24433. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24434. }
  24435. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  24436. positions.push(vertex.x, vertex.y, vertex.z);
  24437. normals.push(normal.x, normal.y, normal.z);
  24438. uvs.push(faceUV[index].x, faceUV[index].w);
  24439. if (faceColors) {
  24440. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24441. }
  24442. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  24443. positions.push(vertex.x, vertex.y, vertex.z);
  24444. normals.push(normal.x, normal.y, normal.z);
  24445. uvs.push(faceUV[index].x, faceUV[index].y);
  24446. if (faceColors) {
  24447. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24448. }
  24449. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  24450. positions.push(vertex.x, vertex.y, vertex.z);
  24451. normals.push(normal.x, normal.y, normal.z);
  24452. uvs.push(faceUV[index].z, faceUV[index].y);
  24453. if (faceColors) {
  24454. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24455. }
  24456. }
  24457. // sides
  24458. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24459. // Result
  24460. var vertexData = new VertexData();
  24461. vertexData.indices = indices;
  24462. vertexData.positions = positions;
  24463. vertexData.normals = normals;
  24464. vertexData.uvs = uvs;
  24465. if (faceColors) {
  24466. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  24467. vertexData.colors = totalColors;
  24468. }
  24469. return vertexData;
  24470. };
  24471. /**
  24472. * Creates the VertexData of the Sphere.
  24473. */
  24474. VertexData.CreateSphere = function (options) {
  24475. var segments = options.segments || 32;
  24476. var diameterX = options.diameterX || options.diameter || 1;
  24477. var diameterY = options.diameterY || options.diameter || 1;
  24478. var diameterZ = options.diameterZ || options.diameter || 1;
  24479. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24480. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  24481. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24482. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  24483. var totalZRotationSteps = 2 + segments;
  24484. var totalYRotationSteps = 2 * totalZRotationSteps;
  24485. var indices = [];
  24486. var positions = [];
  24487. var normals = [];
  24488. var uvs = [];
  24489. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  24490. var normalizedZ = zRotationStep / totalZRotationSteps;
  24491. var angleZ = normalizedZ * Math.PI * slice;
  24492. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  24493. var normalizedY = yRotationStep / totalYRotationSteps;
  24494. var angleY = normalizedY * Math.PI * 2 * arc;
  24495. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  24496. var rotationY = BABYLON.Matrix.RotationY(angleY);
  24497. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  24498. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  24499. var vertex = complete.multiply(radius);
  24500. var normal = complete.divide(radius).normalize();
  24501. positions.push(vertex.x, vertex.y, vertex.z);
  24502. normals.push(normal.x, normal.y, normal.z);
  24503. uvs.push(normalizedY, normalizedZ);
  24504. }
  24505. if (zRotationStep > 0) {
  24506. var verticesCount = positions.length / 3;
  24507. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  24508. indices.push((firstIndex));
  24509. indices.push((firstIndex + 1));
  24510. indices.push(firstIndex + totalYRotationSteps + 1);
  24511. indices.push((firstIndex + totalYRotationSteps + 1));
  24512. indices.push((firstIndex + 1));
  24513. indices.push((firstIndex + totalYRotationSteps + 2));
  24514. }
  24515. }
  24516. }
  24517. // Sides
  24518. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24519. // Result
  24520. var vertexData = new VertexData();
  24521. vertexData.indices = indices;
  24522. vertexData.positions = positions;
  24523. vertexData.normals = normals;
  24524. vertexData.uvs = uvs;
  24525. return vertexData;
  24526. };
  24527. /**
  24528. * Creates the VertexData of the Cylinder or Cone.
  24529. */
  24530. VertexData.CreateCylinder = function (options) {
  24531. var height = options.height || 2;
  24532. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  24533. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  24534. var tessellation = options.tessellation || 24;
  24535. var subdivisions = options.subdivisions || 1;
  24536. var hasRings = options.hasRings;
  24537. var enclose = options.enclose;
  24538. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24539. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24540. var faceUV = options.faceUV || new Array(3);
  24541. var faceColors = options.faceColors;
  24542. // default face colors and UV if undefined
  24543. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  24544. var ringNb = (hasRings) ? subdivisions : 1;
  24545. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  24546. var f;
  24547. for (f = 0; f < surfaceNb; f++) {
  24548. if (faceColors && faceColors[f] === undefined) {
  24549. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24550. }
  24551. }
  24552. for (f = 0; f < surfaceNb; f++) {
  24553. if (faceUV && faceUV[f] === undefined) {
  24554. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24555. }
  24556. }
  24557. var indices = [];
  24558. var positions = [];
  24559. var normals = [];
  24560. var uvs = [];
  24561. var colors = [];
  24562. var angle_step = Math.PI * 2 * arc / tessellation;
  24563. var angle;
  24564. var h;
  24565. var radius;
  24566. var tan = (diameterBottom - diameterTop) / 2 / height;
  24567. var ringVertex = BABYLON.Vector3.Zero();
  24568. var ringNormal = BABYLON.Vector3.Zero();
  24569. var ringFirstVertex = BABYLON.Vector3.Zero();
  24570. var ringFirstNormal = BABYLON.Vector3.Zero();
  24571. var quadNormal = BABYLON.Vector3.Zero();
  24572. var Y = BABYLON.Axis.Y;
  24573. // positions, normals, uvs
  24574. var i;
  24575. var j;
  24576. var r;
  24577. var ringIdx = 1;
  24578. var s = 1; // surface index
  24579. var cs = 0;
  24580. var v = 0;
  24581. for (i = 0; i <= subdivisions; i++) {
  24582. h = i / subdivisions;
  24583. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  24584. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  24585. for (r = 0; r < ringIdx; r++) {
  24586. if (hasRings) {
  24587. s += r;
  24588. }
  24589. if (enclose) {
  24590. s += 2 * r;
  24591. }
  24592. for (j = 0; j <= tessellation; j++) {
  24593. angle = j * angle_step;
  24594. // position
  24595. ringVertex.x = Math.cos(-angle) * radius;
  24596. ringVertex.y = -height / 2 + h * height;
  24597. ringVertex.z = Math.sin(-angle) * radius;
  24598. // normal
  24599. if (diameterTop === 0 && i === subdivisions) {
  24600. // if no top cap, reuse former normals
  24601. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  24602. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  24603. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  24604. }
  24605. else {
  24606. ringNormal.x = ringVertex.x;
  24607. ringNormal.z = ringVertex.z;
  24608. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  24609. ringNormal.normalize();
  24610. }
  24611. // keep first ring vertex values for enclose
  24612. if (j === 0) {
  24613. ringFirstVertex.copyFrom(ringVertex);
  24614. ringFirstNormal.copyFrom(ringNormal);
  24615. }
  24616. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  24617. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  24618. if (hasRings) {
  24619. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  24620. }
  24621. else {
  24622. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  24623. }
  24624. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  24625. if (faceColors) {
  24626. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  24627. }
  24628. }
  24629. // if enclose, add four vertices and their dedicated normals
  24630. if (arc !== 1 && enclose) {
  24631. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  24632. positions.push(0, ringVertex.y, 0);
  24633. positions.push(0, ringVertex.y, 0);
  24634. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  24635. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  24636. quadNormal.normalize();
  24637. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  24638. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  24639. quadNormal.normalize();
  24640. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  24641. if (hasRings) {
  24642. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  24643. }
  24644. else {
  24645. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  24646. }
  24647. uvs.push(faceUV[s + 1].x, v);
  24648. uvs.push(faceUV[s + 1].z, v);
  24649. if (hasRings) {
  24650. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  24651. }
  24652. else {
  24653. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  24654. }
  24655. uvs.push(faceUV[s + 2].x, v);
  24656. uvs.push(faceUV[s + 2].z, v);
  24657. if (faceColors) {
  24658. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  24659. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  24660. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  24661. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  24662. }
  24663. }
  24664. if (cs !== s) {
  24665. cs = s;
  24666. }
  24667. }
  24668. }
  24669. // indices
  24670. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  24671. var s;
  24672. i = 0;
  24673. for (s = 0; s < subdivisions; s++) {
  24674. for (j = 0; j < tessellation; j++) {
  24675. var i0 = i * (e + 1) + j;
  24676. var i1 = (i + 1) * (e + 1) + j;
  24677. var i2 = i * (e + 1) + (j + 1);
  24678. var i3 = (i + 1) * (e + 1) + (j + 1);
  24679. indices.push(i0, i1, i2);
  24680. indices.push(i3, i2, i1);
  24681. }
  24682. if (arc !== 1 && enclose) {
  24683. indices.push(i0 + 2, i1 + 2, i2 + 2);
  24684. indices.push(i3 + 2, i2 + 2, i1 + 2);
  24685. indices.push(i0 + 4, i1 + 4, i2 + 4);
  24686. indices.push(i3 + 4, i2 + 4, i1 + 4);
  24687. }
  24688. i = (hasRings) ? (i + 2) : (i + 1);
  24689. }
  24690. // Caps
  24691. var createCylinderCap = function (isTop) {
  24692. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  24693. if (radius === 0) {
  24694. return;
  24695. }
  24696. // Cap positions, normals & uvs
  24697. var angle;
  24698. var circleVector;
  24699. var i;
  24700. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  24701. var c;
  24702. if (faceColors) {
  24703. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  24704. }
  24705. // cap center
  24706. var vbase = positions.length / 3;
  24707. var offset = isTop ? height / 2 : -height / 2;
  24708. var center = new BABYLON.Vector3(0, offset, 0);
  24709. positions.push(center.x, center.y, center.z);
  24710. normals.push(0, isTop ? 1 : -1, 0);
  24711. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  24712. if (faceColors) {
  24713. colors.push(c.r, c.g, c.b, c.a);
  24714. }
  24715. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  24716. for (i = 0; i <= tessellation; i++) {
  24717. angle = Math.PI * 2 * i * arc / tessellation;
  24718. var cos = Math.cos(-angle);
  24719. var sin = Math.sin(-angle);
  24720. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  24721. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  24722. positions.push(circleVector.x, circleVector.y, circleVector.z);
  24723. normals.push(0, isTop ? 1 : -1, 0);
  24724. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  24725. if (faceColors) {
  24726. colors.push(c.r, c.g, c.b, c.a);
  24727. }
  24728. }
  24729. // Cap indices
  24730. for (i = 0; i < tessellation; i++) {
  24731. if (!isTop) {
  24732. indices.push(vbase);
  24733. indices.push(vbase + (i + 1));
  24734. indices.push(vbase + (i + 2));
  24735. }
  24736. else {
  24737. indices.push(vbase);
  24738. indices.push(vbase + (i + 2));
  24739. indices.push(vbase + (i + 1));
  24740. }
  24741. }
  24742. };
  24743. // add caps to geometry
  24744. createCylinderCap(false);
  24745. createCylinderCap(true);
  24746. // Sides
  24747. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24748. var vertexData = new VertexData();
  24749. vertexData.indices = indices;
  24750. vertexData.positions = positions;
  24751. vertexData.normals = normals;
  24752. vertexData.uvs = uvs;
  24753. if (faceColors) {
  24754. vertexData.colors = colors;
  24755. }
  24756. return vertexData;
  24757. };
  24758. /**
  24759. * Creates the VertexData of the Torus.
  24760. */
  24761. VertexData.CreateTorus = function (options) {
  24762. var indices = [];
  24763. var positions = [];
  24764. var normals = [];
  24765. var uvs = [];
  24766. var diameter = options.diameter || 1;
  24767. var thickness = options.thickness || 0.5;
  24768. var tessellation = options.tessellation || 16;
  24769. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24770. var stride = tessellation + 1;
  24771. for (var i = 0; i <= tessellation; i++) {
  24772. var u = i / tessellation;
  24773. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  24774. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  24775. for (var j = 0; j <= tessellation; j++) {
  24776. var v = 1 - j / tessellation;
  24777. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  24778. var dx = Math.cos(innerAngle);
  24779. var dy = Math.sin(innerAngle);
  24780. // Create a vertex.
  24781. var normal = new BABYLON.Vector3(dx, dy, 0);
  24782. var position = normal.scale(thickness / 2);
  24783. var textureCoordinate = new BABYLON.Vector2(u, v);
  24784. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  24785. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  24786. positions.push(position.x, position.y, position.z);
  24787. normals.push(normal.x, normal.y, normal.z);
  24788. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24789. // And create indices for two triangles.
  24790. var nextI = (i + 1) % stride;
  24791. var nextJ = (j + 1) % stride;
  24792. indices.push(i * stride + j);
  24793. indices.push(i * stride + nextJ);
  24794. indices.push(nextI * stride + j);
  24795. indices.push(i * stride + nextJ);
  24796. indices.push(nextI * stride + nextJ);
  24797. indices.push(nextI * stride + j);
  24798. }
  24799. }
  24800. // Sides
  24801. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24802. // Result
  24803. var vertexData = new VertexData();
  24804. vertexData.indices = indices;
  24805. vertexData.positions = positions;
  24806. vertexData.normals = normals;
  24807. vertexData.uvs = uvs;
  24808. return vertexData;
  24809. };
  24810. /**
  24811. * Creates the VertexData of the LineSystem.
  24812. */
  24813. VertexData.CreateLineSystem = function (options) {
  24814. var indices = [];
  24815. var positions = [];
  24816. var lines = options.lines;
  24817. var idx = 0;
  24818. for (var l = 0; l < lines.length; l++) {
  24819. var points = lines[l];
  24820. for (var index = 0; index < points.length; index++) {
  24821. positions.push(points[index].x, points[index].y, points[index].z);
  24822. if (index > 0) {
  24823. indices.push(idx - 1);
  24824. indices.push(idx);
  24825. }
  24826. idx++;
  24827. }
  24828. }
  24829. var vertexData = new VertexData();
  24830. vertexData.indices = indices;
  24831. vertexData.positions = positions;
  24832. return vertexData;
  24833. };
  24834. /**
  24835. * Create the VertexData of the DashedLines.
  24836. */
  24837. VertexData.CreateDashedLines = function (options) {
  24838. var dashSize = options.dashSize || 3;
  24839. var gapSize = options.gapSize || 1;
  24840. var dashNb = options.dashNb || 200;
  24841. var points = options.points;
  24842. var positions = new Array();
  24843. var indices = new Array();
  24844. var curvect = BABYLON.Vector3.Zero();
  24845. var lg = 0;
  24846. var nb = 0;
  24847. var shft = 0;
  24848. var dashshft = 0;
  24849. var curshft = 0;
  24850. var idx = 0;
  24851. var i = 0;
  24852. for (i = 0; i < points.length - 1; i++) {
  24853. points[i + 1].subtractToRef(points[i], curvect);
  24854. lg += curvect.length();
  24855. }
  24856. shft = lg / dashNb;
  24857. dashshft = dashSize * shft / (dashSize + gapSize);
  24858. for (i = 0; i < points.length - 1; i++) {
  24859. points[i + 1].subtractToRef(points[i], curvect);
  24860. nb = Math.floor(curvect.length() / shft);
  24861. curvect.normalize();
  24862. for (var j = 0; j < nb; j++) {
  24863. curshft = shft * j;
  24864. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  24865. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  24866. indices.push(idx, idx + 1);
  24867. idx += 2;
  24868. }
  24869. }
  24870. // Result
  24871. var vertexData = new VertexData();
  24872. vertexData.positions = positions;
  24873. vertexData.indices = indices;
  24874. return vertexData;
  24875. };
  24876. /**
  24877. * Creates the VertexData of the Ground.
  24878. */
  24879. VertexData.CreateGround = function (options) {
  24880. var indices = [];
  24881. var positions = [];
  24882. var normals = [];
  24883. var uvs = [];
  24884. var row, col;
  24885. var width = options.width || 1;
  24886. var height = options.height || 1;
  24887. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  24888. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  24889. for (row = 0; row <= subdivisionsY; row++) {
  24890. for (col = 0; col <= subdivisionsX; col++) {
  24891. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  24892. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24893. positions.push(position.x, position.y, position.z);
  24894. normals.push(normal.x, normal.y, normal.z);
  24895. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  24896. }
  24897. }
  24898. for (row = 0; row < subdivisionsY; row++) {
  24899. for (col = 0; col < subdivisionsX; col++) {
  24900. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  24901. indices.push(col + 1 + row * (subdivisionsX + 1));
  24902. indices.push(col + row * (subdivisionsX + 1));
  24903. indices.push(col + (row + 1) * (subdivisionsX + 1));
  24904. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  24905. indices.push(col + row * (subdivisionsX + 1));
  24906. }
  24907. }
  24908. // Result
  24909. var vertexData = new VertexData();
  24910. vertexData.indices = indices;
  24911. vertexData.positions = positions;
  24912. vertexData.normals = normals;
  24913. vertexData.uvs = uvs;
  24914. return vertexData;
  24915. };
  24916. /**
  24917. * Creates the VertexData of the TiledGround.
  24918. */
  24919. VertexData.CreateTiledGround = function (options) {
  24920. var xmin = options.xmin || -1.0;
  24921. var zmin = options.zmin || -1.0;
  24922. var xmax = options.xmax || 1.0;
  24923. var zmax = options.zmax || 1.0;
  24924. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  24925. var precision = options.precision || { w: 1, h: 1 };
  24926. var indices = [];
  24927. var positions = [];
  24928. var normals = [];
  24929. var uvs = [];
  24930. var row, col, tileRow, tileCol;
  24931. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  24932. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  24933. precision.w = (precision.w < 1) ? 1 : precision.w;
  24934. precision.h = (precision.h < 1) ? 1 : precision.h;
  24935. var tileSize = {
  24936. 'w': (xmax - xmin) / subdivisions.w,
  24937. 'h': (zmax - zmin) / subdivisions.h
  24938. };
  24939. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  24940. // Indices
  24941. var base = positions.length / 3;
  24942. var rowLength = precision.w + 1;
  24943. for (row = 0; row < precision.h; row++) {
  24944. for (col = 0; col < precision.w; col++) {
  24945. var square = [
  24946. base + col + row * rowLength,
  24947. base + (col + 1) + row * rowLength,
  24948. base + (col + 1) + (row + 1) * rowLength,
  24949. base + col + (row + 1) * rowLength
  24950. ];
  24951. indices.push(square[1]);
  24952. indices.push(square[2]);
  24953. indices.push(square[3]);
  24954. indices.push(square[0]);
  24955. indices.push(square[1]);
  24956. indices.push(square[3]);
  24957. }
  24958. }
  24959. // Position, normals and uvs
  24960. var position = BABYLON.Vector3.Zero();
  24961. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24962. for (row = 0; row <= precision.h; row++) {
  24963. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  24964. for (col = 0; col <= precision.w; col++) {
  24965. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  24966. position.y = 0;
  24967. positions.push(position.x, position.y, position.z);
  24968. normals.push(normal.x, normal.y, normal.z);
  24969. uvs.push(col / precision.w, row / precision.h);
  24970. }
  24971. }
  24972. }
  24973. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  24974. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  24975. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  24976. }
  24977. }
  24978. // Result
  24979. var vertexData = new VertexData();
  24980. vertexData.indices = indices;
  24981. vertexData.positions = positions;
  24982. vertexData.normals = normals;
  24983. vertexData.uvs = uvs;
  24984. return vertexData;
  24985. };
  24986. /**
  24987. * Creates the VertexData of the Ground designed from a heightmap.
  24988. */
  24989. VertexData.CreateGroundFromHeightMap = function (options) {
  24990. var indices = [];
  24991. var positions = [];
  24992. var normals = [];
  24993. var uvs = [];
  24994. var row, col;
  24995. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  24996. // Vertices
  24997. for (row = 0; row <= options.subdivisions; row++) {
  24998. for (col = 0; col <= options.subdivisions; col++) {
  24999. 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));
  25000. // Compute height
  25001. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  25002. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  25003. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  25004. var r = options.buffer[pos] / 255.0;
  25005. var g = options.buffer[pos + 1] / 255.0;
  25006. var b = options.buffer[pos + 2] / 255.0;
  25007. var gradient = r * filter.r + g * filter.g + b * filter.b;
  25008. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  25009. // Add vertex
  25010. positions.push(position.x, position.y, position.z);
  25011. normals.push(0, 0, 0);
  25012. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  25013. }
  25014. }
  25015. // Indices
  25016. for (row = 0; row < options.subdivisions; row++) {
  25017. for (col = 0; col < options.subdivisions; col++) {
  25018. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25019. indices.push(col + 1 + row * (options.subdivisions + 1));
  25020. indices.push(col + row * (options.subdivisions + 1));
  25021. indices.push(col + (row + 1) * (options.subdivisions + 1));
  25022. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  25023. indices.push(col + row * (options.subdivisions + 1));
  25024. }
  25025. }
  25026. // Normals
  25027. VertexData.ComputeNormals(positions, indices, normals);
  25028. // Result
  25029. var vertexData = new VertexData();
  25030. vertexData.indices = indices;
  25031. vertexData.positions = positions;
  25032. vertexData.normals = normals;
  25033. vertexData.uvs = uvs;
  25034. return vertexData;
  25035. };
  25036. /**
  25037. * Creates the VertexData of the Plane.
  25038. */
  25039. VertexData.CreatePlane = function (options) {
  25040. var indices = [];
  25041. var positions = [];
  25042. var normals = [];
  25043. var uvs = [];
  25044. var width = options.width || options.size || 1;
  25045. var height = options.height || options.size || 1;
  25046. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25047. // Vertices
  25048. var halfWidth = width / 2.0;
  25049. var halfHeight = height / 2.0;
  25050. positions.push(-halfWidth, -halfHeight, 0);
  25051. normals.push(0, 0, -1.0);
  25052. uvs.push(0.0, 0.0);
  25053. positions.push(halfWidth, -halfHeight, 0);
  25054. normals.push(0, 0, -1.0);
  25055. uvs.push(1.0, 0.0);
  25056. positions.push(halfWidth, halfHeight, 0);
  25057. normals.push(0, 0, -1.0);
  25058. uvs.push(1.0, 1.0);
  25059. positions.push(-halfWidth, halfHeight, 0);
  25060. normals.push(0, 0, -1.0);
  25061. uvs.push(0.0, 1.0);
  25062. // Indices
  25063. indices.push(0);
  25064. indices.push(1);
  25065. indices.push(2);
  25066. indices.push(0);
  25067. indices.push(2);
  25068. indices.push(3);
  25069. // Sides
  25070. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25071. // Result
  25072. var vertexData = new VertexData();
  25073. vertexData.indices = indices;
  25074. vertexData.positions = positions;
  25075. vertexData.normals = normals;
  25076. vertexData.uvs = uvs;
  25077. return vertexData;
  25078. };
  25079. /**
  25080. * Creates the VertexData of the Disc or regular Polygon.
  25081. */
  25082. VertexData.CreateDisc = function (options) {
  25083. var positions = [];
  25084. var indices = [];
  25085. var normals = [];
  25086. var uvs = [];
  25087. var radius = options.radius || 0.5;
  25088. var tessellation = options.tessellation || 64;
  25089. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25090. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25091. // positions and uvs
  25092. positions.push(0, 0, 0); // disc center first
  25093. uvs.push(0.5, 0.5);
  25094. var theta = Math.PI * 2 * arc;
  25095. var step = theta / tessellation;
  25096. for (var a = 0; a < theta; a += step) {
  25097. var x = Math.cos(a);
  25098. var y = Math.sin(a);
  25099. var u = (x + 1) / 2;
  25100. var v = (1 - y) / 2;
  25101. positions.push(radius * x, radius * y, 0);
  25102. uvs.push(u, v);
  25103. }
  25104. if (arc === 1) {
  25105. positions.push(positions[3], positions[4], positions[5]); // close the circle
  25106. uvs.push(uvs[2], uvs[3]);
  25107. }
  25108. //indices
  25109. var vertexNb = positions.length / 3;
  25110. for (var i = 1; i < vertexNb - 1; i++) {
  25111. indices.push(i + 1, 0, i);
  25112. }
  25113. // result
  25114. VertexData.ComputeNormals(positions, indices, normals);
  25115. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25116. var vertexData = new VertexData();
  25117. vertexData.indices = indices;
  25118. vertexData.positions = positions;
  25119. vertexData.normals = normals;
  25120. vertexData.uvs = uvs;
  25121. return vertexData;
  25122. };
  25123. /**
  25124. * Creates the VertexData of the IcoSphere.
  25125. */
  25126. VertexData.CreateIcoSphere = function (options) {
  25127. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25128. var radius = options.radius || 1;
  25129. var flat = (options.flat === undefined) ? true : options.flat;
  25130. var subdivisions = options.subdivisions || 4;
  25131. var radiusX = options.radiusX || radius;
  25132. var radiusY = options.radiusY || radius;
  25133. var radiusZ = options.radiusZ || radius;
  25134. var t = (1 + Math.sqrt(5)) / 2;
  25135. // 12 vertex x,y,z
  25136. var ico_vertices = [
  25137. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  25138. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  25139. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  25140. ];
  25141. // index of 3 vertex makes a face of icopshere
  25142. var ico_indices = [
  25143. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  25144. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  25145. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  25146. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  25147. ];
  25148. // vertex for uv have aliased position, not for UV
  25149. var vertices_unalias_id = [
  25150. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  25151. // vertex alias
  25152. 0,
  25153. 2,
  25154. 3,
  25155. 3,
  25156. 3,
  25157. 4,
  25158. 7,
  25159. 8,
  25160. 9,
  25161. 9,
  25162. 10,
  25163. 11 // 23: B + 12
  25164. ];
  25165. // uv as integer step (not pixels !)
  25166. var ico_vertexuv = [
  25167. 5, 1, 3, 1, 6, 4, 0, 0,
  25168. 5, 3, 4, 2, 2, 2, 4, 0,
  25169. 2, 0, 1, 1, 6, 0, 6, 2,
  25170. // vertex alias (for same vertex on different faces)
  25171. 0, 4,
  25172. 3, 3,
  25173. 4, 4,
  25174. 3, 1,
  25175. 4, 2,
  25176. 4, 4,
  25177. 0, 2,
  25178. 1, 1,
  25179. 2, 2,
  25180. 3, 3,
  25181. 1, 3,
  25182. 2, 4 // 23: B + 12
  25183. ];
  25184. // Vertices[0, 1, ...9, A, B] : position on UV plane
  25185. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  25186. // First island of uv mapping
  25187. // v = 4h 3+ 2
  25188. // v = 3h 9+ 4
  25189. // v = 2h 9+ 5 B
  25190. // v = 1h 9 1 0
  25191. // v = 0h 3 8 7 A
  25192. // u = 0 1 2 3 4 5 6 *a
  25193. // Second island of uv mapping
  25194. // v = 4h 0+ B+ 4+
  25195. // v = 3h A+ 2+
  25196. // v = 2h 7+ 6 3+
  25197. // v = 1h 8+ 3+
  25198. // v = 0h
  25199. // u = 0 1 2 3 4 5 6 *a
  25200. // Face layout on texture UV mapping
  25201. // ============
  25202. // \ 4 /\ 16 / ======
  25203. // \ / \ / /\ 11 /
  25204. // \/ 7 \/ / \ /
  25205. // ======= / 10 \/
  25206. // /\ 17 /\ =======
  25207. // / \ / \ \ 15 /\
  25208. // / 8 \/ 12 \ \ / \
  25209. // ============ \/ 6 \
  25210. // \ 18 /\ ============
  25211. // \ / \ \ 5 /\ 0 /
  25212. // \/ 13 \ \ / \ /
  25213. // ======= \/ 1 \/
  25214. // =============
  25215. // /\ 19 /\ 2 /\
  25216. // / \ / \ / \
  25217. // / 14 \/ 9 \/ 3 \
  25218. // ===================
  25219. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  25220. var ustep = 138 / 1024;
  25221. var vstep = 239 / 1024;
  25222. var uoffset = 60 / 1024;
  25223. var voffset = 26 / 1024;
  25224. // Second island should have margin, not to touch the first island
  25225. // avoid any borderline artefact in pixel rounding
  25226. var island_u_offset = -40 / 1024;
  25227. var island_v_offset = +20 / 1024;
  25228. // face is either island 0 or 1 :
  25229. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  25230. var island = [
  25231. 0, 0, 0, 0, 1,
  25232. 0, 0, 1, 1, 0,
  25233. 0, 0, 1, 1, 0,
  25234. 0, 1, 1, 1, 0 // 15 - 19
  25235. ];
  25236. var indices = [];
  25237. var positions = [];
  25238. var normals = [];
  25239. var uvs = [];
  25240. var current_indice = 0;
  25241. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  25242. var face_vertex_pos = new Array(3);
  25243. var face_vertex_uv = new Array(3);
  25244. var v012;
  25245. for (v012 = 0; v012 < 3; v012++) {
  25246. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  25247. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  25248. }
  25249. // create all with normals
  25250. for (var face = 0; face < 20; face++) {
  25251. // 3 vertex per face
  25252. for (v012 = 0; v012 < 3; v012++) {
  25253. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  25254. var v_id = ico_indices[3 * face + v012];
  25255. // vertex have 3D position (x,y,z)
  25256. 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]);
  25257. // Normalize to get normal, then scale to radius
  25258. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  25259. // uv Coordinates from vertex ID
  25260. 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);
  25261. }
  25262. // Subdivide the face (interpolate pos, norm, uv)
  25263. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  25264. // - norm is linear interpolation of vertex corner normal
  25265. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  25266. // - uv is linear interpolation
  25267. //
  25268. // Topology is as below for sub-divide by 2
  25269. // vertex shown as v0,v1,v2
  25270. // interp index is i1 to progress in range [v0,v1[
  25271. // interp index is i2 to progress in range [v0,v2[
  25272. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  25273. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25274. //
  25275. //
  25276. // i2 v2
  25277. // ^ ^
  25278. // / / \
  25279. // / / \
  25280. // / / \
  25281. // / / (0,1) \
  25282. // / #---------\
  25283. // / / \ (0,0)'/ \
  25284. // / / \ / \
  25285. // / / \ / \
  25286. // / / (0,0) \ / (1,0) \
  25287. // / #---------#---------\
  25288. // v0 v1
  25289. //
  25290. // --------------------> i1
  25291. //
  25292. // interp of (i1,i2):
  25293. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  25294. // along i1 : lerp(x0,x1, i1/(S-i2))
  25295. //
  25296. // centroid of triangle is needed to get help normal computation
  25297. // (c1,c2) are used for centroid location
  25298. var interp_vertex = function (i1, i2, c1, c2) {
  25299. // vertex is interpolated from
  25300. // - face_vertex_pos[0..2]
  25301. // - face_vertex_uv[0..2]
  25302. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  25303. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  25304. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  25305. pos_interp.normalize();
  25306. var vertex_normal;
  25307. if (flat) {
  25308. // in flat mode, recalculate normal as face centroid normal
  25309. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  25310. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  25311. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  25312. }
  25313. else {
  25314. // in smooth mode, recalculate normal from each single vertex position
  25315. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  25316. }
  25317. // Vertex normal need correction due to X,Y,Z radius scaling
  25318. vertex_normal.x /= radiusX;
  25319. vertex_normal.y /= radiusY;
  25320. vertex_normal.z /= radiusZ;
  25321. vertex_normal.normalize();
  25322. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  25323. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  25324. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  25325. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  25326. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  25327. uvs.push(uv_interp.x, uv_interp.y);
  25328. // push each vertex has member of a face
  25329. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  25330. indices.push(current_indice);
  25331. current_indice++;
  25332. };
  25333. for (var i2 = 0; i2 < subdivisions; i2++) {
  25334. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  25335. // face : (i1,i2) for /\ :
  25336. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  25337. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25338. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25339. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25340. if (i1 + i2 + 1 < subdivisions) {
  25341. // face : (i1,i2)' for \/ :
  25342. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25343. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25344. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25345. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25346. }
  25347. }
  25348. }
  25349. }
  25350. // Sides
  25351. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25352. // Result
  25353. var vertexData = new VertexData();
  25354. vertexData.indices = indices;
  25355. vertexData.positions = positions;
  25356. vertexData.normals = normals;
  25357. vertexData.uvs = uvs;
  25358. return vertexData;
  25359. };
  25360. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  25361. /**
  25362. * Creates the VertexData of the Polyhedron.
  25363. */
  25364. VertexData.CreatePolyhedron = function (options) {
  25365. // provided polyhedron types :
  25366. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  25367. // 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)
  25368. var polyhedra = [];
  25369. 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]] };
  25370. 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]] };
  25371. polyhedra[2] = {
  25372. 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]],
  25373. 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]]
  25374. };
  25375. polyhedra[3] = {
  25376. 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]],
  25377. 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]]
  25378. };
  25379. polyhedra[4] = {
  25380. 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]],
  25381. 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]]
  25382. };
  25383. 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]] };
  25384. 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]] };
  25385. 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]] };
  25386. 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]] };
  25387. 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]] };
  25388. 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]] };
  25389. 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]] };
  25390. 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]] };
  25391. 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]] };
  25392. polyhedra[14] = {
  25393. 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]],
  25394. 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]]
  25395. };
  25396. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  25397. var size = options.size;
  25398. var sizeX = options.sizeX || size || 1;
  25399. var sizeY = options.sizeY || size || 1;
  25400. var sizeZ = options.sizeZ || size || 1;
  25401. var data = options.custom || polyhedra[type];
  25402. var nbfaces = data.face.length;
  25403. var faceUV = options.faceUV || new Array(nbfaces);
  25404. var faceColors = options.faceColors;
  25405. var flat = (options.flat === undefined) ? true : options.flat;
  25406. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25407. var positions = [];
  25408. var indices = [];
  25409. var normals = [];
  25410. var uvs = [];
  25411. var colors = [];
  25412. var index = 0;
  25413. var faceIdx = 0; // face cursor in the array "indexes"
  25414. var indexes = [];
  25415. var i = 0;
  25416. var f = 0;
  25417. var u, v, ang, x, y, tmp;
  25418. // default face colors and UV if undefined
  25419. if (flat) {
  25420. for (f = 0; f < nbfaces; f++) {
  25421. if (faceColors && faceColors[f] === undefined) {
  25422. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25423. }
  25424. if (faceUV && faceUV[f] === undefined) {
  25425. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25426. }
  25427. }
  25428. }
  25429. if (!flat) {
  25430. for (i = 0; i < data.vertex.length; i++) {
  25431. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  25432. uvs.push(0, 0);
  25433. }
  25434. for (f = 0; f < nbfaces; f++) {
  25435. for (i = 0; i < data.face[f].length - 2; i++) {
  25436. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  25437. }
  25438. }
  25439. }
  25440. else {
  25441. for (f = 0; f < nbfaces; f++) {
  25442. var fl = data.face[f].length; // number of vertices of the current face
  25443. ang = 2 * Math.PI / fl;
  25444. x = 0.5 * Math.tan(ang / 2);
  25445. y = 0.5;
  25446. // positions, uvs, colors
  25447. for (i = 0; i < fl; i++) {
  25448. // positions
  25449. 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);
  25450. indexes.push(index);
  25451. index++;
  25452. // uvs
  25453. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  25454. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  25455. uvs.push(u, v);
  25456. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  25457. y = x * Math.sin(ang) + y * Math.cos(ang);
  25458. x = tmp;
  25459. // colors
  25460. if (faceColors) {
  25461. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  25462. }
  25463. }
  25464. // indices from indexes
  25465. for (i = 0; i < fl - 2; i++) {
  25466. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  25467. }
  25468. faceIdx += fl;
  25469. }
  25470. }
  25471. VertexData.ComputeNormals(positions, indices, normals);
  25472. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25473. var vertexData = new VertexData();
  25474. vertexData.positions = positions;
  25475. vertexData.indices = indices;
  25476. vertexData.normals = normals;
  25477. vertexData.uvs = uvs;
  25478. if (faceColors && flat) {
  25479. vertexData.colors = colors;
  25480. }
  25481. return vertexData;
  25482. };
  25483. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  25484. /**
  25485. * Creates the VertexData of the Torus Knot.
  25486. */
  25487. VertexData.CreateTorusKnot = function (options) {
  25488. var indices = [];
  25489. var positions = [];
  25490. var normals = [];
  25491. var uvs = [];
  25492. var radius = options.radius || 2;
  25493. var tube = options.tube || 0.5;
  25494. var radialSegments = options.radialSegments || 32;
  25495. var tubularSegments = options.tubularSegments || 32;
  25496. var p = options.p || 2;
  25497. var q = options.q || 3;
  25498. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25499. // Helper
  25500. var getPos = function (angle) {
  25501. var cu = Math.cos(angle);
  25502. var su = Math.sin(angle);
  25503. var quOverP = q / p * angle;
  25504. var cs = Math.cos(quOverP);
  25505. var tx = radius * (2 + cs) * 0.5 * cu;
  25506. var ty = radius * (2 + cs) * su * 0.5;
  25507. var tz = radius * Math.sin(quOverP) * 0.5;
  25508. return new BABYLON.Vector3(tx, ty, tz);
  25509. };
  25510. // Vertices
  25511. var i;
  25512. var j;
  25513. for (i = 0; i <= radialSegments; i++) {
  25514. var modI = i % radialSegments;
  25515. var u = modI / radialSegments * 2 * p * Math.PI;
  25516. var p1 = getPos(u);
  25517. var p2 = getPos(u + 0.01);
  25518. var tang = p2.subtract(p1);
  25519. var n = p2.add(p1);
  25520. var bitan = BABYLON.Vector3.Cross(tang, n);
  25521. n = BABYLON.Vector3.Cross(bitan, tang);
  25522. bitan.normalize();
  25523. n.normalize();
  25524. for (j = 0; j < tubularSegments; j++) {
  25525. var modJ = j % tubularSegments;
  25526. var v = modJ / tubularSegments * 2 * Math.PI;
  25527. var cx = -tube * Math.cos(v);
  25528. var cy = tube * Math.sin(v);
  25529. positions.push(p1.x + cx * n.x + cy * bitan.x);
  25530. positions.push(p1.y + cx * n.y + cy * bitan.y);
  25531. positions.push(p1.z + cx * n.z + cy * bitan.z);
  25532. uvs.push(i / radialSegments);
  25533. uvs.push(j / tubularSegments);
  25534. }
  25535. }
  25536. for (i = 0; i < radialSegments; i++) {
  25537. for (j = 0; j < tubularSegments; j++) {
  25538. var jNext = (j + 1) % tubularSegments;
  25539. var a = i * tubularSegments + j;
  25540. var b = (i + 1) * tubularSegments + j;
  25541. var c = (i + 1) * tubularSegments + jNext;
  25542. var d = i * tubularSegments + jNext;
  25543. indices.push(d);
  25544. indices.push(b);
  25545. indices.push(a);
  25546. indices.push(d);
  25547. indices.push(c);
  25548. indices.push(b);
  25549. }
  25550. }
  25551. // Normals
  25552. VertexData.ComputeNormals(positions, indices, normals);
  25553. // Sides
  25554. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25555. // Result
  25556. var vertexData = new VertexData();
  25557. vertexData.indices = indices;
  25558. vertexData.positions = positions;
  25559. vertexData.normals = normals;
  25560. vertexData.uvs = uvs;
  25561. return vertexData;
  25562. };
  25563. // Tools
  25564. /**
  25565. * @param {any} - positions (number[] or Float32Array)
  25566. * @param {any} - indices (number[] or Uint16Array)
  25567. * @param {any} - normals (number[] or Float32Array)
  25568. * options (optional) :
  25569. * facetPositions : optional array of facet positions (vector3)
  25570. * facetNormals : optional array of facet normals (vector3)
  25571. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  25572. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  25573. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  25574. * bbSize : optional bounding box size data, required for facetPartitioning computation
  25575. * bInfo : optional bounding info, required for facetPartitioning computation
  25576. */
  25577. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  25578. // temporary scalar variables
  25579. var index = 0; // facet index
  25580. var p1p2x = 0.0; // p1p2 vector x coordinate
  25581. var p1p2y = 0.0; // p1p2 vector y coordinate
  25582. var p1p2z = 0.0; // p1p2 vector z coordinate
  25583. var p3p2x = 0.0; // p3p2 vector x coordinate
  25584. var p3p2y = 0.0; // p3p2 vector y coordinate
  25585. var p3p2z = 0.0; // p3p2 vector z coordinate
  25586. var faceNormalx = 0.0; // facet normal x coordinate
  25587. var faceNormaly = 0.0; // facet normal y coordinate
  25588. var faceNormalz = 0.0; // facet normal z coordinate
  25589. var length = 0.0; // facet normal length before normalization
  25590. var v1x = 0; // vector1 x index in the positions array
  25591. var v1y = 0; // vector1 y index in the positions array
  25592. var v1z = 0; // vector1 z index in the positions array
  25593. var v2x = 0; // vector2 x index in the positions array
  25594. var v2y = 0; // vector2 y index in the positions array
  25595. var v2z = 0; // vector2 z index in the positions array
  25596. var v3x = 0; // vector3 x index in the positions array
  25597. var v3y = 0; // vector3 y index in the positions array
  25598. var v3z = 0; // vector3 z index in the positions array
  25599. var computeFacetNormals = false;
  25600. var computeFacetPositions = false;
  25601. var computeFacetPartitioning = false;
  25602. var faceNormalSign = 1;
  25603. if (options) {
  25604. computeFacetNormals = (options.facetNormals) ? true : false;
  25605. computeFacetPositions = (options.facetPositions) ? true : false;
  25606. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  25607. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  25608. }
  25609. // facetPartitioning reinit if needed
  25610. if (computeFacetPartitioning) {
  25611. var ox = 0; // X partitioning index for facet position
  25612. var oy = 0; // Y partinioning index for facet position
  25613. var oz = 0; // Z partinioning index for facet position
  25614. var b1x = 0; // X partitioning index for facet v1 vertex
  25615. var b1y = 0; // Y partitioning index for facet v1 vertex
  25616. var b1z = 0; // z partitioning index for facet v1 vertex
  25617. var b2x = 0; // X partitioning index for facet v2 vertex
  25618. var b2y = 0; // Y partitioning index for facet v2 vertex
  25619. var b2z = 0; // Z partitioning index for facet v2 vertex
  25620. var b3x = 0; // X partitioning index for facet v3 vertex
  25621. var b3y = 0; // Y partitioning index for facet v3 vertex
  25622. var b3z = 0; // Z partitioning index for facet v3 vertex
  25623. var block_idx_o = 0; // facet barycenter block index
  25624. var block_idx_v1 = 0; // v1 vertex block index
  25625. var block_idx_v2 = 0; // v2 vertex block index
  25626. var block_idx_v3 = 0; // v3 vertex block index
  25627. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  25628. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  25629. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  25630. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  25631. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  25632. var subSq = options.subDiv.max * options.subDiv.max;
  25633. options.facetPartitioning.length = 0;
  25634. }
  25635. // reset the normals
  25636. for (index = 0; index < positions.length; index++) {
  25637. normals[index] = 0.0;
  25638. }
  25639. // Loop : 1 indice triplet = 1 facet
  25640. var nbFaces = indices.length / 3;
  25641. for (index = 0; index < nbFaces; index++) {
  25642. // get the indexes of the coordinates of each vertex of the facet
  25643. v1x = indices[index * 3] * 3;
  25644. v1y = v1x + 1;
  25645. v1z = v1x + 2;
  25646. v2x = indices[index * 3 + 1] * 3;
  25647. v2y = v2x + 1;
  25648. v2z = v2x + 2;
  25649. v3x = indices[index * 3 + 2] * 3;
  25650. v3y = v3x + 1;
  25651. v3z = v3x + 2;
  25652. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  25653. p1p2y = positions[v1y] - positions[v2y];
  25654. p1p2z = positions[v1z] - positions[v2z];
  25655. p3p2x = positions[v3x] - positions[v2x];
  25656. p3p2y = positions[v3y] - positions[v2y];
  25657. p3p2z = positions[v3z] - positions[v2z];
  25658. // compute the face normal with the cross product
  25659. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  25660. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  25661. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  25662. // normalize this normal and store it in the array facetData
  25663. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  25664. length = (length === 0) ? 1.0 : length;
  25665. faceNormalx /= length;
  25666. faceNormaly /= length;
  25667. faceNormalz /= length;
  25668. if (computeFacetNormals) {
  25669. options.facetNormals[index].x = faceNormalx;
  25670. options.facetNormals[index].y = faceNormaly;
  25671. options.facetNormals[index].z = faceNormalz;
  25672. }
  25673. if (computeFacetPositions) {
  25674. // compute and the facet barycenter coordinates in the array facetPositions
  25675. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  25676. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  25677. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  25678. }
  25679. if (computeFacetPartitioning) {
  25680. // store the facet indexes in arrays in the main facetPartitioning array :
  25681. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  25682. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  25683. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  25684. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  25685. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  25686. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  25687. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  25688. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  25689. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  25690. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  25691. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  25692. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  25693. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  25694. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  25695. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  25696. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  25697. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  25698. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  25699. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  25700. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  25701. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  25702. // push each facet index in each block containing the vertex
  25703. options.facetPartitioning[block_idx_v1].push(index);
  25704. if (block_idx_v2 != block_idx_v1) {
  25705. options.facetPartitioning[block_idx_v2].push(index);
  25706. }
  25707. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  25708. options.facetPartitioning[block_idx_v3].push(index);
  25709. }
  25710. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  25711. options.facetPartitioning[block_idx_o].push(index);
  25712. }
  25713. }
  25714. // compute the normals anyway
  25715. normals[v1x] += faceNormalx; // accumulate all the normals per face
  25716. normals[v1y] += faceNormaly;
  25717. normals[v1z] += faceNormalz;
  25718. normals[v2x] += faceNormalx;
  25719. normals[v2y] += faceNormaly;
  25720. normals[v2z] += faceNormalz;
  25721. normals[v3x] += faceNormalx;
  25722. normals[v3y] += faceNormaly;
  25723. normals[v3z] += faceNormalz;
  25724. }
  25725. // last normalization of each normal
  25726. for (index = 0; index < normals.length / 3; index++) {
  25727. faceNormalx = normals[index * 3];
  25728. faceNormaly = normals[index * 3 + 1];
  25729. faceNormalz = normals[index * 3 + 2];
  25730. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  25731. length = (length === 0) ? 1.0 : length;
  25732. faceNormalx /= length;
  25733. faceNormaly /= length;
  25734. faceNormalz /= length;
  25735. normals[index * 3] = faceNormalx;
  25736. normals[index * 3 + 1] = faceNormaly;
  25737. normals[index * 3 + 2] = faceNormalz;
  25738. }
  25739. };
  25740. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  25741. var li = indices.length;
  25742. var ln = normals.length;
  25743. var i;
  25744. var n;
  25745. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25746. switch (sideOrientation) {
  25747. case BABYLON.Mesh.FRONTSIDE:
  25748. // nothing changed
  25749. break;
  25750. case BABYLON.Mesh.BACKSIDE:
  25751. var tmp;
  25752. // indices
  25753. for (i = 0; i < li; i += 3) {
  25754. tmp = indices[i];
  25755. indices[i] = indices[i + 2];
  25756. indices[i + 2] = tmp;
  25757. }
  25758. // normals
  25759. for (n = 0; n < ln; n++) {
  25760. normals[n] = -normals[n];
  25761. }
  25762. break;
  25763. case BABYLON.Mesh.DOUBLESIDE:
  25764. // positions
  25765. var lp = positions.length;
  25766. var l = lp / 3;
  25767. for (var p = 0; p < lp; p++) {
  25768. positions[lp + p] = positions[p];
  25769. }
  25770. // indices
  25771. for (i = 0; i < li; i += 3) {
  25772. indices[i + li] = indices[i + 2] + l;
  25773. indices[i + 1 + li] = indices[i + 1] + l;
  25774. indices[i + 2 + li] = indices[i] + l;
  25775. }
  25776. // normals
  25777. for (n = 0; n < ln; n++) {
  25778. normals[ln + n] = -normals[n];
  25779. }
  25780. // uvs
  25781. var lu = uvs.length;
  25782. for (var u = 0; u < lu; u++) {
  25783. uvs[u + lu] = uvs[u];
  25784. }
  25785. break;
  25786. }
  25787. };
  25788. /**
  25789. * Creates a new VertexData from the imported parameters.
  25790. */
  25791. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  25792. var vertexData = new VertexData();
  25793. // positions
  25794. var positions = parsedVertexData.positions;
  25795. if (positions) {
  25796. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  25797. }
  25798. // normals
  25799. var normals = parsedVertexData.normals;
  25800. if (normals) {
  25801. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  25802. }
  25803. // tangents
  25804. var tangents = parsedVertexData.tangents;
  25805. if (tangents) {
  25806. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  25807. }
  25808. // uvs
  25809. var uvs = parsedVertexData.uvs;
  25810. if (uvs) {
  25811. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  25812. }
  25813. // uv2s
  25814. var uv2s = parsedVertexData.uv2s;
  25815. if (uv2s) {
  25816. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  25817. }
  25818. // uv3s
  25819. var uv3s = parsedVertexData.uv3s;
  25820. if (uv3s) {
  25821. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  25822. }
  25823. // uv4s
  25824. var uv4s = parsedVertexData.uv4s;
  25825. if (uv4s) {
  25826. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  25827. }
  25828. // uv5s
  25829. var uv5s = parsedVertexData.uv5s;
  25830. if (uv5s) {
  25831. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  25832. }
  25833. // uv6s
  25834. var uv6s = parsedVertexData.uv6s;
  25835. if (uv6s) {
  25836. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  25837. }
  25838. // colors
  25839. var colors = parsedVertexData.colors;
  25840. if (colors) {
  25841. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  25842. }
  25843. // matricesIndices
  25844. var matricesIndices = parsedVertexData.matricesIndices;
  25845. if (matricesIndices) {
  25846. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  25847. }
  25848. // matricesWeights
  25849. var matricesWeights = parsedVertexData.matricesWeights;
  25850. if (matricesWeights) {
  25851. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  25852. }
  25853. // indices
  25854. var indices = parsedVertexData.indices;
  25855. if (indices) {
  25856. vertexData.indices = indices;
  25857. }
  25858. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  25859. };
  25860. return VertexData;
  25861. }());
  25862. BABYLON.VertexData = VertexData;
  25863. })(BABYLON || (BABYLON = {}));
  25864. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  25865. var BABYLON;
  25866. (function (BABYLON) {
  25867. var Geometry = (function () {
  25868. function Geometry(id, scene, vertexData, updatable, mesh) {
  25869. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25870. this._totalVertices = 0;
  25871. this._isDisposed = false;
  25872. this.id = id;
  25873. this._engine = scene.getEngine();
  25874. this._meshes = [];
  25875. this._scene = scene;
  25876. //Init vertex buffer cache
  25877. this._vertexBuffers = {};
  25878. this._indices = [];
  25879. // vertexData
  25880. if (vertexData) {
  25881. this.setAllVerticesData(vertexData, updatable);
  25882. }
  25883. else {
  25884. this._totalVertices = 0;
  25885. this._indices = [];
  25886. }
  25887. if (this._engine.getCaps().vertexArrayObject) {
  25888. this._vertexArrayObjects = {};
  25889. }
  25890. // applyToMesh
  25891. if (mesh) {
  25892. if (mesh.getClassName() === "LinesMesh") {
  25893. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  25894. this.updateExtend();
  25895. }
  25896. this.applyToMesh(mesh);
  25897. mesh.computeWorldMatrix(true);
  25898. }
  25899. }
  25900. Object.defineProperty(Geometry.prototype, "boundingBias", {
  25901. /**
  25902. * 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
  25903. * @returns The Bias Vector
  25904. */
  25905. get: function () {
  25906. return this._boundingBias;
  25907. },
  25908. set: function (value) {
  25909. if (this._boundingBias && this._boundingBias.equals(value)) {
  25910. return;
  25911. }
  25912. this._boundingBias = value.clone();
  25913. this.updateBoundingInfo(true, null);
  25914. },
  25915. enumerable: true,
  25916. configurable: true
  25917. });
  25918. Object.defineProperty(Geometry.prototype, "extend", {
  25919. get: function () {
  25920. return this._extend;
  25921. },
  25922. enumerable: true,
  25923. configurable: true
  25924. });
  25925. Geometry.prototype.getScene = function () {
  25926. return this._scene;
  25927. };
  25928. Geometry.prototype.getEngine = function () {
  25929. return this._engine;
  25930. };
  25931. Geometry.prototype.isReady = function () {
  25932. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  25933. };
  25934. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  25935. get: function () {
  25936. for (var index = 0; index < this._meshes.length; index++) {
  25937. if (!this._meshes[index].doNotSerialize) {
  25938. return false;
  25939. }
  25940. }
  25941. return true;
  25942. },
  25943. enumerable: true,
  25944. configurable: true
  25945. });
  25946. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  25947. vertexData.applyToGeometry(this, updatable);
  25948. this.notifyUpdate();
  25949. };
  25950. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25951. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  25952. this.setVerticesBuffer(buffer);
  25953. };
  25954. Geometry.prototype.removeVerticesData = function (kind) {
  25955. if (this._vertexBuffers[kind]) {
  25956. this._vertexBuffers[kind].dispose();
  25957. delete this._vertexBuffers[kind];
  25958. }
  25959. };
  25960. Geometry.prototype.setVerticesBuffer = function (buffer) {
  25961. var kind = buffer.getKind();
  25962. if (this._vertexBuffers[kind]) {
  25963. this._vertexBuffers[kind].dispose();
  25964. }
  25965. this._vertexBuffers[kind] = buffer;
  25966. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25967. var data = buffer.getData();
  25968. var stride = buffer.getStrideSize();
  25969. this._totalVertices = data.length / stride;
  25970. this.updateExtend(data, stride);
  25971. var meshes = this._meshes;
  25972. var numOfMeshes = meshes.length;
  25973. for (var index = 0; index < numOfMeshes; index++) {
  25974. var mesh = meshes[index];
  25975. mesh._resetPointsArrayCache();
  25976. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25977. mesh._createGlobalSubMesh();
  25978. mesh.computeWorldMatrix(true);
  25979. }
  25980. }
  25981. this.notifyUpdate(kind);
  25982. if (this._vertexArrayObjects) {
  25983. this._disposeVertexArrayObjects();
  25984. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  25985. }
  25986. };
  25987. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  25988. var vertexBuffer = this.getVertexBuffer(kind);
  25989. if (!vertexBuffer) {
  25990. return;
  25991. }
  25992. vertexBuffer.updateDirectly(data, offset);
  25993. this.notifyUpdate(kind);
  25994. };
  25995. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  25996. var vertexBuffer = this.getVertexBuffer(kind);
  25997. if (!vertexBuffer) {
  25998. return;
  25999. }
  26000. vertexBuffer.update(data);
  26001. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26002. var stride = vertexBuffer.getStrideSize();
  26003. this._totalVertices = data.length / stride;
  26004. this.updateBoundingInfo(updateExtends, data);
  26005. }
  26006. this.notifyUpdate(kind);
  26007. };
  26008. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  26009. if (updateExtends) {
  26010. this.updateExtend(data);
  26011. }
  26012. var meshes = this._meshes;
  26013. var numOfMeshes = meshes.length;
  26014. for (var index = 0; index < numOfMeshes; index++) {
  26015. var mesh = meshes[index];
  26016. mesh._resetPointsArrayCache();
  26017. if (updateExtends) {
  26018. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26019. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  26020. var subMesh = mesh.subMeshes[subIndex];
  26021. subMesh.refreshBoundingInfo();
  26022. }
  26023. }
  26024. }
  26025. };
  26026. Geometry.prototype._bind = function (effect, indexToBind) {
  26027. if (indexToBind === void 0) { indexToBind = undefined; }
  26028. if (indexToBind === undefined) {
  26029. indexToBind = this._indexBuffer;
  26030. }
  26031. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  26032. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  26033. return;
  26034. }
  26035. // Using VAO
  26036. if (!this._vertexArrayObjects[effect.key]) {
  26037. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  26038. }
  26039. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  26040. };
  26041. Geometry.prototype.getTotalVertices = function () {
  26042. if (!this.isReady()) {
  26043. return 0;
  26044. }
  26045. return this._totalVertices;
  26046. };
  26047. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  26048. var vertexBuffer = this.getVertexBuffer(kind);
  26049. if (!vertexBuffer) {
  26050. return null;
  26051. }
  26052. var orig = vertexBuffer.getData();
  26053. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  26054. return orig;
  26055. }
  26056. else {
  26057. var len = orig.length;
  26058. var copy = [];
  26059. for (var i = 0; i < len; i++) {
  26060. copy.push(orig[i]);
  26061. }
  26062. return copy;
  26063. }
  26064. };
  26065. Geometry.prototype.getVertexBuffer = function (kind) {
  26066. if (!this.isReady()) {
  26067. return null;
  26068. }
  26069. return this._vertexBuffers[kind];
  26070. };
  26071. Geometry.prototype.getVertexBuffers = function () {
  26072. if (!this.isReady()) {
  26073. return null;
  26074. }
  26075. return this._vertexBuffers;
  26076. };
  26077. Geometry.prototype.isVerticesDataPresent = function (kind) {
  26078. if (!this._vertexBuffers) {
  26079. if (this._delayInfo) {
  26080. return this._delayInfo.indexOf(kind) !== -1;
  26081. }
  26082. return false;
  26083. }
  26084. return this._vertexBuffers[kind] !== undefined;
  26085. };
  26086. Geometry.prototype.getVerticesDataKinds = function () {
  26087. var result = [];
  26088. var kind;
  26089. if (!this._vertexBuffers && this._delayInfo) {
  26090. for (kind in this._delayInfo) {
  26091. result.push(kind);
  26092. }
  26093. }
  26094. else {
  26095. for (kind in this._vertexBuffers) {
  26096. result.push(kind);
  26097. }
  26098. }
  26099. return result;
  26100. };
  26101. Geometry.prototype.setIndices = function (indices, totalVertices) {
  26102. if (this._indexBuffer) {
  26103. this._engine._releaseBuffer(this._indexBuffer);
  26104. }
  26105. this._disposeVertexArrayObjects();
  26106. this._indices = indices;
  26107. if (this._meshes.length !== 0 && this._indices) {
  26108. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26109. }
  26110. if (totalVertices !== undefined) {
  26111. this._totalVertices = totalVertices;
  26112. }
  26113. var meshes = this._meshes;
  26114. var numOfMeshes = meshes.length;
  26115. for (var index = 0; index < numOfMeshes; index++) {
  26116. meshes[index]._createGlobalSubMesh();
  26117. }
  26118. this.notifyUpdate();
  26119. };
  26120. Geometry.prototype.getTotalIndices = function () {
  26121. if (!this.isReady()) {
  26122. return 0;
  26123. }
  26124. return this._indices.length;
  26125. };
  26126. Geometry.prototype.getIndices = function (copyWhenShared) {
  26127. if (!this.isReady()) {
  26128. return null;
  26129. }
  26130. var orig = this._indices;
  26131. if (!copyWhenShared || this._meshes.length === 1) {
  26132. return orig;
  26133. }
  26134. else {
  26135. var len = orig.length;
  26136. var copy = [];
  26137. for (var i = 0; i < len; i++) {
  26138. copy.push(orig[i]);
  26139. }
  26140. return copy;
  26141. }
  26142. };
  26143. Geometry.prototype.getIndexBuffer = function () {
  26144. if (!this.isReady()) {
  26145. return null;
  26146. }
  26147. return this._indexBuffer;
  26148. };
  26149. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  26150. if (!effect || !this._vertexArrayObjects) {
  26151. return;
  26152. }
  26153. if (this._vertexArrayObjects[effect.key]) {
  26154. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  26155. delete this._vertexArrayObjects[effect.key];
  26156. }
  26157. };
  26158. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  26159. var meshes = this._meshes;
  26160. var index = meshes.indexOf(mesh);
  26161. if (index === -1) {
  26162. return;
  26163. }
  26164. meshes.splice(index, 1);
  26165. mesh._geometry = null;
  26166. if (meshes.length === 0 && shouldDispose) {
  26167. this.dispose();
  26168. }
  26169. };
  26170. Geometry.prototype.applyToMesh = function (mesh) {
  26171. if (mesh._geometry === this) {
  26172. return;
  26173. }
  26174. var previousGeometry = mesh._geometry;
  26175. if (previousGeometry) {
  26176. previousGeometry.releaseForMesh(mesh);
  26177. }
  26178. var meshes = this._meshes;
  26179. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  26180. mesh._geometry = this;
  26181. this._scene.pushGeometry(this);
  26182. meshes.push(mesh);
  26183. if (this.isReady()) {
  26184. this._applyToMesh(mesh);
  26185. }
  26186. else {
  26187. mesh._boundingInfo = this._boundingInfo;
  26188. }
  26189. };
  26190. Geometry.prototype.updateExtend = function (data, stride) {
  26191. if (data === void 0) { data = null; }
  26192. if (!data) {
  26193. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  26194. }
  26195. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  26196. };
  26197. Geometry.prototype._applyToMesh = function (mesh) {
  26198. var numOfMeshes = this._meshes.length;
  26199. // vertexBuffers
  26200. for (var kind in this._vertexBuffers) {
  26201. if (numOfMeshes === 1) {
  26202. this._vertexBuffers[kind].create();
  26203. }
  26204. var buffer = this._vertexBuffers[kind].getBuffer();
  26205. if (buffer)
  26206. buffer.references = numOfMeshes;
  26207. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26208. mesh._resetPointsArrayCache();
  26209. if (!this._extend) {
  26210. this.updateExtend(this._vertexBuffers[kind].getData());
  26211. }
  26212. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26213. mesh._createGlobalSubMesh();
  26214. //bounding info was just created again, world matrix should be applied again.
  26215. mesh._updateBoundingInfo();
  26216. }
  26217. }
  26218. // indexBuffer
  26219. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  26220. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26221. }
  26222. if (this._indexBuffer) {
  26223. this._indexBuffer.references = numOfMeshes;
  26224. }
  26225. };
  26226. Geometry.prototype.notifyUpdate = function (kind) {
  26227. if (this.onGeometryUpdated) {
  26228. this.onGeometryUpdated(this, kind);
  26229. }
  26230. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  26231. var mesh = _a[_i];
  26232. mesh._markSubMeshesAsAttributesDirty();
  26233. }
  26234. };
  26235. Geometry.prototype.load = function (scene, onLoaded) {
  26236. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26237. return;
  26238. }
  26239. if (this.isReady()) {
  26240. if (onLoaded) {
  26241. onLoaded();
  26242. }
  26243. return;
  26244. }
  26245. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26246. this._queueLoad(scene, onLoaded);
  26247. };
  26248. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  26249. var _this = this;
  26250. scene._addPendingData(this);
  26251. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26252. _this._delayLoadingFunction(JSON.parse(data), _this);
  26253. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26254. _this._delayInfo = [];
  26255. scene._removePendingData(_this);
  26256. var meshes = _this._meshes;
  26257. var numOfMeshes = meshes.length;
  26258. for (var index = 0; index < numOfMeshes; index++) {
  26259. _this._applyToMesh(meshes[index]);
  26260. }
  26261. if (onLoaded) {
  26262. onLoaded();
  26263. }
  26264. }, function () { }, scene.database);
  26265. };
  26266. /**
  26267. * Invert the geometry to move from a right handed system to a left handed one.
  26268. */
  26269. Geometry.prototype.toLeftHanded = function () {
  26270. // Flip faces
  26271. var tIndices = this.getIndices(false);
  26272. if (tIndices != null && tIndices.length > 0) {
  26273. for (var i = 0; i < tIndices.length; i += 3) {
  26274. var tTemp = tIndices[i + 0];
  26275. tIndices[i + 0] = tIndices[i + 2];
  26276. tIndices[i + 2] = tTemp;
  26277. }
  26278. this.setIndices(tIndices);
  26279. }
  26280. // Negate position.z
  26281. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  26282. if (tPositions != null && tPositions.length > 0) {
  26283. for (var i = 0; i < tPositions.length; i += 3) {
  26284. tPositions[i + 2] = -tPositions[i + 2];
  26285. }
  26286. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  26287. }
  26288. // Negate normal.z
  26289. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  26290. if (tNormals != null && tNormals.length > 0) {
  26291. for (var i = 0; i < tNormals.length; i += 3) {
  26292. tNormals[i + 2] = -tNormals[i + 2];
  26293. }
  26294. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  26295. }
  26296. };
  26297. Geometry.prototype.isDisposed = function () {
  26298. return this._isDisposed;
  26299. };
  26300. Geometry.prototype._disposeVertexArrayObjects = function () {
  26301. if (this._vertexArrayObjects) {
  26302. for (var kind in this._vertexArrayObjects) {
  26303. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  26304. }
  26305. this._vertexArrayObjects = {};
  26306. }
  26307. };
  26308. Geometry.prototype.dispose = function () {
  26309. var meshes = this._meshes;
  26310. var numOfMeshes = meshes.length;
  26311. var index;
  26312. for (index = 0; index < numOfMeshes; index++) {
  26313. this.releaseForMesh(meshes[index]);
  26314. }
  26315. this._meshes = [];
  26316. this._disposeVertexArrayObjects();
  26317. for (var kind in this._vertexBuffers) {
  26318. this._vertexBuffers[kind].dispose();
  26319. }
  26320. this._vertexBuffers = {};
  26321. this._totalVertices = 0;
  26322. if (this._indexBuffer) {
  26323. this._engine._releaseBuffer(this._indexBuffer);
  26324. }
  26325. this._indexBuffer = null;
  26326. this._indices = [];
  26327. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26328. this.delayLoadingFile = null;
  26329. this._delayLoadingFunction = null;
  26330. this._delayInfo = [];
  26331. this._boundingInfo = null;
  26332. this._scene.removeGeometry(this);
  26333. this._isDisposed = true;
  26334. };
  26335. Geometry.prototype.copy = function (id) {
  26336. var vertexData = new BABYLON.VertexData();
  26337. vertexData.indices = [];
  26338. var indices = this.getIndices();
  26339. for (var index = 0; index < indices.length; index++) {
  26340. vertexData.indices.push(indices[index]);
  26341. }
  26342. var updatable = false;
  26343. var stopChecking = false;
  26344. var kind;
  26345. for (kind in this._vertexBuffers) {
  26346. // using slice() to make a copy of the array and not just reference it
  26347. var data = this.getVerticesData(kind);
  26348. if (data instanceof Float32Array) {
  26349. vertexData.set(new Float32Array(data), kind);
  26350. }
  26351. else {
  26352. vertexData.set(data.slice(0), kind);
  26353. }
  26354. if (!stopChecking) {
  26355. updatable = this.getVertexBuffer(kind).isUpdatable();
  26356. stopChecking = !updatable;
  26357. }
  26358. }
  26359. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  26360. geometry.delayLoadState = this.delayLoadState;
  26361. geometry.delayLoadingFile = this.delayLoadingFile;
  26362. geometry._delayLoadingFunction = this._delayLoadingFunction;
  26363. for (kind in this._delayInfo) {
  26364. geometry._delayInfo = geometry._delayInfo || [];
  26365. geometry._delayInfo.push(kind);
  26366. }
  26367. // Bounding info
  26368. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26369. return geometry;
  26370. };
  26371. Geometry.prototype.serialize = function () {
  26372. var serializationObject = {};
  26373. serializationObject.id = this.id;
  26374. if (BABYLON.Tags.HasTags(this)) {
  26375. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26376. }
  26377. return serializationObject;
  26378. };
  26379. Geometry.prototype.serializeVerticeData = function () {
  26380. var serializationObject = this.serialize();
  26381. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26382. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26383. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  26384. serializationObject.positions._updatable = true;
  26385. }
  26386. }
  26387. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26388. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26389. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  26390. serializationObject.normals._updatable = true;
  26391. }
  26392. }
  26393. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26394. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26395. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  26396. serializationObject.uvs._updatable = true;
  26397. }
  26398. }
  26399. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26400. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  26401. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  26402. serializationObject.uv2s._updatable = true;
  26403. }
  26404. }
  26405. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26406. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  26407. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  26408. serializationObject.uv3s._updatable = true;
  26409. }
  26410. }
  26411. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26412. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  26413. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  26414. serializationObject.uv4s._updatable = true;
  26415. }
  26416. }
  26417. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26418. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  26419. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  26420. serializationObject.uv5s._updatable = true;
  26421. }
  26422. }
  26423. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26424. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  26425. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  26426. serializationObject.uv6s._updatable = true;
  26427. }
  26428. }
  26429. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26430. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  26431. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  26432. serializationObject.colors._updatable = true;
  26433. }
  26434. }
  26435. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26436. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26437. serializationObject.matricesIndices._isExpanded = true;
  26438. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  26439. serializationObject.matricesIndices._updatable = true;
  26440. }
  26441. }
  26442. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26443. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26444. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  26445. serializationObject.matricesWeights._updatable = true;
  26446. }
  26447. }
  26448. serializationObject.indices = this.getIndices();
  26449. return serializationObject;
  26450. };
  26451. // Statics
  26452. Geometry.ExtractFromMesh = function (mesh, id) {
  26453. var geometry = mesh._geometry;
  26454. if (!geometry) {
  26455. return null;
  26456. }
  26457. return geometry.copy(id);
  26458. };
  26459. /**
  26460. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  26461. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  26462. * Be aware Math.random() could cause collisions, but:
  26463. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  26464. */
  26465. Geometry.RandomId = function () {
  26466. return BABYLON.Tools.RandomId();
  26467. };
  26468. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  26469. var scene = mesh.getScene();
  26470. // Geometry
  26471. var geometryId = parsedGeometry.geometryId;
  26472. if (geometryId) {
  26473. var geometry = scene.getGeometryByID(geometryId);
  26474. if (geometry) {
  26475. geometry.applyToMesh(mesh);
  26476. }
  26477. }
  26478. else if (parsedGeometry instanceof ArrayBuffer) {
  26479. var binaryInfo = mesh._binaryInfo;
  26480. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  26481. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  26482. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  26483. }
  26484. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  26485. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  26486. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  26487. }
  26488. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  26489. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  26490. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  26491. }
  26492. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  26493. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  26494. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  26495. }
  26496. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  26497. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  26498. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  26499. }
  26500. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  26501. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  26502. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  26503. }
  26504. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  26505. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  26506. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  26507. }
  26508. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  26509. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  26510. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  26511. }
  26512. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  26513. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  26514. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  26515. }
  26516. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  26517. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  26518. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  26519. }
  26520. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  26521. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  26522. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  26523. }
  26524. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  26525. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  26526. mesh.setIndices(indicesData);
  26527. }
  26528. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  26529. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  26530. mesh.subMeshes = [];
  26531. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  26532. var materialIndex = subMeshesData[(i * 5) + 0];
  26533. var verticesStart = subMeshesData[(i * 5) + 1];
  26534. var verticesCount = subMeshesData[(i * 5) + 2];
  26535. var indexStart = subMeshesData[(i * 5) + 3];
  26536. var indexCount = subMeshesData[(i * 5) + 4];
  26537. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  26538. }
  26539. }
  26540. }
  26541. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  26542. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  26543. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  26544. if (parsedGeometry.uvs) {
  26545. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  26546. }
  26547. if (parsedGeometry.uvs2) {
  26548. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  26549. }
  26550. if (parsedGeometry.uvs3) {
  26551. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  26552. }
  26553. if (parsedGeometry.uvs4) {
  26554. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  26555. }
  26556. if (parsedGeometry.uvs5) {
  26557. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  26558. }
  26559. if (parsedGeometry.uvs6) {
  26560. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  26561. }
  26562. if (parsedGeometry.colors) {
  26563. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  26564. }
  26565. if (parsedGeometry.matricesIndices) {
  26566. if (!parsedGeometry.matricesIndices._isExpanded) {
  26567. var floatIndices = [];
  26568. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  26569. var matricesIndex = parsedGeometry.matricesIndices[i];
  26570. floatIndices.push(matricesIndex & 0x000000FF);
  26571. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26572. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26573. floatIndices.push(matricesIndex >> 24);
  26574. }
  26575. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  26576. }
  26577. else {
  26578. delete parsedGeometry.matricesIndices._isExpanded;
  26579. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  26580. }
  26581. }
  26582. if (parsedGeometry.matricesIndicesExtra) {
  26583. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  26584. var floatIndices = [];
  26585. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  26586. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  26587. floatIndices.push(matricesIndex & 0x000000FF);
  26588. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26589. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26590. floatIndices.push(matricesIndex >> 24);
  26591. }
  26592. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  26593. }
  26594. else {
  26595. delete parsedGeometry.matricesIndices._isExpanded;
  26596. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  26597. }
  26598. }
  26599. if (parsedGeometry.matricesWeights) {
  26600. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  26601. }
  26602. if (parsedGeometry.matricesWeightsExtra) {
  26603. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  26604. }
  26605. mesh.setIndices(parsedGeometry.indices);
  26606. }
  26607. // SubMeshes
  26608. if (parsedGeometry.subMeshes) {
  26609. mesh.subMeshes = [];
  26610. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  26611. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  26612. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  26613. }
  26614. }
  26615. // Flat shading
  26616. if (mesh._shouldGenerateFlatShading) {
  26617. mesh.convertToFlatShadedMesh();
  26618. delete mesh._shouldGenerateFlatShading;
  26619. }
  26620. // Update
  26621. mesh.computeWorldMatrix(true);
  26622. // Octree
  26623. if (scene['_selectionOctree']) {
  26624. scene['_selectionOctree'].addMesh(mesh);
  26625. }
  26626. };
  26627. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  26628. if (scene.getGeometryByID(parsedVertexData.id)) {
  26629. return null; // null since geometry could be something else than a box...
  26630. }
  26631. var geometry = new Geometry(parsedVertexData.id, scene);
  26632. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  26633. if (parsedVertexData.delayLoadingFile) {
  26634. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26635. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  26636. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  26637. geometry._delayInfo = [];
  26638. if (parsedVertexData.hasUVs) {
  26639. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  26640. }
  26641. if (parsedVertexData.hasUVs2) {
  26642. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  26643. }
  26644. if (parsedVertexData.hasUVs3) {
  26645. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  26646. }
  26647. if (parsedVertexData.hasUVs4) {
  26648. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  26649. }
  26650. if (parsedVertexData.hasUVs5) {
  26651. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  26652. }
  26653. if (parsedVertexData.hasUVs6) {
  26654. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  26655. }
  26656. if (parsedVertexData.hasColors) {
  26657. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  26658. }
  26659. if (parsedVertexData.hasMatricesIndices) {
  26660. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26661. }
  26662. if (parsedVertexData.hasMatricesWeights) {
  26663. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26664. }
  26665. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  26666. }
  26667. else {
  26668. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  26669. }
  26670. scene.pushGeometry(geometry, true);
  26671. return geometry;
  26672. };
  26673. return Geometry;
  26674. }());
  26675. BABYLON.Geometry = Geometry;
  26676. /////// Primitives //////////////////////////////////////////////
  26677. (function (Geometry) {
  26678. var Primitives;
  26679. (function (Primitives) {
  26680. /// Abstract class
  26681. var _Primitive = (function (_super) {
  26682. __extends(_Primitive, _super);
  26683. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  26684. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  26685. _this._canBeRegenerated = _canBeRegenerated;
  26686. _this._beingRegenerated = true;
  26687. _this.regenerate();
  26688. _this._beingRegenerated = false;
  26689. return _this;
  26690. }
  26691. _Primitive.prototype.canBeRegenerated = function () {
  26692. return this._canBeRegenerated;
  26693. };
  26694. _Primitive.prototype.regenerate = function () {
  26695. if (!this._canBeRegenerated) {
  26696. return;
  26697. }
  26698. this._beingRegenerated = true;
  26699. this.setAllVerticesData(this._regenerateVertexData(), false);
  26700. this._beingRegenerated = false;
  26701. };
  26702. _Primitive.prototype.asNewGeometry = function (id) {
  26703. return _super.prototype.copy.call(this, id);
  26704. };
  26705. // overrides
  26706. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  26707. if (!this._beingRegenerated) {
  26708. return;
  26709. }
  26710. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  26711. };
  26712. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  26713. if (!this._beingRegenerated) {
  26714. return;
  26715. }
  26716. _super.prototype.setVerticesData.call(this, kind, data, false);
  26717. };
  26718. // to override
  26719. // protected
  26720. _Primitive.prototype._regenerateVertexData = function () {
  26721. throw new Error("Abstract method");
  26722. };
  26723. _Primitive.prototype.copy = function (id) {
  26724. throw new Error("Must be overriden in sub-classes.");
  26725. };
  26726. _Primitive.prototype.serialize = function () {
  26727. var serializationObject = _super.prototype.serialize.call(this);
  26728. serializationObject.canBeRegenerated = this.canBeRegenerated();
  26729. return serializationObject;
  26730. };
  26731. return _Primitive;
  26732. }(Geometry));
  26733. Primitives._Primitive = _Primitive;
  26734. var Ribbon = (function (_super) {
  26735. __extends(Ribbon, _super);
  26736. // Members
  26737. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  26738. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26739. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26740. _this.pathArray = pathArray;
  26741. _this.closeArray = closeArray;
  26742. _this.closePath = closePath;
  26743. _this.offset = offset;
  26744. _this.side = side;
  26745. return _this;
  26746. }
  26747. Ribbon.prototype._regenerateVertexData = function () {
  26748. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  26749. };
  26750. Ribbon.prototype.copy = function (id) {
  26751. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  26752. };
  26753. return Ribbon;
  26754. }(_Primitive));
  26755. Primitives.Ribbon = Ribbon;
  26756. var Box = (function (_super) {
  26757. __extends(Box, _super);
  26758. // Members
  26759. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  26760. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26761. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26762. _this.size = size;
  26763. _this.side = side;
  26764. return _this;
  26765. }
  26766. Box.prototype._regenerateVertexData = function () {
  26767. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  26768. };
  26769. Box.prototype.copy = function (id) {
  26770. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26771. };
  26772. Box.prototype.serialize = function () {
  26773. var serializationObject = _super.prototype.serialize.call(this);
  26774. serializationObject.size = this.size;
  26775. return serializationObject;
  26776. };
  26777. Box.Parse = function (parsedBox, scene) {
  26778. if (scene.getGeometryByID(parsedBox.id)) {
  26779. return null; // null since geometry could be something else than a box...
  26780. }
  26781. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  26782. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  26783. scene.pushGeometry(box, true);
  26784. return box;
  26785. };
  26786. return Box;
  26787. }(_Primitive));
  26788. Primitives.Box = Box;
  26789. var Sphere = (function (_super) {
  26790. __extends(Sphere, _super);
  26791. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  26792. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26793. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26794. _this.segments = segments;
  26795. _this.diameter = diameter;
  26796. _this.side = side;
  26797. return _this;
  26798. }
  26799. Sphere.prototype._regenerateVertexData = function () {
  26800. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  26801. };
  26802. Sphere.prototype.copy = function (id) {
  26803. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  26804. };
  26805. Sphere.prototype.serialize = function () {
  26806. var serializationObject = _super.prototype.serialize.call(this);
  26807. serializationObject.segments = this.segments;
  26808. serializationObject.diameter = this.diameter;
  26809. return serializationObject;
  26810. };
  26811. Sphere.Parse = function (parsedSphere, scene) {
  26812. if (scene.getGeometryByID(parsedSphere.id)) {
  26813. return null; // null since geometry could be something else than a sphere...
  26814. }
  26815. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  26816. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  26817. scene.pushGeometry(sphere, true);
  26818. return sphere;
  26819. };
  26820. return Sphere;
  26821. }(_Primitive));
  26822. Primitives.Sphere = Sphere;
  26823. var Disc = (function (_super) {
  26824. __extends(Disc, _super);
  26825. // Members
  26826. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  26827. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26828. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26829. _this.radius = radius;
  26830. _this.tessellation = tessellation;
  26831. _this.side = side;
  26832. return _this;
  26833. }
  26834. Disc.prototype._regenerateVertexData = function () {
  26835. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  26836. };
  26837. Disc.prototype.copy = function (id) {
  26838. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  26839. };
  26840. return Disc;
  26841. }(_Primitive));
  26842. Primitives.Disc = Disc;
  26843. var Cylinder = (function (_super) {
  26844. __extends(Cylinder, _super);
  26845. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  26846. if (subdivisions === void 0) { subdivisions = 1; }
  26847. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26848. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26849. _this.height = height;
  26850. _this.diameterTop = diameterTop;
  26851. _this.diameterBottom = diameterBottom;
  26852. _this.tessellation = tessellation;
  26853. _this.subdivisions = subdivisions;
  26854. _this.side = side;
  26855. return _this;
  26856. }
  26857. Cylinder.prototype._regenerateVertexData = function () {
  26858. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  26859. };
  26860. Cylinder.prototype.copy = function (id) {
  26861. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  26862. };
  26863. Cylinder.prototype.serialize = function () {
  26864. var serializationObject = _super.prototype.serialize.call(this);
  26865. serializationObject.height = this.height;
  26866. serializationObject.diameterTop = this.diameterTop;
  26867. serializationObject.diameterBottom = this.diameterBottom;
  26868. serializationObject.tessellation = this.tessellation;
  26869. return serializationObject;
  26870. };
  26871. Cylinder.Parse = function (parsedCylinder, scene) {
  26872. if (scene.getGeometryByID(parsedCylinder.id)) {
  26873. return null; // null since geometry could be something else than a cylinder...
  26874. }
  26875. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  26876. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  26877. scene.pushGeometry(cylinder, true);
  26878. return cylinder;
  26879. };
  26880. return Cylinder;
  26881. }(_Primitive));
  26882. Primitives.Cylinder = Cylinder;
  26883. var Torus = (function (_super) {
  26884. __extends(Torus, _super);
  26885. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  26886. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26887. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26888. _this.diameter = diameter;
  26889. _this.thickness = thickness;
  26890. _this.tessellation = tessellation;
  26891. _this.side = side;
  26892. return _this;
  26893. }
  26894. Torus.prototype._regenerateVertexData = function () {
  26895. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  26896. };
  26897. Torus.prototype.copy = function (id) {
  26898. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  26899. };
  26900. Torus.prototype.serialize = function () {
  26901. var serializationObject = _super.prototype.serialize.call(this);
  26902. serializationObject.diameter = this.diameter;
  26903. serializationObject.thickness = this.thickness;
  26904. serializationObject.tessellation = this.tessellation;
  26905. return serializationObject;
  26906. };
  26907. Torus.Parse = function (parsedTorus, scene) {
  26908. if (scene.getGeometryByID(parsedTorus.id)) {
  26909. return null; // null since geometry could be something else than a torus...
  26910. }
  26911. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  26912. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  26913. scene.pushGeometry(torus, true);
  26914. return torus;
  26915. };
  26916. return Torus;
  26917. }(_Primitive));
  26918. Primitives.Torus = Torus;
  26919. var Ground = (function (_super) {
  26920. __extends(Ground, _super);
  26921. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  26922. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26923. _this.width = width;
  26924. _this.height = height;
  26925. _this.subdivisions = subdivisions;
  26926. return _this;
  26927. }
  26928. Ground.prototype._regenerateVertexData = function () {
  26929. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  26930. };
  26931. Ground.prototype.copy = function (id) {
  26932. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  26933. };
  26934. Ground.prototype.serialize = function () {
  26935. var serializationObject = _super.prototype.serialize.call(this);
  26936. serializationObject.width = this.width;
  26937. serializationObject.height = this.height;
  26938. serializationObject.subdivisions = this.subdivisions;
  26939. return serializationObject;
  26940. };
  26941. Ground.Parse = function (parsedGround, scene) {
  26942. if (scene.getGeometryByID(parsedGround.id)) {
  26943. return null; // null since geometry could be something else than a ground...
  26944. }
  26945. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  26946. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  26947. scene.pushGeometry(ground, true);
  26948. return ground;
  26949. };
  26950. return Ground;
  26951. }(_Primitive));
  26952. Primitives.Ground = Ground;
  26953. var TiledGround = (function (_super) {
  26954. __extends(TiledGround, _super);
  26955. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  26956. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26957. _this.xmin = xmin;
  26958. _this.zmin = zmin;
  26959. _this.xmax = xmax;
  26960. _this.zmax = zmax;
  26961. _this.subdivisions = subdivisions;
  26962. _this.precision = precision;
  26963. return _this;
  26964. }
  26965. TiledGround.prototype._regenerateVertexData = function () {
  26966. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  26967. };
  26968. TiledGround.prototype.copy = function (id) {
  26969. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  26970. };
  26971. return TiledGround;
  26972. }(_Primitive));
  26973. Primitives.TiledGround = TiledGround;
  26974. var Plane = (function (_super) {
  26975. __extends(Plane, _super);
  26976. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  26977. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26978. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26979. _this.size = size;
  26980. _this.side = side;
  26981. return _this;
  26982. }
  26983. Plane.prototype._regenerateVertexData = function () {
  26984. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  26985. };
  26986. Plane.prototype.copy = function (id) {
  26987. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26988. };
  26989. Plane.prototype.serialize = function () {
  26990. var serializationObject = _super.prototype.serialize.call(this);
  26991. serializationObject.size = this.size;
  26992. return serializationObject;
  26993. };
  26994. Plane.Parse = function (parsedPlane, scene) {
  26995. if (scene.getGeometryByID(parsedPlane.id)) {
  26996. return null; // null since geometry could be something else than a ground...
  26997. }
  26998. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  26999. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  27000. scene.pushGeometry(plane, true);
  27001. return plane;
  27002. };
  27003. return Plane;
  27004. }(_Primitive));
  27005. Primitives.Plane = Plane;
  27006. var TorusKnot = (function (_super) {
  27007. __extends(TorusKnot, _super);
  27008. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  27009. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27010. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  27011. _this.radius = radius;
  27012. _this.tube = tube;
  27013. _this.radialSegments = radialSegments;
  27014. _this.tubularSegments = tubularSegments;
  27015. _this.p = p;
  27016. _this.q = q;
  27017. _this.side = side;
  27018. return _this;
  27019. }
  27020. TorusKnot.prototype._regenerateVertexData = function () {
  27021. 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 });
  27022. };
  27023. TorusKnot.prototype.copy = function (id) {
  27024. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  27025. };
  27026. TorusKnot.prototype.serialize = function () {
  27027. var serializationObject = _super.prototype.serialize.call(this);
  27028. serializationObject.radius = this.radius;
  27029. serializationObject.tube = this.tube;
  27030. serializationObject.radialSegments = this.radialSegments;
  27031. serializationObject.tubularSegments = this.tubularSegments;
  27032. serializationObject.p = this.p;
  27033. serializationObject.q = this.q;
  27034. return serializationObject;
  27035. };
  27036. ;
  27037. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  27038. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  27039. return null; // null since geometry could be something else than a ground...
  27040. }
  27041. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  27042. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  27043. scene.pushGeometry(torusKnot, true);
  27044. return torusKnot;
  27045. };
  27046. return TorusKnot;
  27047. }(_Primitive));
  27048. Primitives.TorusKnot = TorusKnot;
  27049. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  27050. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  27051. })(BABYLON || (BABYLON = {}));
  27052. //# sourceMappingURL=babylon.geometry.js.map
  27053. var BABYLON;
  27054. (function (BABYLON) {
  27055. var PostProcessManager = (function () {
  27056. function PostProcessManager(scene) {
  27057. this._vertexBuffers = {};
  27058. this._scene = scene;
  27059. }
  27060. PostProcessManager.prototype._prepareBuffers = function () {
  27061. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  27062. return;
  27063. }
  27064. // VBO
  27065. var vertices = [];
  27066. vertices.push(1, 1);
  27067. vertices.push(-1, 1);
  27068. vertices.push(-1, -1);
  27069. vertices.push(1, -1);
  27070. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  27071. // Indices
  27072. var indices = [];
  27073. indices.push(0);
  27074. indices.push(1);
  27075. indices.push(2);
  27076. indices.push(0);
  27077. indices.push(2);
  27078. indices.push(3);
  27079. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  27080. };
  27081. // Methods
  27082. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  27083. var postProcesses = this._scene.activeCamera._postProcesses;
  27084. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  27085. return false;
  27086. }
  27087. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  27088. return true;
  27089. };
  27090. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  27091. var engine = this._scene.getEngine();
  27092. for (var index = 0; index < postProcesses.length; index++) {
  27093. if (index < postProcesses.length - 1) {
  27094. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  27095. }
  27096. else {
  27097. if (targetTexture) {
  27098. engine.bindFramebuffer(targetTexture);
  27099. }
  27100. else {
  27101. engine.restoreDefaultFramebuffer();
  27102. }
  27103. }
  27104. var pp = postProcesses[index];
  27105. var effect = pp.apply();
  27106. if (effect) {
  27107. pp.onBeforeRenderObservable.notifyObservers(effect);
  27108. // VBOs
  27109. this._prepareBuffers();
  27110. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27111. // Draw order
  27112. engine.draw(true, 0, 6);
  27113. pp.onAfterRenderObservable.notifyObservers(effect);
  27114. }
  27115. }
  27116. // Restore depth buffer
  27117. engine.setDepthBuffer(true);
  27118. engine.setDepthWrite(true);
  27119. };
  27120. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  27121. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  27122. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  27123. return;
  27124. }
  27125. var engine = this._scene.getEngine();
  27126. for (var index = 0, len = postProcesses.length; index < len; index++) {
  27127. if (index < len - 1) {
  27128. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  27129. }
  27130. else {
  27131. if (targetTexture) {
  27132. engine.bindFramebuffer(targetTexture, faceIndex);
  27133. }
  27134. else {
  27135. engine.restoreDefaultFramebuffer();
  27136. }
  27137. }
  27138. if (doNotPresent) {
  27139. break;
  27140. }
  27141. var pp = postProcesses[index];
  27142. var effect = pp.apply();
  27143. if (effect) {
  27144. pp.onBeforeRenderObservable.notifyObservers(effect);
  27145. // VBOs
  27146. this._prepareBuffers();
  27147. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27148. // Draw order
  27149. engine.draw(true, 0, 6);
  27150. pp.onAfterRenderObservable.notifyObservers(effect);
  27151. }
  27152. }
  27153. // Restore depth buffer
  27154. engine.setDepthBuffer(true);
  27155. engine.setDepthWrite(true);
  27156. };
  27157. PostProcessManager.prototype.dispose = function () {
  27158. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  27159. if (buffer) {
  27160. buffer.dispose();
  27161. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  27162. }
  27163. if (this._indexBuffer) {
  27164. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27165. this._indexBuffer = null;
  27166. }
  27167. };
  27168. return PostProcessManager;
  27169. }());
  27170. BABYLON.PostProcessManager = PostProcessManager;
  27171. })(BABYLON || (BABYLON = {}));
  27172. //# sourceMappingURL=babylon.postProcessManager.js.map
  27173. var BABYLON;
  27174. (function (BABYLON) {
  27175. var StandardMaterialDefines = (function (_super) {
  27176. __extends(StandardMaterialDefines, _super);
  27177. function StandardMaterialDefines() {
  27178. var _this = _super.call(this) || this;
  27179. _this.DIFFUSE = false;
  27180. _this.AMBIENT = false;
  27181. _this.OPACITY = false;
  27182. _this.OPACITYRGB = false;
  27183. _this.REFLECTION = false;
  27184. _this.EMISSIVE = false;
  27185. _this.SPECULAR = false;
  27186. _this.BUMP = false;
  27187. _this.PARALLAX = false;
  27188. _this.PARALLAXOCCLUSION = false;
  27189. _this.SPECULAROVERALPHA = false;
  27190. _this.CLIPPLANE = false;
  27191. _this.ALPHATEST = false;
  27192. _this.ALPHAFROMDIFFUSE = false;
  27193. _this.POINTSIZE = false;
  27194. _this.FOG = false;
  27195. _this.SPECULARTERM = false;
  27196. _this.DIFFUSEFRESNEL = false;
  27197. _this.OPACITYFRESNEL = false;
  27198. _this.REFLECTIONFRESNEL = false;
  27199. _this.REFRACTIONFRESNEL = false;
  27200. _this.EMISSIVEFRESNEL = false;
  27201. _this.FRESNEL = false;
  27202. _this.NORMAL = false;
  27203. _this.UV1 = false;
  27204. _this.UV2 = false;
  27205. _this.VERTEXCOLOR = false;
  27206. _this.VERTEXALPHA = false;
  27207. _this.NUM_BONE_INFLUENCERS = 0;
  27208. _this.BonesPerMesh = 0;
  27209. _this.INSTANCES = false;
  27210. _this.GLOSSINESS = false;
  27211. _this.ROUGHNESS = false;
  27212. _this.EMISSIVEASILLUMINATION = false;
  27213. _this.LINKEMISSIVEWITHDIFFUSE = false;
  27214. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  27215. _this.LIGHTMAP = false;
  27216. _this.USELIGHTMAPASSHADOWMAP = false;
  27217. _this.REFLECTIONMAP_3D = false;
  27218. _this.REFLECTIONMAP_SPHERICAL = false;
  27219. _this.REFLECTIONMAP_PLANAR = false;
  27220. _this.REFLECTIONMAP_CUBIC = false;
  27221. _this.REFLECTIONMAP_PROJECTION = false;
  27222. _this.REFLECTIONMAP_SKYBOX = false;
  27223. _this.REFLECTIONMAP_EXPLICIT = false;
  27224. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  27225. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  27226. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  27227. _this.INVERTCUBICMAP = false;
  27228. _this.LOGARITHMICDEPTH = false;
  27229. _this.REFRACTION = false;
  27230. _this.REFRACTIONMAP_3D = false;
  27231. _this.REFLECTIONOVERALPHA = false;
  27232. _this.INVERTNORMALMAPX = false;
  27233. _this.INVERTNORMALMAPY = false;
  27234. _this.TWOSIDEDLIGHTING = false;
  27235. _this.SHADOWFULLFLOAT = false;
  27236. _this.CAMERACOLORGRADING = false;
  27237. _this.CAMERACOLORCURVES = false;
  27238. _this.MORPHTARGETS = false;
  27239. _this.MORPHTARGETS_NORMAL = false;
  27240. _this.MORPHTARGETS_TANGENT = false;
  27241. _this.NUM_MORPH_INFLUENCERS = 0;
  27242. _this.rebuild();
  27243. return _this;
  27244. }
  27245. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  27246. var modes = [
  27247. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  27248. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  27249. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  27250. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  27251. ];
  27252. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  27253. var mode = modes_1[_i];
  27254. this[mode] = (mode === modeToEnable);
  27255. }
  27256. };
  27257. return StandardMaterialDefines;
  27258. }(BABYLON.MaterialDefines));
  27259. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  27260. var StandardMaterial = (function (_super) {
  27261. __extends(StandardMaterial, _super);
  27262. function StandardMaterial(name, scene) {
  27263. var _this = _super.call(this, name, scene) || this;
  27264. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  27265. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  27266. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  27267. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  27268. _this.specularPower = 64;
  27269. _this._useAlphaFromDiffuseTexture = false;
  27270. _this._useEmissiveAsIllumination = false;
  27271. _this._linkEmissiveWithDiffuse = false;
  27272. _this._useSpecularOverAlpha = false;
  27273. _this._useReflectionOverAlpha = false;
  27274. _this._disableLighting = false;
  27275. _this._useParallax = false;
  27276. _this._useParallaxOcclusion = false;
  27277. _this.parallaxScaleBias = 0.05;
  27278. _this._roughness = 0;
  27279. _this.indexOfRefraction = 0.98;
  27280. _this.invertRefractionY = true;
  27281. _this._useLightmapAsShadowmap = false;
  27282. _this._useReflectionFresnelFromSpecular = false;
  27283. _this._useGlossinessFromSpecularMapAlpha = false;
  27284. _this._maxSimultaneousLights = 4;
  27285. /**
  27286. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  27287. */
  27288. _this._invertNormalMapX = false;
  27289. /**
  27290. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  27291. */
  27292. _this._invertNormalMapY = false;
  27293. /**
  27294. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  27295. */
  27296. _this._twoSidedLighting = false;
  27297. /**
  27298. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  27299. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  27300. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  27301. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  27302. */
  27303. _this._cameraColorCurves = null;
  27304. _this._renderTargets = new BABYLON.SmartArray(16);
  27305. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  27306. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  27307. _this.getRenderTargetTextures = function () {
  27308. _this._renderTargets.reset();
  27309. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  27310. _this._renderTargets.push(_this._reflectionTexture);
  27311. }
  27312. if (_this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  27313. _this._renderTargets.push(_this._refractionTexture);
  27314. }
  27315. return _this._renderTargets;
  27316. };
  27317. return _this;
  27318. }
  27319. StandardMaterial.prototype.getClassName = function () {
  27320. return "StandardMaterial";
  27321. };
  27322. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  27323. get: function () {
  27324. return this._useLogarithmicDepth;
  27325. },
  27326. set: function (value) {
  27327. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  27328. this._markAllSubMeshesAsMiscDirty();
  27329. },
  27330. enumerable: true,
  27331. configurable: true
  27332. });
  27333. StandardMaterial.prototype.needAlphaBlending = function () {
  27334. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  27335. };
  27336. StandardMaterial.prototype.needAlphaTesting = function () {
  27337. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  27338. };
  27339. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  27340. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  27341. };
  27342. StandardMaterial.prototype.getAlphaTestTexture = function () {
  27343. return this._diffuseTexture;
  27344. };
  27345. /**
  27346. * Child classes can use it to update shaders
  27347. */
  27348. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  27349. if (this.isFrozen) {
  27350. if (this._wasPreviouslyReady && subMesh.effect) {
  27351. return true;
  27352. }
  27353. }
  27354. if (!subMesh._materialDefines) {
  27355. subMesh._materialDefines = new StandardMaterialDefines();
  27356. }
  27357. var scene = this.getScene();
  27358. var defines = subMesh._materialDefines;
  27359. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  27360. if (defines._renderId === scene.getRenderId()) {
  27361. return true;
  27362. }
  27363. }
  27364. var engine = scene.getEngine();
  27365. // Lights
  27366. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  27367. // Textures
  27368. if (defines._areTexturesDirty) {
  27369. defines._needUVs = false;
  27370. if (scene.texturesEnabled) {
  27371. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  27372. if (!this._diffuseTexture.isReady()) {
  27373. return false;
  27374. }
  27375. else {
  27376. defines._needUVs = true;
  27377. defines.DIFFUSE = true;
  27378. }
  27379. }
  27380. else {
  27381. defines.DIFFUSE = false;
  27382. }
  27383. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  27384. if (!this._ambientTexture.isReady()) {
  27385. return false;
  27386. }
  27387. else {
  27388. defines._needUVs = true;
  27389. defines.AMBIENT = true;
  27390. }
  27391. }
  27392. else {
  27393. defines.AMBIENT = false;
  27394. }
  27395. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  27396. if (!this._opacityTexture.isReady()) {
  27397. return false;
  27398. }
  27399. else {
  27400. defines._needUVs = true;
  27401. defines.OPACITY = true;
  27402. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  27403. }
  27404. }
  27405. else {
  27406. defines.OPACITY = false;
  27407. }
  27408. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  27409. if (!this._reflectionTexture.isReady()) {
  27410. return false;
  27411. }
  27412. else {
  27413. defines._needNormals = true;
  27414. defines.REFLECTION = true;
  27415. defines.ROUGHNESS = (this._roughness > 0);
  27416. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  27417. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  27418. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  27419. switch (this._reflectionTexture.coordinatesMode) {
  27420. case BABYLON.Texture.CUBIC_MODE:
  27421. case BABYLON.Texture.INVCUBIC_MODE:
  27422. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  27423. break;
  27424. case BABYLON.Texture.EXPLICIT_MODE:
  27425. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  27426. break;
  27427. case BABYLON.Texture.PLANAR_MODE:
  27428. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  27429. break;
  27430. case BABYLON.Texture.PROJECTION_MODE:
  27431. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  27432. break;
  27433. case BABYLON.Texture.SKYBOX_MODE:
  27434. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  27435. break;
  27436. case BABYLON.Texture.SPHERICAL_MODE:
  27437. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  27438. break;
  27439. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  27440. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  27441. break;
  27442. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  27443. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  27444. break;
  27445. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  27446. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  27447. break;
  27448. }
  27449. }
  27450. }
  27451. else {
  27452. defines.REFLECTION = false;
  27453. }
  27454. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  27455. if (!this._emissiveTexture.isReady()) {
  27456. return false;
  27457. }
  27458. else {
  27459. defines._needUVs = true;
  27460. defines.EMISSIVE = true;
  27461. }
  27462. }
  27463. else {
  27464. defines.EMISSIVE = false;
  27465. }
  27466. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  27467. if (!this._lightmapTexture.isReady()) {
  27468. return false;
  27469. }
  27470. else {
  27471. defines._needUVs = true;
  27472. defines.LIGHTMAP = true;
  27473. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  27474. }
  27475. }
  27476. else {
  27477. defines.LIGHTMAP = false;
  27478. }
  27479. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  27480. if (!this._specularTexture.isReady()) {
  27481. return false;
  27482. }
  27483. else {
  27484. defines._needUVs = true;
  27485. defines.SPECULAR = true;
  27486. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  27487. }
  27488. }
  27489. else {
  27490. defines.SPECULAR = false;
  27491. }
  27492. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  27493. if (!this._bumpTexture.isReady()) {
  27494. return false;
  27495. }
  27496. else {
  27497. defines._needUVs = true;
  27498. defines.BUMP = true;
  27499. defines.INVERTNORMALMAPX = this.invertNormalMapX;
  27500. defines.INVERTNORMALMAPY = this.invertNormalMapY;
  27501. defines.PARALLAX = this._useParallax;
  27502. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  27503. }
  27504. }
  27505. else {
  27506. defines.BUMP = false;
  27507. }
  27508. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  27509. if (!this._refractionTexture.isReady()) {
  27510. return false;
  27511. }
  27512. else {
  27513. defines._needUVs = true;
  27514. defines.REFRACTION = true;
  27515. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  27516. }
  27517. }
  27518. else {
  27519. defines.REFRACTION = false;
  27520. }
  27521. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  27522. if (!this._cameraColorGradingTexture.isReady()) {
  27523. return false;
  27524. }
  27525. else {
  27526. defines.CAMERACOLORGRADING = true;
  27527. }
  27528. }
  27529. else {
  27530. defines.CAMERACOLORGRADING = false;
  27531. }
  27532. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  27533. }
  27534. else {
  27535. defines.DIFFUSE = false;
  27536. defines.AMBIENT = false;
  27537. defines.OPACITY = false;
  27538. defines.REFLECTION = false;
  27539. defines.EMISSIVE = false;
  27540. defines.LIGHTMAP = false;
  27541. defines.BUMP = false;
  27542. defines.REFRACTION = false;
  27543. defines.CAMERACOLORGRADING = false;
  27544. }
  27545. defines.CAMERACOLORCURVES = (this._cameraColorCurves !== undefined && this._cameraColorCurves !== null);
  27546. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  27547. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  27548. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  27549. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  27550. }
  27551. if (defines._areFresnelDirty) {
  27552. if (StandardMaterial.FresnelEnabled) {
  27553. // Fresnel
  27554. if (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled ||
  27555. this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled ||
  27556. this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled ||
  27557. this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled ||
  27558. this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled) {
  27559. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  27560. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  27561. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  27562. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  27563. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  27564. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  27565. defines._needNormals = true;
  27566. defines.FRESNEL = true;
  27567. }
  27568. }
  27569. else {
  27570. defines.FRESNEL = false;
  27571. }
  27572. }
  27573. // Misc.
  27574. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  27575. // Attribs
  27576. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  27577. // Values that need to be evaluated on every frame
  27578. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  27579. if (scene._mirroredCameraPosition && defines.BUMP) {
  27580. defines.INVERTNORMALMAPX = !this.invertNormalMapX;
  27581. defines.INVERTNORMALMAPY = !this.invertNormalMapY;
  27582. defines.markAsUnprocessed();
  27583. }
  27584. // Get correct effect
  27585. if (defines.isDirty) {
  27586. defines.markAsProcessed();
  27587. scene.resetCachedMaterial();
  27588. // Fallbacks
  27589. var fallbacks = new BABYLON.EffectFallbacks();
  27590. if (defines.REFLECTION) {
  27591. fallbacks.addFallback(0, "REFLECTION");
  27592. }
  27593. if (defines.SPECULAR) {
  27594. fallbacks.addFallback(0, "SPECULAR");
  27595. }
  27596. if (defines.BUMP) {
  27597. fallbacks.addFallback(0, "BUMP");
  27598. }
  27599. if (defines.PARALLAX) {
  27600. fallbacks.addFallback(1, "PARALLAX");
  27601. }
  27602. if (defines.PARALLAXOCCLUSION) {
  27603. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  27604. }
  27605. if (defines.SPECULAROVERALPHA) {
  27606. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  27607. }
  27608. if (defines.FOG) {
  27609. fallbacks.addFallback(1, "FOG");
  27610. }
  27611. if (defines.POINTSIZE) {
  27612. fallbacks.addFallback(0, "POINTSIZE");
  27613. }
  27614. if (defines.LOGARITHMICDEPTH) {
  27615. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  27616. }
  27617. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  27618. if (defines.SPECULARTERM) {
  27619. fallbacks.addFallback(0, "SPECULARTERM");
  27620. }
  27621. if (defines.DIFFUSEFRESNEL) {
  27622. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  27623. }
  27624. if (defines.OPACITYFRESNEL) {
  27625. fallbacks.addFallback(2, "OPACITYFRESNEL");
  27626. }
  27627. if (defines.REFLECTIONFRESNEL) {
  27628. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  27629. }
  27630. if (defines.EMISSIVEFRESNEL) {
  27631. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  27632. }
  27633. if (defines.FRESNEL) {
  27634. fallbacks.addFallback(4, "FRESNEL");
  27635. }
  27636. //Attributes
  27637. var attribs = [BABYLON.VertexBuffer.PositionKind];
  27638. if (defines.NORMAL) {
  27639. attribs.push(BABYLON.VertexBuffer.NormalKind);
  27640. }
  27641. if (defines.UV1) {
  27642. attribs.push(BABYLON.VertexBuffer.UVKind);
  27643. }
  27644. if (defines.UV2) {
  27645. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27646. }
  27647. if (defines.VERTEXCOLOR) {
  27648. attribs.push(BABYLON.VertexBuffer.ColorKind);
  27649. }
  27650. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  27651. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  27652. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  27653. var shaderName = "default";
  27654. if (this.customShaderNameResolve) {
  27655. shaderName = this.customShaderNameResolve(shaderName);
  27656. }
  27657. var join = defines.toString();
  27658. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  27659. "vFogInfos", "vFogColor", "pointSize",
  27660. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  27661. "mBones",
  27662. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  27663. "depthValues",
  27664. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  27665. "logarithmicDepthConstant"
  27666. ];
  27667. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  27668. var uniformBuffers = ["Material", "Scene"];
  27669. if (defines.CAMERACOLORCURVES) {
  27670. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  27671. }
  27672. if (defines.CAMERACOLORGRADING) {
  27673. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  27674. }
  27675. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  27676. uniformsNames: uniforms,
  27677. uniformBuffersNames: uniformBuffers,
  27678. samplers: samplers,
  27679. defines: defines,
  27680. maxSimultaneousLights: this._maxSimultaneousLights
  27681. });
  27682. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  27683. attributes: attribs,
  27684. uniformsNames: uniforms,
  27685. uniformBuffersNames: uniformBuffers,
  27686. samplers: samplers,
  27687. defines: join,
  27688. fallbacks: fallbacks,
  27689. onCompiled: this.onCompiled,
  27690. onError: this.onError,
  27691. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  27692. }, engine), defines);
  27693. this.buildUniformLayout();
  27694. }
  27695. if (!subMesh.effect.isReady()) {
  27696. return false;
  27697. }
  27698. defines._renderId = scene.getRenderId();
  27699. this._wasPreviouslyReady = true;
  27700. return true;
  27701. };
  27702. StandardMaterial.prototype.buildUniformLayout = function () {
  27703. // Order is important !
  27704. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  27705. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  27706. this._uniformBuffer.addUniform("opacityParts", 4);
  27707. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  27708. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  27709. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  27710. this._uniformBuffer.addUniform("refractionRightColor", 4);
  27711. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  27712. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  27713. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  27714. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  27715. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  27716. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  27717. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  27718. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  27719. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  27720. this._uniformBuffer.addUniform("vBumpInfos", 3);
  27721. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  27722. this._uniformBuffer.addUniform("ambientMatrix", 16);
  27723. this._uniformBuffer.addUniform("opacityMatrix", 16);
  27724. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  27725. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  27726. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  27727. this._uniformBuffer.addUniform("specularMatrix", 16);
  27728. this._uniformBuffer.addUniform("bumpMatrix", 16);
  27729. this._uniformBuffer.addUniform("refractionMatrix", 16);
  27730. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  27731. this._uniformBuffer.addUniform("vSpecularColor", 4);
  27732. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  27733. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  27734. this._uniformBuffer.addUniform("pointSize", 1);
  27735. this._uniformBuffer.create();
  27736. };
  27737. StandardMaterial.prototype.unbind = function () {
  27738. if (this._activeEffect) {
  27739. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  27740. this._activeEffect.setTexture("reflection2DSampler", null);
  27741. }
  27742. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  27743. this._activeEffect.setTexture("refraction2DSampler", null);
  27744. }
  27745. }
  27746. _super.prototype.unbind.call(this);
  27747. };
  27748. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  27749. var scene = this.getScene();
  27750. var defines = subMesh._materialDefines;
  27751. if (!defines) {
  27752. return;
  27753. }
  27754. var effect = subMesh.effect;
  27755. this._activeEffect = effect;
  27756. // Matrices
  27757. this.bindOnlyWorldMatrix(world);
  27758. // Bones
  27759. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  27760. if (this._mustRebind(scene, effect, mesh.visibility)) {
  27761. this._uniformBuffer.bindToEffect(effect, "Material");
  27762. this.bindViewProjection(effect);
  27763. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  27764. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  27765. // Fresnel
  27766. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  27767. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  27768. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  27769. }
  27770. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  27771. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  27772. }
  27773. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  27774. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  27775. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  27776. }
  27777. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  27778. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  27779. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  27780. }
  27781. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  27782. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  27783. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  27784. }
  27785. }
  27786. // Textures
  27787. if (scene.texturesEnabled) {
  27788. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  27789. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  27790. this._uniformBuffer.updateMatrix("diffuseMatrix", this._diffuseTexture.getTextureMatrix());
  27791. }
  27792. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  27793. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  27794. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  27795. }
  27796. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  27797. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  27798. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  27799. }
  27800. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  27801. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  27802. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  27803. }
  27804. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  27805. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  27806. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  27807. }
  27808. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  27809. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  27810. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  27811. }
  27812. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  27813. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  27814. this._uniformBuffer.updateMatrix("specularMatrix", this._specularTexture.getTextureMatrix());
  27815. }
  27816. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  27817. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  27818. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  27819. }
  27820. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  27821. var depth = 1.0;
  27822. if (!this._refractionTexture.isCube) {
  27823. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  27824. if (this._refractionTexture.depth) {
  27825. depth = this._refractionTexture.depth;
  27826. }
  27827. }
  27828. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  27829. }
  27830. }
  27831. // Point size
  27832. if (this.pointsCloud) {
  27833. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  27834. }
  27835. if (defines.SPECULARTERM) {
  27836. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  27837. }
  27838. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  27839. // Diffuse
  27840. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  27841. }
  27842. // Textures
  27843. if (scene.texturesEnabled) {
  27844. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  27845. effect.setTexture("diffuseSampler", this._diffuseTexture);
  27846. }
  27847. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  27848. effect.setTexture("ambientSampler", this._ambientTexture);
  27849. }
  27850. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  27851. effect.setTexture("opacitySampler", this._opacityTexture);
  27852. }
  27853. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  27854. if (this._reflectionTexture.isCube) {
  27855. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  27856. }
  27857. else {
  27858. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  27859. }
  27860. }
  27861. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  27862. effect.setTexture("emissiveSampler", this._emissiveTexture);
  27863. }
  27864. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  27865. effect.setTexture("lightmapSampler", this._lightmapTexture);
  27866. }
  27867. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  27868. effect.setTexture("specularSampler", this._specularTexture);
  27869. }
  27870. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  27871. effect.setTexture("bumpSampler", this._bumpTexture);
  27872. }
  27873. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  27874. var depth = 1.0;
  27875. if (this._refractionTexture.isCube) {
  27876. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  27877. }
  27878. else {
  27879. effect.setTexture("refraction2DSampler", this._refractionTexture);
  27880. }
  27881. }
  27882. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  27883. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, effect);
  27884. }
  27885. }
  27886. // Clip plane
  27887. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  27888. // Colors
  27889. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  27890. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  27891. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  27892. }
  27893. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  27894. // Lights
  27895. if (scene.lightsEnabled && !this._disableLighting) {
  27896. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  27897. }
  27898. // View
  27899. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  27900. this.bindView(effect);
  27901. }
  27902. // Fog
  27903. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  27904. // Morph targets
  27905. if (defines.NUM_MORPH_INFLUENCERS) {
  27906. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  27907. }
  27908. // Log. depth
  27909. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  27910. // Color Curves
  27911. if (this._cameraColorCurves) {
  27912. BABYLON.ColorCurves.Bind(this._cameraColorCurves, effect);
  27913. }
  27914. }
  27915. this._uniformBuffer.update();
  27916. this._afterBind(mesh, this._activeEffect);
  27917. };
  27918. StandardMaterial.prototype.getAnimatables = function () {
  27919. var results = [];
  27920. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  27921. results.push(this._diffuseTexture);
  27922. }
  27923. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  27924. results.push(this._ambientTexture);
  27925. }
  27926. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  27927. results.push(this._opacityTexture);
  27928. }
  27929. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  27930. results.push(this._reflectionTexture);
  27931. }
  27932. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  27933. results.push(this._emissiveTexture);
  27934. }
  27935. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  27936. results.push(this._specularTexture);
  27937. }
  27938. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  27939. results.push(this._bumpTexture);
  27940. }
  27941. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  27942. results.push(this._lightmapTexture);
  27943. }
  27944. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  27945. results.push(this._refractionTexture);
  27946. }
  27947. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  27948. results.push(this._cameraColorGradingTexture);
  27949. }
  27950. return results;
  27951. };
  27952. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27953. if (forceDisposeTextures) {
  27954. if (this._diffuseTexture) {
  27955. this._diffuseTexture.dispose();
  27956. }
  27957. if (this._ambientTexture) {
  27958. this._ambientTexture.dispose();
  27959. }
  27960. if (this._opacityTexture) {
  27961. this._opacityTexture.dispose();
  27962. }
  27963. if (this._reflectionTexture) {
  27964. this._reflectionTexture.dispose();
  27965. }
  27966. if (this._emissiveTexture) {
  27967. this._emissiveTexture.dispose();
  27968. }
  27969. if (this._specularTexture) {
  27970. this._specularTexture.dispose();
  27971. }
  27972. if (this._bumpTexture) {
  27973. this._bumpTexture.dispose();
  27974. }
  27975. if (this._lightmapTexture) {
  27976. this._lightmapTexture.dispose();
  27977. }
  27978. if (this._refractionTexture) {
  27979. this._refractionTexture.dispose();
  27980. }
  27981. if (this._cameraColorGradingTexture) {
  27982. this._cameraColorGradingTexture.dispose();
  27983. }
  27984. }
  27985. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  27986. };
  27987. StandardMaterial.prototype.clone = function (name) {
  27988. var _this = this;
  27989. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  27990. result.name = name;
  27991. result.id = name;
  27992. return result;
  27993. };
  27994. StandardMaterial.prototype.serialize = function () {
  27995. return BABYLON.SerializationHelper.Serialize(this);
  27996. };
  27997. // Statics
  27998. StandardMaterial.Parse = function (source, scene, rootUrl) {
  27999. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  28000. };
  28001. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  28002. get: function () {
  28003. return StandardMaterial._DiffuseTextureEnabled;
  28004. },
  28005. set: function (value) {
  28006. if (StandardMaterial._DiffuseTextureEnabled === value) {
  28007. return;
  28008. }
  28009. StandardMaterial._DiffuseTextureEnabled = value;
  28010. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28011. },
  28012. enumerable: true,
  28013. configurable: true
  28014. });
  28015. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  28016. get: function () {
  28017. return StandardMaterial._AmbientTextureEnabled;
  28018. },
  28019. set: function (value) {
  28020. if (StandardMaterial._AmbientTextureEnabled === value) {
  28021. return;
  28022. }
  28023. StandardMaterial._AmbientTextureEnabled = value;
  28024. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28025. },
  28026. enumerable: true,
  28027. configurable: true
  28028. });
  28029. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  28030. get: function () {
  28031. return StandardMaterial._OpacityTextureEnabled;
  28032. },
  28033. set: function (value) {
  28034. if (StandardMaterial._OpacityTextureEnabled === value) {
  28035. return;
  28036. }
  28037. StandardMaterial._OpacityTextureEnabled = value;
  28038. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28039. },
  28040. enumerable: true,
  28041. configurable: true
  28042. });
  28043. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  28044. get: function () {
  28045. return StandardMaterial._ReflectionTextureEnabled;
  28046. },
  28047. set: function (value) {
  28048. if (StandardMaterial._ReflectionTextureEnabled === value) {
  28049. return;
  28050. }
  28051. StandardMaterial._ReflectionTextureEnabled = value;
  28052. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28053. },
  28054. enumerable: true,
  28055. configurable: true
  28056. });
  28057. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  28058. get: function () {
  28059. return StandardMaterial._EmissiveTextureEnabled;
  28060. },
  28061. set: function (value) {
  28062. if (StandardMaterial._EmissiveTextureEnabled === value) {
  28063. return;
  28064. }
  28065. StandardMaterial._EmissiveTextureEnabled = value;
  28066. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28067. },
  28068. enumerable: true,
  28069. configurable: true
  28070. });
  28071. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  28072. get: function () {
  28073. return StandardMaterial._SpecularTextureEnabled;
  28074. },
  28075. set: function (value) {
  28076. if (StandardMaterial._SpecularTextureEnabled === value) {
  28077. return;
  28078. }
  28079. StandardMaterial._SpecularTextureEnabled = value;
  28080. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28081. },
  28082. enumerable: true,
  28083. configurable: true
  28084. });
  28085. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  28086. get: function () {
  28087. return StandardMaterial._BumpTextureEnabled;
  28088. },
  28089. set: function (value) {
  28090. if (StandardMaterial._BumpTextureEnabled === value) {
  28091. return;
  28092. }
  28093. StandardMaterial._BumpTextureEnabled = value;
  28094. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28095. },
  28096. enumerable: true,
  28097. configurable: true
  28098. });
  28099. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  28100. get: function () {
  28101. return StandardMaterial._LightmapTextureEnabled;
  28102. },
  28103. set: function (value) {
  28104. if (StandardMaterial._LightmapTextureEnabled === value) {
  28105. return;
  28106. }
  28107. StandardMaterial._LightmapTextureEnabled = value;
  28108. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28109. },
  28110. enumerable: true,
  28111. configurable: true
  28112. });
  28113. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  28114. get: function () {
  28115. return StandardMaterial._RefractionTextureEnabled;
  28116. },
  28117. set: function (value) {
  28118. if (StandardMaterial._RefractionTextureEnabled === value) {
  28119. return;
  28120. }
  28121. StandardMaterial._RefractionTextureEnabled = value;
  28122. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28123. },
  28124. enumerable: true,
  28125. configurable: true
  28126. });
  28127. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  28128. get: function () {
  28129. return StandardMaterial._ColorGradingTextureEnabled;
  28130. },
  28131. set: function (value) {
  28132. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  28133. return;
  28134. }
  28135. StandardMaterial._ColorGradingTextureEnabled = value;
  28136. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28137. },
  28138. enumerable: true,
  28139. configurable: true
  28140. });
  28141. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  28142. get: function () {
  28143. return StandardMaterial._FresnelEnabled;
  28144. },
  28145. set: function (value) {
  28146. if (StandardMaterial._FresnelEnabled === value) {
  28147. return;
  28148. }
  28149. StandardMaterial._FresnelEnabled = value;
  28150. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  28151. },
  28152. enumerable: true,
  28153. configurable: true
  28154. });
  28155. return StandardMaterial;
  28156. }(BABYLON.PushMaterial));
  28157. // Flags used to enable or disable a type of texture for all Standard Materials
  28158. StandardMaterial._DiffuseTextureEnabled = true;
  28159. StandardMaterial._AmbientTextureEnabled = true;
  28160. StandardMaterial._OpacityTextureEnabled = true;
  28161. StandardMaterial._ReflectionTextureEnabled = true;
  28162. StandardMaterial._EmissiveTextureEnabled = true;
  28163. StandardMaterial._SpecularTextureEnabled = true;
  28164. StandardMaterial._BumpTextureEnabled = true;
  28165. StandardMaterial._LightmapTextureEnabled = true;
  28166. StandardMaterial._RefractionTextureEnabled = true;
  28167. StandardMaterial._ColorGradingTextureEnabled = true;
  28168. StandardMaterial._FresnelEnabled = true;
  28169. __decorate([
  28170. BABYLON.serializeAsTexture("diffuseTexture")
  28171. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  28172. __decorate([
  28173. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28174. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  28175. __decorate([
  28176. BABYLON.serializeAsTexture("ambientTexture")
  28177. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  28178. __decorate([
  28179. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28180. ], StandardMaterial.prototype, "ambientTexture", void 0);
  28181. __decorate([
  28182. BABYLON.serializeAsTexture("opacityTexture")
  28183. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  28184. __decorate([
  28185. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28186. ], StandardMaterial.prototype, "opacityTexture", void 0);
  28187. __decorate([
  28188. BABYLON.serializeAsTexture("reflectionTexture")
  28189. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  28190. __decorate([
  28191. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28192. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  28193. __decorate([
  28194. BABYLON.serializeAsTexture("emissiveTexture")
  28195. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  28196. __decorate([
  28197. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28198. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  28199. __decorate([
  28200. BABYLON.serializeAsTexture("specularTexture")
  28201. ], StandardMaterial.prototype, "_specularTexture", void 0);
  28202. __decorate([
  28203. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28204. ], StandardMaterial.prototype, "specularTexture", void 0);
  28205. __decorate([
  28206. BABYLON.serializeAsTexture("bumpTexture")
  28207. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  28208. __decorate([
  28209. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28210. ], StandardMaterial.prototype, "bumpTexture", void 0);
  28211. __decorate([
  28212. BABYLON.serializeAsTexture("lightmapTexture")
  28213. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  28214. __decorate([
  28215. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28216. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  28217. __decorate([
  28218. BABYLON.serializeAsTexture("refractionTexture")
  28219. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  28220. __decorate([
  28221. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28222. ], StandardMaterial.prototype, "refractionTexture", void 0);
  28223. __decorate([
  28224. BABYLON.serializeAsColor3("ambient")
  28225. ], StandardMaterial.prototype, "ambientColor", void 0);
  28226. __decorate([
  28227. BABYLON.serializeAsColor3("diffuse")
  28228. ], StandardMaterial.prototype, "diffuseColor", void 0);
  28229. __decorate([
  28230. BABYLON.serializeAsColor3("specular")
  28231. ], StandardMaterial.prototype, "specularColor", void 0);
  28232. __decorate([
  28233. BABYLON.serializeAsColor3("emissive")
  28234. ], StandardMaterial.prototype, "emissiveColor", void 0);
  28235. __decorate([
  28236. BABYLON.serialize()
  28237. ], StandardMaterial.prototype, "specularPower", void 0);
  28238. __decorate([
  28239. BABYLON.serialize("useAlphaFromDiffuseTexture")
  28240. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  28241. __decorate([
  28242. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28243. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  28244. __decorate([
  28245. BABYLON.serialize("useEmissiveAsIllumination")
  28246. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  28247. __decorate([
  28248. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28249. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  28250. __decorate([
  28251. BABYLON.serialize("linkEmissiveWithDiffuse")
  28252. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  28253. __decorate([
  28254. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28255. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  28256. __decorate([
  28257. BABYLON.serialize("useSpecularOverAlpha")
  28258. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  28259. __decorate([
  28260. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28261. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  28262. __decorate([
  28263. BABYLON.serialize("useReflectionOverAlpha")
  28264. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  28265. __decorate([
  28266. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28267. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  28268. __decorate([
  28269. BABYLON.serialize("disableLighting")
  28270. ], StandardMaterial.prototype, "_disableLighting", void 0);
  28271. __decorate([
  28272. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  28273. ], StandardMaterial.prototype, "disableLighting", void 0);
  28274. __decorate([
  28275. BABYLON.serialize("useParallax")
  28276. ], StandardMaterial.prototype, "_useParallax", void 0);
  28277. __decorate([
  28278. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28279. ], StandardMaterial.prototype, "useParallax", void 0);
  28280. __decorate([
  28281. BABYLON.serialize("useParallaxOcclusion")
  28282. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  28283. __decorate([
  28284. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28285. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  28286. __decorate([
  28287. BABYLON.serialize()
  28288. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  28289. __decorate([
  28290. BABYLON.serialize("roughness")
  28291. ], StandardMaterial.prototype, "_roughness", void 0);
  28292. __decorate([
  28293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28294. ], StandardMaterial.prototype, "roughness", void 0);
  28295. __decorate([
  28296. BABYLON.serialize()
  28297. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  28298. __decorate([
  28299. BABYLON.serialize()
  28300. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  28301. __decorate([
  28302. BABYLON.serialize("useLightmapAsShadowmap")
  28303. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  28304. __decorate([
  28305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28306. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  28307. __decorate([
  28308. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  28309. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  28310. __decorate([
  28311. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28312. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  28313. __decorate([
  28314. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  28315. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  28316. __decorate([
  28317. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28318. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  28319. __decorate([
  28320. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  28321. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  28322. __decorate([
  28323. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28324. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  28325. __decorate([
  28326. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  28327. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  28328. __decorate([
  28329. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28330. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  28331. __decorate([
  28332. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  28333. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  28334. __decorate([
  28335. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28336. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  28337. __decorate([
  28338. BABYLON.serialize("useReflectionFresnelFromSpecular")
  28339. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  28340. __decorate([
  28341. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28342. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  28343. __decorate([
  28344. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  28345. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  28346. __decorate([
  28347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28348. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  28349. __decorate([
  28350. BABYLON.serialize("maxSimultaneousLights")
  28351. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  28352. __decorate([
  28353. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  28354. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  28355. __decorate([
  28356. BABYLON.serialize("invertNormalMapX")
  28357. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  28358. __decorate([
  28359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28360. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  28361. __decorate([
  28362. BABYLON.serialize("invertNormalMapY")
  28363. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  28364. __decorate([
  28365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28366. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  28367. __decorate([
  28368. BABYLON.serialize("twoSidedLighting")
  28369. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  28370. __decorate([
  28371. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28372. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  28373. __decorate([
  28374. BABYLON.serializeAsTexture("cameraColorGradingTexture")
  28375. ], StandardMaterial.prototype, "_cameraColorGradingTexture", void 0);
  28376. __decorate([
  28377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28378. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  28379. __decorate([
  28380. BABYLON.serializeAsColorCurves("cameraColorCurves")
  28381. ], StandardMaterial.prototype, "_cameraColorCurves", void 0);
  28382. __decorate([
  28383. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28384. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  28385. __decorate([
  28386. BABYLON.serialize()
  28387. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  28388. BABYLON.StandardMaterial = StandardMaterial;
  28389. })(BABYLON || (BABYLON = {}));
  28390. //# sourceMappingURL=babylon.standardMaterial.js.map
  28391. var BABYLON;
  28392. (function (BABYLON) {
  28393. var PBRMaterialDefines = (function (_super) {
  28394. __extends(PBRMaterialDefines, _super);
  28395. function PBRMaterialDefines() {
  28396. var _this = _super.call(this) || this;
  28397. _this.ALBEDO = false;
  28398. _this.AMBIENT = false;
  28399. _this.AMBIENTINGRAYSCALE = false;
  28400. _this.OPACITY = false;
  28401. _this.OPACITYRGB = false;
  28402. _this.REFLECTION = false;
  28403. _this.EMISSIVE = false;
  28404. _this.REFLECTIVITY = false;
  28405. _this.BUMP = false;
  28406. _this.PARALLAX = false;
  28407. _this.PARALLAXOCCLUSION = false;
  28408. _this.SPECULAROVERALPHA = false;
  28409. _this.CLIPPLANE = false;
  28410. _this.ALPHATEST = false;
  28411. _this.ALPHAFROMALBEDO = false;
  28412. _this.POINTSIZE = false;
  28413. _this.FOG = false;
  28414. _this.SPECULARTERM = false;
  28415. _this.OPACITYFRESNEL = false;
  28416. _this.EMISSIVEFRESNEL = false;
  28417. _this.FRESNEL = false;
  28418. _this.NORMAL = false;
  28419. _this.TANGENT = false;
  28420. _this.UV1 = false;
  28421. _this.UV2 = false;
  28422. _this.VERTEXCOLOR = false;
  28423. _this.VERTEXALPHA = false;
  28424. _this.NUM_BONE_INFLUENCERS = 0;
  28425. _this.BonesPerMesh = 0;
  28426. _this.INSTANCES = false;
  28427. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  28428. _this.MICROSURFACEAUTOMATIC = false;
  28429. _this.EMISSIVEASILLUMINATION = false;
  28430. _this.LINKEMISSIVEWITHALBEDO = false;
  28431. _this.LIGHTMAP = false;
  28432. _this.USELIGHTMAPASSHADOWMAP = false;
  28433. _this.REFLECTIONMAP_3D = false;
  28434. _this.REFLECTIONMAP_SPHERICAL = false;
  28435. _this.REFLECTIONMAP_PLANAR = false;
  28436. _this.REFLECTIONMAP_CUBIC = false;
  28437. _this.REFLECTIONMAP_PROJECTION = false;
  28438. _this.REFLECTIONMAP_SKYBOX = false;
  28439. _this.REFLECTIONMAP_EXPLICIT = false;
  28440. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  28441. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  28442. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  28443. _this.INVERTCUBICMAP = false;
  28444. _this.LOGARITHMICDEPTH = false;
  28445. _this.CAMERATONEMAP = false;
  28446. _this.CAMERACONTRAST = false;
  28447. _this.CAMERACOLORGRADING = false;
  28448. _this.CAMERACOLORCURVES = false;
  28449. _this.OVERLOADEDVALUES = false;
  28450. _this.OVERLOADEDSHADOWVALUES = false;
  28451. _this.USESPHERICALFROMREFLECTIONMAP = false;
  28452. _this.REFRACTION = false;
  28453. _this.REFRACTIONMAP_3D = false;
  28454. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  28455. _this.REFRACTIONMAPINLINEARSPACE = false;
  28456. _this.LODBASEDMICROSFURACE = false;
  28457. _this.USEPHYSICALLIGHTFALLOFF = false;
  28458. _this.RADIANCEOVERALPHA = false;
  28459. _this.USEPMREMREFLECTION = false;
  28460. _this.USEPMREMREFRACTION = false;
  28461. _this.INVERTNORMALMAPX = false;
  28462. _this.INVERTNORMALMAPY = false;
  28463. _this.TWOSIDEDLIGHTING = false;
  28464. _this.SHADOWFULLFLOAT = false;
  28465. _this.METALLICWORKFLOW = false;
  28466. _this.METALLICMAP = false;
  28467. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  28468. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  28469. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  28470. _this.AOSTOREINMETALMAPRED = false;
  28471. _this.MICROSURFACEMAP = false;
  28472. _this.MORPHTARGETS = false;
  28473. _this.MORPHTARGETS_NORMAL = false;
  28474. _this.MORPHTARGETS_TANGENT = false;
  28475. _this.NUM_MORPH_INFLUENCERS = 0;
  28476. _this.rebuild();
  28477. return _this;
  28478. }
  28479. return PBRMaterialDefines;
  28480. }(BABYLON.MaterialDefines));
  28481. /**
  28482. * The Physically based material of BJS.
  28483. *
  28484. * This offers the main features of a standard PBR material.
  28485. * For more information, please refer to the documentation :
  28486. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  28487. */
  28488. var PBRMaterial = (function (_super) {
  28489. __extends(PBRMaterial, _super);
  28490. /**
  28491. * Instantiates a new PBRMaterial instance.
  28492. *
  28493. * @param name The material name
  28494. * @param scene The scene the material will be use in.
  28495. */
  28496. function PBRMaterial(name, scene) {
  28497. var _this = _super.call(this, name, scene) || this;
  28498. /**
  28499. * Intensity of the direct lights e.g. the four lights available in your scene.
  28500. * This impacts both the direct diffuse and specular highlights.
  28501. */
  28502. _this.directIntensity = 1.0;
  28503. /**
  28504. * Intensity of the emissive part of the material.
  28505. * This helps controlling the emissive effect without modifying the emissive color.
  28506. */
  28507. _this.emissiveIntensity = 1.0;
  28508. /**
  28509. * Intensity of the environment e.g. how much the environment will light the object
  28510. * either through harmonics for rough material or through the refelction for shiny ones.
  28511. */
  28512. _this.environmentIntensity = 1.0;
  28513. /**
  28514. * This is a special control allowing the reduction of the specular highlights coming from the
  28515. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  28516. */
  28517. _this.specularIntensity = 1.0;
  28518. _this._lightingInfos = new BABYLON.Vector4(_this.directIntensity, _this.emissiveIntensity, _this.environmentIntensity, _this.specularIntensity);
  28519. /**
  28520. * Debug Control allowing disabling the bump map on this material.
  28521. */
  28522. _this.disableBumpMap = false;
  28523. /**
  28524. * Debug Control helping enforcing or dropping the darkness of shadows.
  28525. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  28526. */
  28527. _this.overloadedShadowIntensity = 1.0;
  28528. /**
  28529. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  28530. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  28531. */
  28532. _this.overloadedShadeIntensity = 1.0;
  28533. _this._overloadedShadowInfos = new BABYLON.Vector4(_this.overloadedShadowIntensity, _this.overloadedShadeIntensity, 0.0, 0.0);
  28534. /**
  28535. * The camera exposure used on this material.
  28536. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  28537. * This corresponds to a photographic exposure.
  28538. */
  28539. _this.cameraExposure = 1.0;
  28540. /**
  28541. * The camera contrast used on this material.
  28542. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  28543. */
  28544. _this.cameraContrast = 1.0;
  28545. /**
  28546. * Color Grading 2D Lookup Texture.
  28547. * This allows special effects like sepia, black and white to sixties rendering style.
  28548. */
  28549. _this.cameraColorGradingTexture = null;
  28550. /**
  28551. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  28552. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  28553. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  28554. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  28555. */
  28556. _this.cameraColorCurves = null;
  28557. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  28558. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  28559. /**
  28560. * Debug Control allowing to overload the ambient color.
  28561. * This as to be use with the overloadedAmbientIntensity parameter.
  28562. */
  28563. _this.overloadedAmbient = BABYLON.Color3.White();
  28564. /**
  28565. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  28566. */
  28567. _this.overloadedAmbientIntensity = 0.0;
  28568. /**
  28569. * Debug Control allowing to overload the albedo color.
  28570. * This as to be use with the overloadedAlbedoIntensity parameter.
  28571. */
  28572. _this.overloadedAlbedo = BABYLON.Color3.White();
  28573. /**
  28574. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  28575. */
  28576. _this.overloadedAlbedoIntensity = 0.0;
  28577. /**
  28578. * Debug Control allowing to overload the reflectivity color.
  28579. * This as to be use with the overloadedReflectivityIntensity parameter.
  28580. */
  28581. _this.overloadedReflectivity = new BABYLON.Color3(0.0, 0.0, 0.0);
  28582. /**
  28583. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  28584. */
  28585. _this.overloadedReflectivityIntensity = 0.0;
  28586. /**
  28587. * Debug Control allowing to overload the emissive color.
  28588. * This as to be use with the overloadedEmissiveIntensity parameter.
  28589. */
  28590. _this.overloadedEmissive = BABYLON.Color3.White();
  28591. /**
  28592. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  28593. */
  28594. _this.overloadedEmissiveIntensity = 0.0;
  28595. _this._overloadedIntensity = new BABYLON.Vector4(_this.overloadedAmbientIntensity, _this.overloadedAlbedoIntensity, _this.overloadedReflectivityIntensity, _this.overloadedEmissiveIntensity);
  28596. /**
  28597. * Debug Control allowing to overload the reflection color.
  28598. * This as to be use with the overloadedReflectionIntensity parameter.
  28599. */
  28600. _this.overloadedReflection = BABYLON.Color3.White();
  28601. /**
  28602. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  28603. */
  28604. _this.overloadedReflectionIntensity = 0.0;
  28605. /**
  28606. * Debug Control allowing to overload the microsurface.
  28607. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  28608. */
  28609. _this.overloadedMicroSurface = 0.0;
  28610. /**
  28611. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  28612. */
  28613. _this.overloadedMicroSurfaceIntensity = 0.0;
  28614. _this._overloadedMicroSurface = new BABYLON.Vector3(_this.overloadedMicroSurface, _this.overloadedMicroSurfaceIntensity, _this.overloadedReflectionIntensity);
  28615. /**
  28616. * AKA Occlusion Texture Intensity in other nomenclature.
  28617. */
  28618. _this.ambientTextureStrength = 1.0;
  28619. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  28620. /**
  28621. * AKA Diffuse Color in other nomenclature.
  28622. */
  28623. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  28624. /**
  28625. * AKA Specular Color in other nomenclature.
  28626. */
  28627. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  28628. _this.reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  28629. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  28630. /**
  28631. * AKA Glossiness in other nomenclature.
  28632. */
  28633. _this.microSurface = 0.9;
  28634. /**
  28635. * source material index of refraction (IOR)' / 'destination material IOR.
  28636. */
  28637. _this.indexOfRefraction = 0.66;
  28638. /**
  28639. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  28640. */
  28641. _this.invertRefractionY = false;
  28642. /**
  28643. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  28644. * Materials half opaque for instance using refraction could benefit from this control.
  28645. */
  28646. _this.linkRefractionWithTransparency = false;
  28647. /**
  28648. * The emissive and albedo are linked to never be more than one (Energy conservation).
  28649. */
  28650. _this.linkEmissiveWithAlbedo = false;
  28651. _this.useLightmapAsShadowmap = false;
  28652. /**
  28653. * In this mode, the emissive informtaion will always be added to the lighting once.
  28654. * A light for instance can be thought as emissive.
  28655. */
  28656. _this.useEmissiveAsIllumination = false;
  28657. /**
  28658. * Secifies that the alpha is coming form the albedo channel alpha channel.
  28659. */
  28660. _this.useAlphaFromAlbedoTexture = false;
  28661. /**
  28662. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  28663. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  28664. */
  28665. _this.useSpecularOverAlpha = true;
  28666. /**
  28667. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  28668. */
  28669. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  28670. /**
  28671. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  28672. */
  28673. _this.useRoughnessFromMetallicTextureAlpha = true;
  28674. /**
  28675. * Specifies if the metallic texture contains the roughness information in its green channel.
  28676. */
  28677. _this.useRoughnessFromMetallicTextureGreen = false;
  28678. /**
  28679. * Specifies if the metallic texture contains the metallness information in its blue channel.
  28680. */
  28681. _this.useMetallnessFromMetallicTextureBlue = false;
  28682. /**
  28683. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  28684. */
  28685. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  28686. /**
  28687. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  28688. */
  28689. _this.useAmbientInGrayScale = false;
  28690. /**
  28691. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  28692. * The material will try to infer what glossiness each pixel should be.
  28693. */
  28694. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  28695. /**
  28696. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  28697. * the creation of the material.
  28698. */
  28699. _this.useScalarInLinearSpace = false;
  28700. /**
  28701. * BJS is using an harcoded light falloff based on a manually sets up range.
  28702. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  28703. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  28704. */
  28705. _this.usePhysicalLightFalloff = true;
  28706. /**
  28707. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  28708. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  28709. */
  28710. _this.useRadianceOverAlpha = true;
  28711. /**
  28712. * Allows using the bump map in parallax mode.
  28713. */
  28714. _this.useParallax = false;
  28715. /**
  28716. * Allows using the bump map in parallax occlusion mode.
  28717. */
  28718. _this.useParallaxOcclusion = false;
  28719. /**
  28720. * Controls the scale bias of the parallax mode.
  28721. */
  28722. _this.parallaxScaleBias = 0.05;
  28723. /**
  28724. * If sets to true, disables all the lights affecting the material.
  28725. */
  28726. _this.disableLighting = false;
  28727. /**
  28728. * Number of Simultaneous lights allowed on the material.
  28729. */
  28730. _this.maxSimultaneousLights = 4;
  28731. /**
  28732. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  28733. */
  28734. _this.invertNormalMapX = false;
  28735. /**
  28736. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  28737. */
  28738. _this.invertNormalMapY = false;
  28739. /**
  28740. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  28741. */
  28742. _this.twoSidedLighting = false;
  28743. _this._renderTargets = new BABYLON.SmartArray(16);
  28744. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  28745. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  28746. _this._tempColor = new BABYLON.Color3();
  28747. _this._defines = new PBRMaterialDefines();
  28748. _this._cachedDefines = new PBRMaterialDefines();
  28749. _this._myScene = null;
  28750. _this._myShadowGenerator = null;
  28751. _this._cachedDefines.BonesPerMesh = -1;
  28752. _this.getRenderTargetTextures = function () {
  28753. _this._renderTargets.reset();
  28754. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  28755. _this._renderTargets.push(_this.reflectionTexture);
  28756. }
  28757. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  28758. _this._renderTargets.push(_this.refractionTexture);
  28759. }
  28760. return _this._renderTargets;
  28761. };
  28762. return _this;
  28763. }
  28764. PBRMaterial.prototype.getClassName = function () {
  28765. return "PBRMaterial";
  28766. };
  28767. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  28768. get: function () {
  28769. return this._useLogarithmicDepth;
  28770. },
  28771. set: function (value) {
  28772. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  28773. },
  28774. enumerable: true,
  28775. configurable: true
  28776. });
  28777. PBRMaterial.prototype.needAlphaBlending = function () {
  28778. if (this.linkRefractionWithTransparency) {
  28779. return false;
  28780. }
  28781. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  28782. };
  28783. PBRMaterial.prototype.needAlphaTesting = function () {
  28784. if (this.linkRefractionWithTransparency) {
  28785. return false;
  28786. }
  28787. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  28788. };
  28789. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  28790. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  28791. };
  28792. PBRMaterial.prototype.getAlphaTestTexture = function () {
  28793. return this.albedoTexture;
  28794. };
  28795. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  28796. if (!mesh) {
  28797. return true;
  28798. }
  28799. if (this._defines.INSTANCES !== useInstances) {
  28800. return false;
  28801. }
  28802. return false;
  28803. };
  28804. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  28805. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  28806. };
  28807. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  28808. if (!useScalarInLinear) {
  28809. color.toLinearSpaceToRef(ref);
  28810. }
  28811. else {
  28812. ref.r = color.r;
  28813. ref.g = color.g;
  28814. ref.b = color.b;
  28815. }
  28816. };
  28817. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  28818. var lightIndex = 0;
  28819. var depthValuesAlreadySet = false;
  28820. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  28821. var light = _a[_i];
  28822. var useUbo = light._uniformBuffer.useUbo;
  28823. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  28824. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  28825. // GAMMA CORRECTION.
  28826. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  28827. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  28828. light._uniformBuffer.updateColor4(useUbo ? "vLightDiffuse" : "vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  28829. if (defines["SPECULARTERM"]) {
  28830. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  28831. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  28832. light._uniformBuffer.updateColor3(useUbo ? "vLightSpecular" : "vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  28833. }
  28834. // Shadows
  28835. if (scene.shadowsEnabled) {
  28836. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex + "", effect, depthValuesAlreadySet);
  28837. }
  28838. light._uniformBuffer.update();
  28839. lightIndex++;
  28840. if (lightIndex === maxSimultaneousLights)
  28841. break;
  28842. }
  28843. };
  28844. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  28845. if (this.isFrozen) {
  28846. if (this._wasPreviouslyReady) {
  28847. return true;
  28848. }
  28849. }
  28850. var scene = this.getScene();
  28851. var engine = scene.getEngine();
  28852. var needUVs = false;
  28853. this._defines.reset();
  28854. if (scene.lightsEnabled && !this.disableLighting) {
  28855. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, true, this.maxSimultaneousLights);
  28856. }
  28857. if (!this.checkReadyOnEveryCall) {
  28858. if (this._renderId === scene.getRenderId()) {
  28859. if (this._checkCache(scene, mesh, useInstances)) {
  28860. return true;
  28861. }
  28862. }
  28863. }
  28864. if (scene.texturesEnabled) {
  28865. if (scene.getEngine().getCaps().textureLOD) {
  28866. this._defines.LODBASEDMICROSFURACE = true;
  28867. }
  28868. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  28869. if (!this.albedoTexture.isReady()) {
  28870. return false;
  28871. }
  28872. needUVs = true;
  28873. this._defines.ALBEDO = true;
  28874. }
  28875. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  28876. if (!this.ambientTexture.isReady()) {
  28877. return false;
  28878. }
  28879. needUVs = true;
  28880. this._defines.AMBIENT = true;
  28881. this._defines.AMBIENTINGRAYSCALE = this.useAmbientInGrayScale;
  28882. }
  28883. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  28884. if (!this.opacityTexture.isReady()) {
  28885. return false;
  28886. }
  28887. needUVs = true;
  28888. this._defines.OPACITY = true;
  28889. if (this.opacityTexture.getAlphaFromRGB) {
  28890. this._defines.OPACITYRGB = true;
  28891. }
  28892. }
  28893. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  28894. if (!this.reflectionTexture.isReady()) {
  28895. return false;
  28896. }
  28897. this._defines.REFLECTION = true;
  28898. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  28899. this._defines.INVERTCUBICMAP = true;
  28900. }
  28901. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  28902. switch (this.reflectionTexture.coordinatesMode) {
  28903. case BABYLON.Texture.CUBIC_MODE:
  28904. case BABYLON.Texture.INVCUBIC_MODE:
  28905. this._defines.REFLECTIONMAP_CUBIC = true;
  28906. break;
  28907. case BABYLON.Texture.EXPLICIT_MODE:
  28908. this._defines.REFLECTIONMAP_EXPLICIT = true;
  28909. break;
  28910. case BABYLON.Texture.PLANAR_MODE:
  28911. this._defines.REFLECTIONMAP_PLANAR = true;
  28912. break;
  28913. case BABYLON.Texture.PROJECTION_MODE:
  28914. this._defines.REFLECTIONMAP_PROJECTION = true;
  28915. break;
  28916. case BABYLON.Texture.SKYBOX_MODE:
  28917. this._defines.REFLECTIONMAP_SKYBOX = true;
  28918. break;
  28919. case BABYLON.Texture.SPHERICAL_MODE:
  28920. this._defines.REFLECTIONMAP_SPHERICAL = true;
  28921. break;
  28922. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  28923. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  28924. break;
  28925. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  28926. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  28927. break;
  28928. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  28929. this._defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  28930. break;
  28931. }
  28932. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  28933. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  28934. if (this.reflectionTexture.isPMREM) {
  28935. this._defines.USEPMREMREFLECTION = true;
  28936. }
  28937. }
  28938. }
  28939. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  28940. if (!this.lightmapTexture.isReady()) {
  28941. return false;
  28942. }
  28943. needUVs = true;
  28944. this._defines.LIGHTMAP = true;
  28945. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  28946. }
  28947. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  28948. if (!this.emissiveTexture.isReady()) {
  28949. return false;
  28950. }
  28951. needUVs = true;
  28952. this._defines.EMISSIVE = true;
  28953. }
  28954. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  28955. if (this.metallicTexture) {
  28956. if (!this.metallicTexture.isReady()) {
  28957. return false;
  28958. }
  28959. needUVs = true;
  28960. this._defines.METALLICWORKFLOW = true;
  28961. this._defines.METALLICMAP = true;
  28962. this._defines.ROUGHNESSSTOREINMETALMAPALPHA = this.useRoughnessFromMetallicTextureAlpha;
  28963. this._defines.ROUGHNESSSTOREINMETALMAPGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  28964. this._defines.METALLNESSSTOREINMETALMAPBLUE = this.useMetallnessFromMetallicTextureBlue;
  28965. this._defines.AOSTOREINMETALMAPRED = this.useAmbientOcclusionFromMetallicTextureRed;
  28966. }
  28967. else if (this.reflectivityTexture) {
  28968. if (!this.reflectivityTexture.isReady()) {
  28969. return false;
  28970. }
  28971. needUVs = true;
  28972. this._defines.REFLECTIVITY = true;
  28973. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  28974. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  28975. }
  28976. if (this.microSurfaceTexture) {
  28977. if (!this.microSurfaceTexture.isReady()) {
  28978. return false;
  28979. }
  28980. needUVs = true;
  28981. this._defines.MICROSURFACEMAP = true;
  28982. }
  28983. }
  28984. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  28985. if (!this.bumpTexture.isReady()) {
  28986. return false;
  28987. }
  28988. needUVs = true;
  28989. this._defines.BUMP = true;
  28990. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  28991. this._defines.PARALLAX = true;
  28992. if (this.useParallaxOcclusion) {
  28993. this._defines.PARALLAXOCCLUSION = true;
  28994. }
  28995. }
  28996. if (this.invertNormalMapX) {
  28997. this._defines.INVERTNORMALMAPX = true;
  28998. }
  28999. if (this.invertNormalMapY) {
  29000. this._defines.INVERTNORMALMAPY = true;
  29001. }
  29002. if (scene._mirroredCameraPosition) {
  29003. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  29004. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  29005. }
  29006. }
  29007. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  29008. if (!this.refractionTexture.isReady()) {
  29009. return false;
  29010. }
  29011. needUVs = true;
  29012. this._defines.REFRACTION = true;
  29013. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  29014. if (this.linkRefractionWithTransparency) {
  29015. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  29016. }
  29017. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  29018. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  29019. if (this.refractionTexture.isPMREM) {
  29020. this._defines.USEPMREMREFRACTION = true;
  29021. }
  29022. }
  29023. }
  29024. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  29025. if (!this.cameraColorGradingTexture.isReady()) {
  29026. return false;
  29027. }
  29028. this._defines.CAMERACOLORGRADING = true;
  29029. }
  29030. if (!this.backFaceCulling && this.twoSidedLighting) {
  29031. this._defines.TWOSIDEDLIGHTING = true;
  29032. }
  29033. }
  29034. // Effect
  29035. if (scene.clipPlane) {
  29036. this._defines.CLIPPLANE = true;
  29037. }
  29038. if (engine.getAlphaTesting()) {
  29039. this._defines.ALPHATEST = true;
  29040. }
  29041. if (this._shouldUseAlphaFromAlbedoTexture()) {
  29042. this._defines.ALPHAFROMALBEDO = true;
  29043. }
  29044. if (this.useEmissiveAsIllumination) {
  29045. this._defines.EMISSIVEASILLUMINATION = true;
  29046. }
  29047. if (this.linkEmissiveWithAlbedo) {
  29048. this._defines.LINKEMISSIVEWITHALBEDO = true;
  29049. }
  29050. if (this.useLogarithmicDepth) {
  29051. this._defines.LOGARITHMICDEPTH = true;
  29052. }
  29053. if (this.cameraContrast != 1) {
  29054. this._defines.CAMERACONTRAST = true;
  29055. }
  29056. if (this.cameraExposure != 1) {
  29057. this._defines.CAMERATONEMAP = true;
  29058. }
  29059. if (this.cameraColorCurves) {
  29060. this._defines.CAMERACOLORCURVES = true;
  29061. }
  29062. if (this.overloadedShadeIntensity != 1 ||
  29063. this.overloadedShadowIntensity != 1) {
  29064. this._defines.OVERLOADEDSHADOWVALUES = true;
  29065. }
  29066. if (this.overloadedMicroSurfaceIntensity > 0 ||
  29067. this.overloadedEmissiveIntensity > 0 ||
  29068. this.overloadedReflectivityIntensity > 0 ||
  29069. this.overloadedAlbedoIntensity > 0 ||
  29070. this.overloadedAmbientIntensity > 0 ||
  29071. this.overloadedReflectionIntensity > 0) {
  29072. this._defines.OVERLOADEDVALUES = true;
  29073. }
  29074. // Point size
  29075. if (this.pointsCloud || scene.forcePointsCloud) {
  29076. this._defines.POINTSIZE = true;
  29077. }
  29078. // Fog
  29079. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  29080. this._defines.FOG = true;
  29081. }
  29082. if (BABYLON.StandardMaterial.FresnelEnabled) {
  29083. // Fresnel
  29084. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  29085. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  29086. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  29087. this._defines.OPACITYFRESNEL = true;
  29088. }
  29089. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  29090. this._defines.EMISSIVEFRESNEL = true;
  29091. }
  29092. this._defines.FRESNEL = true;
  29093. }
  29094. }
  29095. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  29096. this._defines.SPECULAROVERALPHA = true;
  29097. }
  29098. if (this.usePhysicalLightFalloff) {
  29099. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  29100. }
  29101. if (this.useRadianceOverAlpha) {
  29102. this._defines.RADIANCEOVERALPHA = true;
  29103. }
  29104. if ((this.metallic !== undefined && this.metallic !== null) || (this.roughness !== undefined && this.roughness !== null)) {
  29105. this._defines.METALLICWORKFLOW = true;
  29106. }
  29107. // Attribs
  29108. if (mesh) {
  29109. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29110. mesh.createNormals(true);
  29111. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  29112. }
  29113. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29114. this._defines.NORMAL = true;
  29115. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  29116. this._defines.TANGENT = true;
  29117. }
  29118. }
  29119. if (needUVs) {
  29120. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29121. this._defines.UV1 = true;
  29122. }
  29123. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29124. this._defines.UV2 = true;
  29125. }
  29126. }
  29127. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29128. this._defines.VERTEXCOLOR = true;
  29129. if (mesh.hasVertexAlpha) {
  29130. this._defines.VERTEXALPHA = true;
  29131. }
  29132. }
  29133. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29134. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  29135. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  29136. }
  29137. // Instances
  29138. if (useInstances) {
  29139. this._defines.INSTANCES = true;
  29140. }
  29141. if (mesh.morphTargetManager) {
  29142. var manager = mesh.morphTargetManager;
  29143. this._defines.MORPHTARGETS_TANGENT = manager.supportsTangents && this._defines.TANGENT;
  29144. this._defines.MORPHTARGETS_NORMAL = manager.supportsNormals && this._defines.NORMAL;
  29145. this._defines.MORPHTARGETS = (manager.numInfluencers > 0);
  29146. this._defines.NUM_MORPH_INFLUENCERS = manager.numInfluencers;
  29147. }
  29148. }
  29149. // Get correct effect
  29150. if (!this._defines.isEqual(this._cachedDefines)) {
  29151. this._defines.cloneTo(this._cachedDefines);
  29152. scene.resetCachedMaterial();
  29153. // Fallbacks
  29154. var fallbacks = new BABYLON.EffectFallbacks();
  29155. if (this._defines.REFLECTION) {
  29156. fallbacks.addFallback(0, "REFLECTION");
  29157. }
  29158. if (this._defines.REFRACTION) {
  29159. fallbacks.addFallback(0, "REFRACTION");
  29160. }
  29161. if (this._defines.REFLECTIVITY) {
  29162. fallbacks.addFallback(0, "REFLECTIVITY");
  29163. }
  29164. if (this._defines.BUMP) {
  29165. fallbacks.addFallback(0, "BUMP");
  29166. }
  29167. if (this._defines.PARALLAX) {
  29168. fallbacks.addFallback(1, "PARALLAX");
  29169. }
  29170. if (this._defines.PARALLAXOCCLUSION) {
  29171. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  29172. }
  29173. if (this._defines.SPECULAROVERALPHA) {
  29174. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  29175. }
  29176. if (this._defines.FOG) {
  29177. fallbacks.addFallback(1, "FOG");
  29178. }
  29179. if (this._defines.POINTSIZE) {
  29180. fallbacks.addFallback(0, "POINTSIZE");
  29181. }
  29182. if (this._defines.LOGARITHMICDEPTH) {
  29183. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  29184. }
  29185. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  29186. if (this._defines.SPECULARTERM) {
  29187. fallbacks.addFallback(0, "SPECULARTERM");
  29188. }
  29189. if (this._defines.OPACITYFRESNEL) {
  29190. fallbacks.addFallback(1, "OPACITYFRESNEL");
  29191. }
  29192. if (this._defines.EMISSIVEFRESNEL) {
  29193. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  29194. }
  29195. if (this._defines.FRESNEL) {
  29196. fallbacks.addFallback(3, "FRESNEL");
  29197. }
  29198. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  29199. fallbacks.addCPUSkinningFallback(0, mesh);
  29200. }
  29201. //Attributes
  29202. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29203. if (this._defines.NORMAL) {
  29204. attribs.push(BABYLON.VertexBuffer.NormalKind);
  29205. }
  29206. if (this._defines.TANGENT) {
  29207. attribs.push(BABYLON.VertexBuffer.TangentKind);
  29208. }
  29209. if (this._defines.UV1) {
  29210. attribs.push(BABYLON.VertexBuffer.UVKind);
  29211. }
  29212. if (this._defines.UV2) {
  29213. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29214. }
  29215. if (this._defines.VERTEXCOLOR) {
  29216. attribs.push(BABYLON.VertexBuffer.ColorKind);
  29217. }
  29218. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  29219. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  29220. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, this._defines);
  29221. // Legacy browser patch
  29222. var join = this._defines.toString();
  29223. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  29224. "vFogInfos", "vFogColor", "pointSize",
  29225. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  29226. "mBones",
  29227. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  29228. "depthValues",
  29229. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  29230. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  29231. "logarithmicDepthConstant",
  29232. "vSphericalX", "vSphericalY", "vSphericalZ",
  29233. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  29234. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  29235. "vMicrosurfaceTextureLods",
  29236. "vCameraInfos"
  29237. ];
  29238. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "microSurfaceSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  29239. var uniformBuffers = ["Material", "Scene"];
  29240. if (this._defines.CAMERACOLORCURVES) {
  29241. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  29242. }
  29243. if (this._defines.CAMERACOLORGRADING) {
  29244. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  29245. }
  29246. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  29247. uniformsNames: uniforms,
  29248. uniformBuffersNames: uniformBuffers,
  29249. samplers: samplers,
  29250. defines: this._defines,
  29251. maxSimultaneousLights: this.maxSimultaneousLights
  29252. });
  29253. var onCompiled = function (effect) {
  29254. if (this.onCompiled) {
  29255. this.onCompiled(effect);
  29256. }
  29257. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  29258. }.bind(this);
  29259. this._effect = scene.getEngine().createEffect("pbr", {
  29260. attributes: attribs,
  29261. uniformsNames: uniforms,
  29262. uniformBuffersNames: uniformBuffers,
  29263. samplers: samplers,
  29264. defines: join,
  29265. fallbacks: fallbacks,
  29266. onCompiled: onCompiled,
  29267. onError: this.onError,
  29268. indexParameters: { maxSimultaneousLights: this.maxSimultaneousLights, maxSimultaneousMorphTargets: this._defines.NUM_MORPH_INFLUENCERS }
  29269. }, engine);
  29270. this.buildUniformLayout();
  29271. }
  29272. if (!this._effect.isReady()) {
  29273. return false;
  29274. }
  29275. this._renderId = scene.getRenderId();
  29276. this._wasPreviouslyReady = true;
  29277. return true;
  29278. };
  29279. PBRMaterial.prototype.buildUniformLayout = function () {
  29280. // Order is important !
  29281. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  29282. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  29283. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  29284. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  29285. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  29286. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  29287. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  29288. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  29289. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  29290. this._uniformBuffer.addUniform("vBumpInfos", 3);
  29291. this._uniformBuffer.addUniform("albedoMatrix", 16);
  29292. this._uniformBuffer.addUniform("ambientMatrix", 16);
  29293. this._uniformBuffer.addUniform("opacityMatrix", 16);
  29294. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  29295. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  29296. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  29297. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  29298. this._uniformBuffer.addUniform("bumpMatrix", 16);
  29299. this._uniformBuffer.addUniform("refractionMatrix", 16);
  29300. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  29301. this._uniformBuffer.addUniform("vReflectionColor", 3);
  29302. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  29303. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  29304. this._uniformBuffer.addUniform("vMicrosurfaceTextureLods", 2);
  29305. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  29306. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  29307. this._uniformBuffer.addUniform("opacityParts", 4);
  29308. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  29309. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  29310. this._uniformBuffer.addUniform("vOverloadedIntensity", 4);
  29311. this._uniformBuffer.addUniform("vOverloadedAmbient", 3);
  29312. this._uniformBuffer.addUniform("vOverloadedAlbedo", 3);
  29313. this._uniformBuffer.addUniform("vOverloadedReflectivity", 3);
  29314. this._uniformBuffer.addUniform("vOverloadedEmissive", 3);
  29315. this._uniformBuffer.addUniform("vOverloadedReflection", 3);
  29316. this._uniformBuffer.addUniform("vOverloadedMicroSurface", 3);
  29317. this._uniformBuffer.addUniform("vOverloadedShadowIntensity", 4);
  29318. this._uniformBuffer.addUniform("pointSize", 1);
  29319. this._uniformBuffer.create();
  29320. };
  29321. PBRMaterial.prototype.unbind = function () {
  29322. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  29323. this._uniformBuffer.setTexture("reflection2DSampler", null);
  29324. }
  29325. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  29326. this._uniformBuffer.setTexture("refraction2DSampler", null);
  29327. }
  29328. _super.prototype.unbind.call(this);
  29329. };
  29330. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  29331. this._effect.setMatrix("world", world);
  29332. };
  29333. PBRMaterial.prototype.bind = function (world, mesh) {
  29334. this._myScene = this.getScene();
  29335. var effect = this._effect;
  29336. // Matrices
  29337. this.bindOnlyWorldMatrix(world);
  29338. // Bones
  29339. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  29340. if (this._myScene.getCachedMaterial() !== this) {
  29341. this._uniformBuffer.bindToEffect(effect, "Material");
  29342. this.bindViewProjection(effect);
  29343. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  29344. // Fresnel
  29345. if (BABYLON.StandardMaterial.FresnelEnabled) {
  29346. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  29347. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  29348. }
  29349. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  29350. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  29351. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  29352. }
  29353. }
  29354. // Texture uniforms
  29355. if (this._myScene.texturesEnabled) {
  29356. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  29357. this._uniformBuffer.updateFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  29358. this._uniformBuffer.updateMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  29359. }
  29360. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  29361. this._uniformBuffer.updateFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  29362. this._uniformBuffer.updateMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  29363. }
  29364. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  29365. this._uniformBuffer.updateFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  29366. this._uniformBuffer.updateMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  29367. }
  29368. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  29369. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  29370. this._uniformBuffer.updateMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  29371. this._uniformBuffer.updateFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  29372. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  29373. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  29374. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  29375. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  29376. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  29377. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  29378. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  29379. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  29380. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  29381. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  29382. }
  29383. }
  29384. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  29385. this._uniformBuffer.updateFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  29386. this._uniformBuffer.updateMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  29387. }
  29388. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  29389. this._uniformBuffer.updateFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  29390. this._uniformBuffer.updateMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  29391. }
  29392. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  29393. if (this.metallicTexture) {
  29394. this._uniformBuffer.updateFloat3("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level, this.ambientTextureStrength);
  29395. this._uniformBuffer.updateMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  29396. }
  29397. else if (this.reflectivityTexture) {
  29398. this._uniformBuffer.updateFloat3("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level, 1.0);
  29399. this._uniformBuffer.updateMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  29400. }
  29401. if (this.microSurfaceTexture) {
  29402. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this.microSurfaceTexture.coordinatesIndex, this.microSurfaceTexture.level);
  29403. this._uniformBuffer.updateMatrix("microSurfaceSamplerMatrix", this.microSurfaceTexture.getTextureMatrix());
  29404. }
  29405. }
  29406. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  29407. this._uniformBuffer.updateFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  29408. this._uniformBuffer.updateMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  29409. }
  29410. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  29411. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  29412. var depth = 1.0;
  29413. if (!this.refractionTexture.isCube) {
  29414. this._uniformBuffer.updateMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  29415. if (this.refractionTexture.depth) {
  29416. depth = this.refractionTexture.depth;
  29417. }
  29418. }
  29419. this._uniformBuffer.updateFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  29420. }
  29421. if ((this.reflectionTexture || this.refractionTexture)) {
  29422. this._uniformBuffer.updateFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  29423. }
  29424. }
  29425. // Point size
  29426. if (this.pointsCloud) {
  29427. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  29428. }
  29429. // Colors
  29430. if (this._defines.METALLICWORKFLOW) {
  29431. PBRMaterial._scaledReflectivity.r = (this.metallic === undefined || this.metallic === null) ? 1 : this.metallic;
  29432. PBRMaterial._scaledReflectivity.g = (this.roughness === undefined || this.roughness === null) ? 1 : this.roughness;
  29433. this._uniformBuffer.updateColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, 0);
  29434. }
  29435. else {
  29436. // GAMMA CORRECTION.
  29437. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  29438. this._uniformBuffer.updateColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  29439. }
  29440. // GAMMA CORRECTION.
  29441. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  29442. this._uniformBuffer.updateColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  29443. // GAMMA CORRECTION.
  29444. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  29445. this._uniformBuffer.updateColor3("vReflectionColor", PBRMaterial._scaledReflection);
  29446. // GAMMA CORRECTION.
  29447. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  29448. this._uniformBuffer.updateColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  29449. // Misc
  29450. this._lightingInfos.x = this.directIntensity;
  29451. this._lightingInfos.y = this.emissiveIntensity;
  29452. this._lightingInfos.z = this.environmentIntensity;
  29453. this._lightingInfos.w = this.specularIntensity;
  29454. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  29455. // Overloaded params
  29456. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  29457. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  29458. this._uniformBuffer.updateVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  29459. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  29460. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  29461. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  29462. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  29463. this._uniformBuffer.updateVector4("vOverloadedIntensity", this._overloadedIntensity);
  29464. this._uniformBuffer.updateColor3("vOverloadedAmbient", this.overloadedAmbient);
  29465. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  29466. this._uniformBuffer.updateColor3("vOverloadedAlbedo", this._tempColor);
  29467. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  29468. this._uniformBuffer.updateColor3("vOverloadedReflectivity", this._tempColor);
  29469. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  29470. this._uniformBuffer.updateColor3("vOverloadedEmissive", this._tempColor);
  29471. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  29472. this._uniformBuffer.updateColor3("vOverloadedReflection", this._tempColor);
  29473. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  29474. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  29475. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  29476. this._uniformBuffer.updateVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  29477. }
  29478. // Textures
  29479. if (this._myScene.texturesEnabled) {
  29480. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  29481. this._uniformBuffer.setTexture("albedoSampler", this.albedoTexture);
  29482. }
  29483. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  29484. this._uniformBuffer.setTexture("ambientSampler", this.ambientTexture);
  29485. }
  29486. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  29487. this._uniformBuffer.setTexture("opacitySampler", this.opacityTexture);
  29488. }
  29489. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  29490. if (this.reflectionTexture.isCube) {
  29491. this._uniformBuffer.setTexture("reflectionCubeSampler", this.reflectionTexture);
  29492. }
  29493. else {
  29494. this._uniformBuffer.setTexture("reflection2DSampler", this.reflectionTexture);
  29495. }
  29496. }
  29497. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  29498. this._uniformBuffer.setTexture("emissiveSampler", this.emissiveTexture);
  29499. }
  29500. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  29501. this._uniformBuffer.setTexture("lightmapSampler", this.lightmapTexture);
  29502. }
  29503. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  29504. if (this.metallicTexture) {
  29505. this._uniformBuffer.setTexture("reflectivitySampler", this.metallicTexture);
  29506. }
  29507. else if (this.reflectivityTexture) {
  29508. this._uniformBuffer.setTexture("reflectivitySampler", this.reflectivityTexture);
  29509. }
  29510. if (this.microSurfaceTexture) {
  29511. this._uniformBuffer.setTexture("microSurfaceSampler", this.microSurfaceTexture);
  29512. }
  29513. }
  29514. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  29515. this._uniformBuffer.setTexture("bumpSampler", this.bumpTexture);
  29516. }
  29517. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  29518. if (this.refractionTexture.isCube) {
  29519. this._uniformBuffer.setTexture("refractionCubeSampler", this.refractionTexture);
  29520. }
  29521. else {
  29522. this._uniformBuffer.setTexture("refraction2DSampler", this.refractionTexture);
  29523. }
  29524. }
  29525. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  29526. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  29527. }
  29528. }
  29529. // Clip plane
  29530. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  29531. // Colors
  29532. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  29533. effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  29534. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  29535. }
  29536. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  29537. // Lights
  29538. if (this._myScene.lightsEnabled && !this.disableLighting) {
  29539. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  29540. }
  29541. // View
  29542. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  29543. this.bindView(effect);
  29544. }
  29545. // Fog
  29546. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  29547. // Morph targets
  29548. if (this._defines.NUM_MORPH_INFLUENCERS) {
  29549. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  29550. }
  29551. this._cameraInfos.x = this.cameraExposure;
  29552. this._cameraInfos.y = this.cameraContrast;
  29553. effect.setVector4("vCameraInfos", this._cameraInfos);
  29554. if (this.cameraColorCurves) {
  29555. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  29556. }
  29557. // Log. depth
  29558. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  29559. }
  29560. this._uniformBuffer.update();
  29561. this._afterBind(mesh);
  29562. this._myScene = null;
  29563. };
  29564. PBRMaterial.prototype.getAnimatables = function () {
  29565. var results = [];
  29566. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  29567. results.push(this.albedoTexture);
  29568. }
  29569. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  29570. results.push(this.ambientTexture);
  29571. }
  29572. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  29573. results.push(this.opacityTexture);
  29574. }
  29575. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  29576. results.push(this.reflectionTexture);
  29577. }
  29578. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  29579. results.push(this.emissiveTexture);
  29580. }
  29581. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  29582. results.push(this.metallicTexture);
  29583. }
  29584. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  29585. results.push(this.reflectivityTexture);
  29586. }
  29587. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  29588. results.push(this.bumpTexture);
  29589. }
  29590. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  29591. results.push(this.lightmapTexture);
  29592. }
  29593. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  29594. results.push(this.refractionTexture);
  29595. }
  29596. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  29597. results.push(this.cameraColorGradingTexture);
  29598. }
  29599. return results;
  29600. };
  29601. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29602. if (forceDisposeTextures) {
  29603. if (this.albedoTexture) {
  29604. this.albedoTexture.dispose();
  29605. }
  29606. if (this.ambientTexture) {
  29607. this.ambientTexture.dispose();
  29608. }
  29609. if (this.opacityTexture) {
  29610. this.opacityTexture.dispose();
  29611. }
  29612. if (this.reflectionTexture) {
  29613. this.reflectionTexture.dispose();
  29614. }
  29615. if (this.emissiveTexture) {
  29616. this.emissiveTexture.dispose();
  29617. }
  29618. if (this.metallicTexture) {
  29619. this.metallicTexture.dispose();
  29620. }
  29621. if (this.reflectivityTexture) {
  29622. this.reflectivityTexture.dispose();
  29623. }
  29624. if (this.bumpTexture) {
  29625. this.bumpTexture.dispose();
  29626. }
  29627. if (this.lightmapTexture) {
  29628. this.lightmapTexture.dispose();
  29629. }
  29630. if (this.refractionTexture) {
  29631. this.refractionTexture.dispose();
  29632. }
  29633. if (this.cameraColorGradingTexture) {
  29634. this.cameraColorGradingTexture.dispose();
  29635. }
  29636. }
  29637. this._renderTargets.dispose();
  29638. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  29639. };
  29640. PBRMaterial.prototype.clone = function (name) {
  29641. var _this = this;
  29642. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  29643. };
  29644. PBRMaterial.prototype.serialize = function () {
  29645. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  29646. serializationObject.customType = "BABYLON.PBRMaterial";
  29647. return serializationObject;
  29648. };
  29649. // Statics
  29650. PBRMaterial.Parse = function (source, scene, rootUrl) {
  29651. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  29652. };
  29653. return PBRMaterial;
  29654. }(BABYLON.Material));
  29655. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  29656. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  29657. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  29658. PBRMaterial._scaledReflection = new BABYLON.Color3();
  29659. __decorate([
  29660. BABYLON.serialize()
  29661. ], PBRMaterial.prototype, "directIntensity", void 0);
  29662. __decorate([
  29663. BABYLON.serialize()
  29664. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  29665. __decorate([
  29666. BABYLON.serialize()
  29667. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  29668. __decorate([
  29669. BABYLON.serialize()
  29670. ], PBRMaterial.prototype, "specularIntensity", void 0);
  29671. __decorate([
  29672. BABYLON.serialize()
  29673. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  29674. __decorate([
  29675. BABYLON.serialize()
  29676. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  29677. __decorate([
  29678. BABYLON.serialize()
  29679. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  29680. __decorate([
  29681. BABYLON.serialize()
  29682. ], PBRMaterial.prototype, "cameraExposure", void 0);
  29683. __decorate([
  29684. BABYLON.serialize()
  29685. ], PBRMaterial.prototype, "cameraContrast", void 0);
  29686. __decorate([
  29687. BABYLON.serializeAsTexture()
  29688. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  29689. __decorate([
  29690. BABYLON.serializeAsColorCurves()
  29691. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  29692. __decorate([
  29693. BABYLON.serializeAsColor3()
  29694. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  29695. __decorate([
  29696. BABYLON.serialize()
  29697. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  29698. __decorate([
  29699. BABYLON.serializeAsColor3()
  29700. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  29701. __decorate([
  29702. BABYLON.serialize()
  29703. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  29704. __decorate([
  29705. BABYLON.serializeAsColor3()
  29706. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  29707. __decorate([
  29708. BABYLON.serialize()
  29709. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  29710. __decorate([
  29711. BABYLON.serializeAsColor3()
  29712. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  29713. __decorate([
  29714. BABYLON.serialize()
  29715. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  29716. __decorate([
  29717. BABYLON.serializeAsColor3()
  29718. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  29719. __decorate([
  29720. BABYLON.serialize()
  29721. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  29722. __decorate([
  29723. BABYLON.serialize()
  29724. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  29725. __decorate([
  29726. BABYLON.serialize()
  29727. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  29728. __decorate([
  29729. BABYLON.serializeAsTexture()
  29730. ], PBRMaterial.prototype, "albedoTexture", void 0);
  29731. __decorate([
  29732. BABYLON.serializeAsTexture()
  29733. ], PBRMaterial.prototype, "ambientTexture", void 0);
  29734. __decorate([
  29735. BABYLON.serialize()
  29736. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  29737. __decorate([
  29738. BABYLON.serializeAsTexture()
  29739. ], PBRMaterial.prototype, "opacityTexture", void 0);
  29740. __decorate([
  29741. BABYLON.serializeAsTexture()
  29742. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  29743. __decorate([
  29744. BABYLON.serializeAsTexture()
  29745. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  29746. __decorate([
  29747. BABYLON.serializeAsTexture()
  29748. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  29749. __decorate([
  29750. BABYLON.serializeAsTexture()
  29751. ], PBRMaterial.prototype, "metallicTexture", void 0);
  29752. __decorate([
  29753. BABYLON.serialize()
  29754. ], PBRMaterial.prototype, "metallic", void 0);
  29755. __decorate([
  29756. BABYLON.serialize()
  29757. ], PBRMaterial.prototype, "roughness", void 0);
  29758. __decorate([
  29759. BABYLON.serializeAsTexture()
  29760. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  29761. __decorate([
  29762. BABYLON.serializeAsTexture()
  29763. ], PBRMaterial.prototype, "bumpTexture", void 0);
  29764. __decorate([
  29765. BABYLON.serializeAsTexture()
  29766. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  29767. __decorate([
  29768. BABYLON.serializeAsTexture()
  29769. ], PBRMaterial.prototype, "refractionTexture", void 0);
  29770. __decorate([
  29771. BABYLON.serializeAsColor3("ambient")
  29772. ], PBRMaterial.prototype, "ambientColor", void 0);
  29773. __decorate([
  29774. BABYLON.serializeAsColor3("albedo")
  29775. ], PBRMaterial.prototype, "albedoColor", void 0);
  29776. __decorate([
  29777. BABYLON.serializeAsColor3("reflectivity")
  29778. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  29779. __decorate([
  29780. BABYLON.serializeAsColor3("reflection")
  29781. ], PBRMaterial.prototype, "reflectionColor", void 0);
  29782. __decorate([
  29783. BABYLON.serializeAsColor3("emissive")
  29784. ], PBRMaterial.prototype, "emissiveColor", void 0);
  29785. __decorate([
  29786. BABYLON.serialize()
  29787. ], PBRMaterial.prototype, "microSurface", void 0);
  29788. __decorate([
  29789. BABYLON.serialize()
  29790. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  29791. __decorate([
  29792. BABYLON.serialize()
  29793. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  29794. __decorate([
  29795. BABYLON.serializeAsFresnelParameters()
  29796. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  29797. __decorate([
  29798. BABYLON.serializeAsFresnelParameters()
  29799. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  29800. __decorate([
  29801. BABYLON.serialize()
  29802. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  29803. __decorate([
  29804. BABYLON.serialize()
  29805. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  29806. __decorate([
  29807. BABYLON.serialize()
  29808. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  29809. __decorate([
  29810. BABYLON.serialize()
  29811. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  29812. __decorate([
  29813. BABYLON.serialize()
  29814. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  29815. __decorate([
  29816. BABYLON.serialize()
  29817. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  29818. __decorate([
  29819. BABYLON.serialize()
  29820. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  29821. __decorate([
  29822. BABYLON.serialize()
  29823. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  29824. __decorate([
  29825. BABYLON.serialize()
  29826. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  29827. __decorate([
  29828. BABYLON.serialize()
  29829. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  29830. __decorate([
  29831. BABYLON.serialize()
  29832. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  29833. __decorate([
  29834. BABYLON.serialize()
  29835. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  29836. __decorate([
  29837. BABYLON.serialize()
  29838. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  29839. __decorate([
  29840. BABYLON.serialize()
  29841. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  29842. __decorate([
  29843. BABYLON.serialize()
  29844. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  29845. __decorate([
  29846. BABYLON.serialize()
  29847. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  29848. __decorate([
  29849. BABYLON.serialize()
  29850. ], PBRMaterial.prototype, "useParallax", void 0);
  29851. __decorate([
  29852. BABYLON.serialize()
  29853. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  29854. __decorate([
  29855. BABYLON.serialize()
  29856. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  29857. __decorate([
  29858. BABYLON.serialize()
  29859. ], PBRMaterial.prototype, "disableLighting", void 0);
  29860. __decorate([
  29861. BABYLON.serialize()
  29862. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  29863. __decorate([
  29864. BABYLON.serialize()
  29865. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  29866. __decorate([
  29867. BABYLON.serialize()
  29868. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  29869. __decorate([
  29870. BABYLON.serialize()
  29871. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  29872. __decorate([
  29873. BABYLON.serialize()
  29874. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  29875. BABYLON.PBRMaterial = PBRMaterial;
  29876. })(BABYLON || (BABYLON = {}));
  29877. //# sourceMappingURL=babylon.pbrMaterial.js.map
  29878. var BABYLON;
  29879. (function (BABYLON) {
  29880. BABYLON.CameraInputTypes = {};
  29881. var CameraInputsManager = (function () {
  29882. function CameraInputsManager(camera) {
  29883. this.attached = {};
  29884. this.camera = camera;
  29885. this.checkInputs = function () { };
  29886. }
  29887. CameraInputsManager.prototype.add = function (input) {
  29888. var type = input.getSimpleName();
  29889. if (this.attached[type]) {
  29890. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  29891. return;
  29892. }
  29893. this.attached[type] = input;
  29894. input.camera = this.camera;
  29895. //for checkInputs, we are dynamically creating a function
  29896. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  29897. if (input.checkInputs) {
  29898. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  29899. }
  29900. if (this.attachedElement) {
  29901. input.attachControl(this.attachedElement);
  29902. }
  29903. };
  29904. CameraInputsManager.prototype.remove = function (inputToRemove) {
  29905. for (var cam in this.attached) {
  29906. var input = this.attached[cam];
  29907. if (input === inputToRemove) {
  29908. input.detachControl(this.attachedElement);
  29909. delete this.attached[cam];
  29910. this.rebuildInputCheck();
  29911. }
  29912. }
  29913. };
  29914. CameraInputsManager.prototype.removeByType = function (inputType) {
  29915. for (var cam in this.attached) {
  29916. var input = this.attached[cam];
  29917. if (input.getTypeName() === inputType) {
  29918. input.detachControl(this.attachedElement);
  29919. delete this.attached[cam];
  29920. this.rebuildInputCheck();
  29921. }
  29922. }
  29923. };
  29924. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  29925. var current = this.checkInputs;
  29926. return function () {
  29927. current();
  29928. fn();
  29929. };
  29930. };
  29931. CameraInputsManager.prototype.attachInput = function (input) {
  29932. input.attachControl(this.attachedElement, this.noPreventDefault);
  29933. };
  29934. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  29935. if (this.attachedElement) {
  29936. return;
  29937. }
  29938. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  29939. this.attachedElement = element;
  29940. this.noPreventDefault = noPreventDefault;
  29941. for (var cam in this.attached) {
  29942. var input = this.attached[cam];
  29943. this.attached[cam].attachControl(element, noPreventDefault);
  29944. }
  29945. };
  29946. CameraInputsManager.prototype.detachElement = function (element) {
  29947. if (this.attachedElement !== element) {
  29948. return;
  29949. }
  29950. for (var cam in this.attached) {
  29951. var input = this.attached[cam];
  29952. this.attached[cam].detachControl(element);
  29953. }
  29954. this.attachedElement = null;
  29955. };
  29956. CameraInputsManager.prototype.rebuildInputCheck = function () {
  29957. this.checkInputs = function () { };
  29958. for (var cam in this.attached) {
  29959. var input = this.attached[cam];
  29960. if (input.checkInputs) {
  29961. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  29962. }
  29963. }
  29964. };
  29965. CameraInputsManager.prototype.clear = function () {
  29966. if (this.attachedElement) {
  29967. this.detachElement(this.attachedElement);
  29968. }
  29969. this.attached = {};
  29970. this.attachedElement = null;
  29971. this.checkInputs = function () { };
  29972. };
  29973. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  29974. var inputs = {};
  29975. for (var cam in this.attached) {
  29976. var input = this.attached[cam];
  29977. var res = BABYLON.SerializationHelper.Serialize(input);
  29978. inputs[input.getTypeName()] = res;
  29979. }
  29980. serializedCamera.inputsmgr = inputs;
  29981. };
  29982. CameraInputsManager.prototype.parse = function (parsedCamera) {
  29983. var parsedInputs = parsedCamera.inputsmgr;
  29984. if (parsedInputs) {
  29985. this.clear();
  29986. for (var n in parsedInputs) {
  29987. var construct = BABYLON.CameraInputTypes[n];
  29988. if (construct) {
  29989. var parsedinput = parsedInputs[n];
  29990. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  29991. this.add(input);
  29992. }
  29993. }
  29994. }
  29995. else {
  29996. //2016-03-08 this part is for managing backward compatibility
  29997. for (var n in this.attached) {
  29998. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  29999. if (construct) {
  30000. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  30001. this.remove(this.attached[n]);
  30002. this.add(input);
  30003. }
  30004. }
  30005. }
  30006. };
  30007. return CameraInputsManager;
  30008. }());
  30009. BABYLON.CameraInputsManager = CameraInputsManager;
  30010. })(BABYLON || (BABYLON = {}));
  30011. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  30012. var BABYLON;
  30013. (function (BABYLON) {
  30014. var FreeCameraMouseInput = (function () {
  30015. function FreeCameraMouseInput(touchEnabled) {
  30016. if (touchEnabled === void 0) { touchEnabled = true; }
  30017. this.touchEnabled = touchEnabled;
  30018. this.buttons = [0, 1, 2];
  30019. this.angularSensibility = 2000.0;
  30020. }
  30021. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  30022. var _this = this;
  30023. var engine = this.camera.getEngine();
  30024. if (!this._pointerInput) {
  30025. this._pointerInput = function (p, s) {
  30026. var evt = p.event;
  30027. if (!_this.touchEnabled && evt.pointerType === "touch") {
  30028. return;
  30029. }
  30030. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  30031. return;
  30032. }
  30033. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  30034. try {
  30035. evt.srcElement.setPointerCapture(evt.pointerId);
  30036. }
  30037. catch (e) {
  30038. //Nothing to do with the error. Execution will continue.
  30039. }
  30040. _this.previousPosition = {
  30041. x: evt.clientX,
  30042. y: evt.clientY
  30043. };
  30044. if (!noPreventDefault) {
  30045. evt.preventDefault();
  30046. element.focus();
  30047. }
  30048. }
  30049. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  30050. try {
  30051. evt.srcElement.releasePointerCapture(evt.pointerId);
  30052. }
  30053. catch (e) {
  30054. //Nothing to do with the error.
  30055. }
  30056. _this.previousPosition = null;
  30057. if (!noPreventDefault) {
  30058. evt.preventDefault();
  30059. }
  30060. }
  30061. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  30062. if (!_this.previousPosition || engine.isPointerLock) {
  30063. return;
  30064. }
  30065. var offsetX = evt.clientX - _this.previousPosition.x;
  30066. var offsetY = evt.clientY - _this.previousPosition.y;
  30067. if (_this.camera.getScene().useRightHandedSystem) {
  30068. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  30069. }
  30070. else {
  30071. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  30072. }
  30073. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  30074. _this.previousPosition = {
  30075. x: evt.clientX,
  30076. y: evt.clientY
  30077. };
  30078. if (!noPreventDefault) {
  30079. evt.preventDefault();
  30080. }
  30081. }
  30082. };
  30083. }
  30084. this._onMouseMove = function (evt) {
  30085. if (!engine.isPointerLock) {
  30086. return;
  30087. }
  30088. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  30089. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  30090. if (_this.camera.getScene().useRightHandedSystem) {
  30091. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  30092. }
  30093. else {
  30094. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  30095. }
  30096. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  30097. _this.previousPosition = null;
  30098. if (!noPreventDefault) {
  30099. evt.preventDefault();
  30100. }
  30101. };
  30102. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  30103. element.addEventListener("mousemove", this._onMouseMove, false);
  30104. };
  30105. FreeCameraMouseInput.prototype.detachControl = function (element) {
  30106. if (this._observer && element) {
  30107. this.camera.getScene().onPointerObservable.remove(this._observer);
  30108. element.removeEventListener("mousemove", this._onMouseMove);
  30109. this._observer = null;
  30110. this._onMouseMove = null;
  30111. this.previousPosition = null;
  30112. }
  30113. };
  30114. FreeCameraMouseInput.prototype.getTypeName = function () {
  30115. return "FreeCameraMouseInput";
  30116. };
  30117. FreeCameraMouseInput.prototype.getSimpleName = function () {
  30118. return "mouse";
  30119. };
  30120. return FreeCameraMouseInput;
  30121. }());
  30122. __decorate([
  30123. BABYLON.serialize()
  30124. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  30125. __decorate([
  30126. BABYLON.serialize()
  30127. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  30128. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  30129. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  30130. })(BABYLON || (BABYLON = {}));
  30131. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  30132. var BABYLON;
  30133. (function (BABYLON) {
  30134. var FreeCameraKeyboardMoveInput = (function () {
  30135. function FreeCameraKeyboardMoveInput() {
  30136. this._keys = [];
  30137. this.keysUp = [38];
  30138. this.keysDown = [40];
  30139. this.keysLeft = [37];
  30140. this.keysRight = [39];
  30141. }
  30142. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  30143. var _this = this;
  30144. if (!this._onKeyDown) {
  30145. element.tabIndex = 1;
  30146. this._onKeyDown = function (evt) {
  30147. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  30148. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  30149. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  30150. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  30151. var index = _this._keys.indexOf(evt.keyCode);
  30152. if (index === -1) {
  30153. _this._keys.push(evt.keyCode);
  30154. }
  30155. if (!noPreventDefault) {
  30156. evt.preventDefault();
  30157. }
  30158. }
  30159. };
  30160. this._onKeyUp = function (evt) {
  30161. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  30162. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  30163. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  30164. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  30165. var index = _this._keys.indexOf(evt.keyCode);
  30166. if (index >= 0) {
  30167. _this._keys.splice(index, 1);
  30168. }
  30169. if (!noPreventDefault) {
  30170. evt.preventDefault();
  30171. }
  30172. }
  30173. };
  30174. element.addEventListener("keydown", this._onKeyDown, false);
  30175. element.addEventListener("keyup", this._onKeyUp, false);
  30176. BABYLON.Tools.RegisterTopRootEvents([
  30177. { name: "blur", handler: this._onLostFocus }
  30178. ]);
  30179. }
  30180. };
  30181. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  30182. if (this._onKeyDown) {
  30183. element.removeEventListener("keydown", this._onKeyDown);
  30184. element.removeEventListener("keyup", this._onKeyUp);
  30185. BABYLON.Tools.UnregisterTopRootEvents([
  30186. { name: "blur", handler: this._onLostFocus }
  30187. ]);
  30188. this._keys = [];
  30189. this._onKeyDown = null;
  30190. this._onKeyUp = null;
  30191. }
  30192. };
  30193. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  30194. if (this._onKeyDown) {
  30195. var camera = this.camera;
  30196. // Keyboard
  30197. for (var index = 0; index < this._keys.length; index++) {
  30198. var keyCode = this._keys[index];
  30199. var speed = camera._computeLocalCameraSpeed();
  30200. if (this.keysLeft.indexOf(keyCode) !== -1) {
  30201. camera._localDirection.copyFromFloats(-speed, 0, 0);
  30202. }
  30203. else if (this.keysUp.indexOf(keyCode) !== -1) {
  30204. camera._localDirection.copyFromFloats(0, 0, speed);
  30205. }
  30206. else if (this.keysRight.indexOf(keyCode) !== -1) {
  30207. camera._localDirection.copyFromFloats(speed, 0, 0);
  30208. }
  30209. else if (this.keysDown.indexOf(keyCode) !== -1) {
  30210. camera._localDirection.copyFromFloats(0, 0, -speed);
  30211. }
  30212. if (camera.getScene().useRightHandedSystem) {
  30213. camera._localDirection.z *= -1;
  30214. }
  30215. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  30216. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  30217. camera.cameraDirection.addInPlace(camera._transformedDirection);
  30218. }
  30219. }
  30220. };
  30221. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  30222. return "FreeCameraKeyboardMoveInput";
  30223. };
  30224. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  30225. this._keys = [];
  30226. };
  30227. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  30228. return "keyboard";
  30229. };
  30230. return FreeCameraKeyboardMoveInput;
  30231. }());
  30232. __decorate([
  30233. BABYLON.serialize()
  30234. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  30235. __decorate([
  30236. BABYLON.serialize()
  30237. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  30238. __decorate([
  30239. BABYLON.serialize()
  30240. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  30241. __decorate([
  30242. BABYLON.serialize()
  30243. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  30244. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  30245. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  30246. })(BABYLON || (BABYLON = {}));
  30247. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  30248. var BABYLON;
  30249. (function (BABYLON) {
  30250. var FreeCameraInputsManager = (function (_super) {
  30251. __extends(FreeCameraInputsManager, _super);
  30252. function FreeCameraInputsManager(camera) {
  30253. return _super.call(this, camera) || this;
  30254. }
  30255. FreeCameraInputsManager.prototype.addKeyboard = function () {
  30256. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  30257. return this;
  30258. };
  30259. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  30260. if (touchEnabled === void 0) { touchEnabled = true; }
  30261. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  30262. return this;
  30263. };
  30264. FreeCameraInputsManager.prototype.addGamepad = function () {
  30265. this.add(new BABYLON.FreeCameraGamepadInput());
  30266. return this;
  30267. };
  30268. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  30269. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  30270. return this;
  30271. };
  30272. FreeCameraInputsManager.prototype.addTouch = function () {
  30273. this.add(new BABYLON.FreeCameraTouchInput());
  30274. return this;
  30275. };
  30276. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  30277. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  30278. return this;
  30279. };
  30280. return FreeCameraInputsManager;
  30281. }(BABYLON.CameraInputsManager));
  30282. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  30283. })(BABYLON || (BABYLON = {}));
  30284. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  30285. /// <reference path="babylon.camera.ts" />
  30286. var BABYLON;
  30287. (function (BABYLON) {
  30288. var TargetCamera = (function (_super) {
  30289. __extends(TargetCamera, _super);
  30290. function TargetCamera(name, position, scene) {
  30291. var _this = _super.call(this, name, position, scene) || this;
  30292. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  30293. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  30294. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  30295. _this.speed = 2.0;
  30296. _this.noRotationConstraint = false;
  30297. _this.lockedTarget = null;
  30298. _this._currentTarget = BABYLON.Vector3.Zero();
  30299. _this._viewMatrix = BABYLON.Matrix.Zero();
  30300. _this._camMatrix = BABYLON.Matrix.Zero();
  30301. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  30302. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  30303. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  30304. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  30305. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  30306. _this._lookAtTemp = BABYLON.Matrix.Zero();
  30307. _this._tempMatrix = BABYLON.Matrix.Zero();
  30308. return _this;
  30309. }
  30310. TargetCamera.prototype.getFrontPosition = function (distance) {
  30311. var direction = this.getTarget().subtract(this.position);
  30312. direction.normalize();
  30313. direction.scaleInPlace(distance);
  30314. return this.globalPosition.add(direction);
  30315. };
  30316. TargetCamera.prototype._getLockedTargetPosition = function () {
  30317. if (!this.lockedTarget) {
  30318. return null;
  30319. }
  30320. if (this.lockedTarget.absolutePosition) {
  30321. this.lockedTarget.computeWorldMatrix();
  30322. }
  30323. return this.lockedTarget.absolutePosition || this.lockedTarget;
  30324. };
  30325. // Cache
  30326. TargetCamera.prototype._initCache = function () {
  30327. _super.prototype._initCache.call(this);
  30328. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  30329. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  30330. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  30331. };
  30332. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  30333. if (!ignoreParentClass) {
  30334. _super.prototype._updateCache.call(this);
  30335. }
  30336. var lockedTargetPosition = this._getLockedTargetPosition();
  30337. if (!lockedTargetPosition) {
  30338. this._cache.lockedTarget = null;
  30339. }
  30340. else {
  30341. if (!this._cache.lockedTarget) {
  30342. this._cache.lockedTarget = lockedTargetPosition.clone();
  30343. }
  30344. else {
  30345. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  30346. }
  30347. }
  30348. this._cache.rotation.copyFrom(this.rotation);
  30349. if (this.rotationQuaternion)
  30350. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  30351. };
  30352. // Synchronized
  30353. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  30354. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  30355. return false;
  30356. }
  30357. var lockedTargetPosition = this._getLockedTargetPosition();
  30358. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  30359. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  30360. };
  30361. // Methods
  30362. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  30363. var engine = this.getEngine();
  30364. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  30365. };
  30366. // Target
  30367. TargetCamera.prototype.setTarget = function (target) {
  30368. this.upVector.normalize();
  30369. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  30370. this._camMatrix.invert();
  30371. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  30372. var vDir = target.subtract(this.position);
  30373. if (vDir.x >= 0.0) {
  30374. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  30375. }
  30376. else {
  30377. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  30378. }
  30379. this.rotation.z = 0;
  30380. if (isNaN(this.rotation.x)) {
  30381. this.rotation.x = 0;
  30382. }
  30383. if (isNaN(this.rotation.y)) {
  30384. this.rotation.y = 0;
  30385. }
  30386. if (isNaN(this.rotation.z)) {
  30387. this.rotation.z = 0;
  30388. }
  30389. if (this.rotationQuaternion) {
  30390. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  30391. }
  30392. };
  30393. /**
  30394. * Return the current target position of the camera. This value is expressed in local space.
  30395. */
  30396. TargetCamera.prototype.getTarget = function () {
  30397. return this._currentTarget;
  30398. };
  30399. TargetCamera.prototype._decideIfNeedsToMove = function () {
  30400. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  30401. };
  30402. TargetCamera.prototype._updatePosition = function () {
  30403. if (this.parent) {
  30404. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  30405. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  30406. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  30407. return;
  30408. }
  30409. this.position.addInPlace(this.cameraDirection);
  30410. };
  30411. TargetCamera.prototype._checkInputs = function () {
  30412. var needToMove = this._decideIfNeedsToMove();
  30413. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  30414. // Move
  30415. if (needToMove) {
  30416. this._updatePosition();
  30417. }
  30418. // Rotate
  30419. if (needToRotate) {
  30420. this.rotation.x += this.cameraRotation.x;
  30421. this.rotation.y += this.cameraRotation.y;
  30422. //rotate, if quaternion is set and rotation was used
  30423. if (this.rotationQuaternion) {
  30424. var len = this.rotation.lengthSquared();
  30425. if (len) {
  30426. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  30427. }
  30428. }
  30429. if (!this.noRotationConstraint) {
  30430. var limit = (Math.PI / 2) * 0.95;
  30431. if (this.rotation.x > limit)
  30432. this.rotation.x = limit;
  30433. if (this.rotation.x < -limit)
  30434. this.rotation.x = -limit;
  30435. }
  30436. }
  30437. // Inertia
  30438. if (needToMove) {
  30439. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  30440. this.cameraDirection.x = 0;
  30441. }
  30442. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  30443. this.cameraDirection.y = 0;
  30444. }
  30445. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  30446. this.cameraDirection.z = 0;
  30447. }
  30448. this.cameraDirection.scaleInPlace(this.inertia);
  30449. }
  30450. if (needToRotate) {
  30451. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  30452. this.cameraRotation.x = 0;
  30453. }
  30454. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  30455. this.cameraRotation.y = 0;
  30456. }
  30457. this.cameraRotation.scaleInPlace(this.inertia);
  30458. }
  30459. _super.prototype._checkInputs.call(this);
  30460. };
  30461. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  30462. if (this.rotationQuaternion) {
  30463. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  30464. //update the up vector!
  30465. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  30466. }
  30467. else {
  30468. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  30469. }
  30470. };
  30471. TargetCamera.prototype._getViewMatrix = function () {
  30472. if (!this.lockedTarget) {
  30473. // Compute
  30474. this._updateCameraRotationMatrix();
  30475. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  30476. // Computing target and final matrix
  30477. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  30478. }
  30479. else {
  30480. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  30481. }
  30482. if (this.getScene().useRightHandedSystem) {
  30483. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  30484. }
  30485. else {
  30486. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  30487. }
  30488. return this._viewMatrix;
  30489. };
  30490. /**
  30491. * @override
  30492. * Override Camera.createRigCamera
  30493. */
  30494. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  30495. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  30496. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  30497. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  30498. if (!this.rotationQuaternion) {
  30499. this.rotationQuaternion = new BABYLON.Quaternion();
  30500. }
  30501. rigCamera._cameraRigParams = {};
  30502. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  30503. }
  30504. return rigCamera;
  30505. }
  30506. return null;
  30507. };
  30508. /**
  30509. * @override
  30510. * Override Camera._updateRigCameras
  30511. */
  30512. TargetCamera.prototype._updateRigCameras = function () {
  30513. var camLeft = this._rigCameras[0];
  30514. var camRight = this._rigCameras[1];
  30515. switch (this.cameraRigMode) {
  30516. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  30517. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  30518. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  30519. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  30520. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  30521. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  30522. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  30523. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  30524. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  30525. camLeft.setTarget(this.getTarget());
  30526. camRight.setTarget(this.getTarget());
  30527. break;
  30528. case BABYLON.Camera.RIG_MODE_VR:
  30529. if (camLeft.rotationQuaternion) {
  30530. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  30531. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  30532. }
  30533. else {
  30534. camLeft.rotation.copyFrom(this.rotation);
  30535. camRight.rotation.copyFrom(this.rotation);
  30536. }
  30537. camLeft.position.copyFrom(this.position);
  30538. camRight.position.copyFrom(this.position);
  30539. break;
  30540. }
  30541. _super.prototype._updateRigCameras.call(this);
  30542. };
  30543. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  30544. if (!this._rigCamTransformMatrix) {
  30545. this._rigCamTransformMatrix = new BABYLON.Matrix();
  30546. }
  30547. var target = this.getTarget();
  30548. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  30549. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  30550. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  30551. };
  30552. TargetCamera.prototype.getClassName = function () {
  30553. return "TargetCamera";
  30554. };
  30555. return TargetCamera;
  30556. }(BABYLON.Camera));
  30557. __decorate([
  30558. BABYLON.serializeAsVector3()
  30559. ], TargetCamera.prototype, "rotation", void 0);
  30560. __decorate([
  30561. BABYLON.serialize()
  30562. ], TargetCamera.prototype, "speed", void 0);
  30563. __decorate([
  30564. BABYLON.serializeAsMeshReference("lockedTargetId")
  30565. ], TargetCamera.prototype, "lockedTarget", void 0);
  30566. BABYLON.TargetCamera = TargetCamera;
  30567. })(BABYLON || (BABYLON = {}));
  30568. //# sourceMappingURL=babylon.targetCamera.js.map
  30569. var BABYLON;
  30570. (function (BABYLON) {
  30571. var FreeCamera = (function (_super) {
  30572. __extends(FreeCamera, _super);
  30573. function FreeCamera(name, position, scene) {
  30574. var _this = _super.call(this, name, position, scene) || this;
  30575. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  30576. _this.checkCollisions = false;
  30577. _this.applyGravity = false;
  30578. _this._needMoveForGravity = false;
  30579. _this._oldPosition = BABYLON.Vector3.Zero();
  30580. _this._diffPosition = BABYLON.Vector3.Zero();
  30581. _this._newPosition = BABYLON.Vector3.Zero();
  30582. // Collisions
  30583. _this._collisionMask = -1;
  30584. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  30585. if (collidedMesh === void 0) { collidedMesh = null; }
  30586. //TODO move this to the collision coordinator!
  30587. if (_this.getScene().workerCollisions)
  30588. newPosition.multiplyInPlace(_this._collider.radius);
  30589. var updatePosition = function (newPos) {
  30590. _this._newPosition.copyFrom(newPos);
  30591. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  30592. var oldPosition = _this.position.clone();
  30593. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  30594. _this.position.addInPlace(_this._diffPosition);
  30595. if (_this.onCollide && collidedMesh) {
  30596. _this.onCollide(collidedMesh);
  30597. }
  30598. }
  30599. };
  30600. updatePosition(newPosition);
  30601. };
  30602. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  30603. _this.inputs.addKeyboard().addMouse();
  30604. return _this;
  30605. }
  30606. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  30607. //-- begin properties for backward compatibility for inputs
  30608. get: function () {
  30609. var mouse = this.inputs.attached["mouse"];
  30610. if (mouse)
  30611. return mouse.angularSensibility;
  30612. },
  30613. set: function (value) {
  30614. var mouse = this.inputs.attached["mouse"];
  30615. if (mouse)
  30616. mouse.angularSensibility = value;
  30617. },
  30618. enumerable: true,
  30619. configurable: true
  30620. });
  30621. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  30622. get: function () {
  30623. var keyboard = this.inputs.attached["keyboard"];
  30624. if (keyboard)
  30625. return keyboard.keysUp;
  30626. },
  30627. set: function (value) {
  30628. var keyboard = this.inputs.attached["keyboard"];
  30629. if (keyboard)
  30630. keyboard.keysUp = value;
  30631. },
  30632. enumerable: true,
  30633. configurable: true
  30634. });
  30635. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  30636. get: function () {
  30637. var keyboard = this.inputs.attached["keyboard"];
  30638. if (keyboard)
  30639. return keyboard.keysDown;
  30640. },
  30641. set: function (value) {
  30642. var keyboard = this.inputs.attached["keyboard"];
  30643. if (keyboard)
  30644. keyboard.keysDown = value;
  30645. },
  30646. enumerable: true,
  30647. configurable: true
  30648. });
  30649. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  30650. get: function () {
  30651. var keyboard = this.inputs.attached["keyboard"];
  30652. if (keyboard)
  30653. return keyboard.keysLeft;
  30654. },
  30655. set: function (value) {
  30656. var keyboard = this.inputs.attached["keyboard"];
  30657. if (keyboard)
  30658. keyboard.keysLeft = value;
  30659. },
  30660. enumerable: true,
  30661. configurable: true
  30662. });
  30663. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  30664. get: function () {
  30665. var keyboard = this.inputs.attached["keyboard"];
  30666. if (keyboard)
  30667. return keyboard.keysRight;
  30668. },
  30669. set: function (value) {
  30670. var keyboard = this.inputs.attached["keyboard"];
  30671. if (keyboard)
  30672. keyboard.keysRight = value;
  30673. },
  30674. enumerable: true,
  30675. configurable: true
  30676. });
  30677. // Controls
  30678. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  30679. this.inputs.attachElement(element, noPreventDefault);
  30680. };
  30681. FreeCamera.prototype.detachControl = function (element) {
  30682. this.inputs.detachElement(element);
  30683. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  30684. this.cameraRotation = new BABYLON.Vector2(0, 0);
  30685. };
  30686. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  30687. get: function () {
  30688. return this._collisionMask;
  30689. },
  30690. set: function (mask) {
  30691. this._collisionMask = !isNaN(mask) ? mask : -1;
  30692. },
  30693. enumerable: true,
  30694. configurable: true
  30695. });
  30696. FreeCamera.prototype._collideWithWorld = function (velocity) {
  30697. var globalPosition;
  30698. if (this.parent) {
  30699. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  30700. }
  30701. else {
  30702. globalPosition = this.position;
  30703. }
  30704. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  30705. if (!this._collider) {
  30706. this._collider = new BABYLON.Collider();
  30707. }
  30708. this._collider.radius = this.ellipsoid;
  30709. this._collider.collisionMask = this._collisionMask;
  30710. //no need for clone, as long as gravity is not on.
  30711. var actualVelocity = velocity;
  30712. //add gravity to the velocity to prevent the dual-collision checking
  30713. if (this.applyGravity) {
  30714. //this prevents mending with cameraDirection, a global variable of the free camera class.
  30715. actualVelocity = velocity.add(this.getScene().gravity);
  30716. }
  30717. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  30718. };
  30719. FreeCamera.prototype._checkInputs = function () {
  30720. if (!this._localDirection) {
  30721. this._localDirection = BABYLON.Vector3.Zero();
  30722. this._transformedDirection = BABYLON.Vector3.Zero();
  30723. }
  30724. this.inputs.checkInputs();
  30725. _super.prototype._checkInputs.call(this);
  30726. };
  30727. FreeCamera.prototype._decideIfNeedsToMove = function () {
  30728. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  30729. };
  30730. FreeCamera.prototype._updatePosition = function () {
  30731. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  30732. this._collideWithWorld(this.cameraDirection);
  30733. }
  30734. else {
  30735. _super.prototype._updatePosition.call(this);
  30736. }
  30737. };
  30738. FreeCamera.prototype.dispose = function () {
  30739. this.inputs.clear();
  30740. _super.prototype.dispose.call(this);
  30741. };
  30742. FreeCamera.prototype.getClassName = function () {
  30743. return "FreeCamera";
  30744. };
  30745. return FreeCamera;
  30746. }(BABYLON.TargetCamera));
  30747. __decorate([
  30748. BABYLON.serializeAsVector3()
  30749. ], FreeCamera.prototype, "ellipsoid", void 0);
  30750. __decorate([
  30751. BABYLON.serialize()
  30752. ], FreeCamera.prototype, "checkCollisions", void 0);
  30753. __decorate([
  30754. BABYLON.serialize()
  30755. ], FreeCamera.prototype, "applyGravity", void 0);
  30756. BABYLON.FreeCamera = FreeCamera;
  30757. })(BABYLON || (BABYLON = {}));
  30758. //# sourceMappingURL=babylon.freeCamera.js.map
  30759. var BABYLON;
  30760. (function (BABYLON) {
  30761. var ArcRotateCameraKeyboardMoveInput = (function () {
  30762. function ArcRotateCameraKeyboardMoveInput() {
  30763. this._keys = [];
  30764. this.keysUp = [38];
  30765. this.keysDown = [40];
  30766. this.keysLeft = [37];
  30767. this.keysRight = [39];
  30768. }
  30769. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  30770. var _this = this;
  30771. element.tabIndex = 1;
  30772. this._onKeyDown = function (evt) {
  30773. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  30774. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  30775. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  30776. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  30777. var index = _this._keys.indexOf(evt.keyCode);
  30778. if (index === -1) {
  30779. _this._keys.push(evt.keyCode);
  30780. }
  30781. if (evt.preventDefault) {
  30782. if (!noPreventDefault) {
  30783. evt.preventDefault();
  30784. }
  30785. }
  30786. }
  30787. };
  30788. this._onKeyUp = function (evt) {
  30789. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  30790. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  30791. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  30792. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  30793. var index = _this._keys.indexOf(evt.keyCode);
  30794. if (index >= 0) {
  30795. _this._keys.splice(index, 1);
  30796. }
  30797. if (evt.preventDefault) {
  30798. if (!noPreventDefault) {
  30799. evt.preventDefault();
  30800. }
  30801. }
  30802. }
  30803. };
  30804. this._onLostFocus = function () {
  30805. _this._keys = [];
  30806. };
  30807. element.addEventListener("keydown", this._onKeyDown, false);
  30808. element.addEventListener("keyup", this._onKeyUp, false);
  30809. BABYLON.Tools.RegisterTopRootEvents([
  30810. { name: "blur", handler: this._onLostFocus }
  30811. ]);
  30812. };
  30813. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  30814. if (element) {
  30815. element.removeEventListener("keydown", this._onKeyDown);
  30816. element.removeEventListener("keyup", this._onKeyUp);
  30817. }
  30818. BABYLON.Tools.UnregisterTopRootEvents([
  30819. { name: "blur", handler: this._onLostFocus }
  30820. ]);
  30821. this._keys = [];
  30822. this._onKeyDown = null;
  30823. this._onKeyUp = null;
  30824. this._onLostFocus = null;
  30825. };
  30826. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  30827. if (this._onKeyDown) {
  30828. var camera = this.camera;
  30829. for (var index = 0; index < this._keys.length; index++) {
  30830. var keyCode = this._keys[index];
  30831. if (this.keysLeft.indexOf(keyCode) !== -1) {
  30832. camera.inertialAlphaOffset -= 0.01;
  30833. }
  30834. else if (this.keysUp.indexOf(keyCode) !== -1) {
  30835. camera.inertialBetaOffset -= 0.01;
  30836. }
  30837. else if (this.keysRight.indexOf(keyCode) !== -1) {
  30838. camera.inertialAlphaOffset += 0.01;
  30839. }
  30840. else if (this.keysDown.indexOf(keyCode) !== -1) {
  30841. camera.inertialBetaOffset += 0.01;
  30842. }
  30843. }
  30844. }
  30845. };
  30846. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  30847. return "ArcRotateCameraKeyboardMoveInput";
  30848. };
  30849. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  30850. return "keyboard";
  30851. };
  30852. return ArcRotateCameraKeyboardMoveInput;
  30853. }());
  30854. __decorate([
  30855. BABYLON.serialize()
  30856. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  30857. __decorate([
  30858. BABYLON.serialize()
  30859. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  30860. __decorate([
  30861. BABYLON.serialize()
  30862. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  30863. __decorate([
  30864. BABYLON.serialize()
  30865. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  30866. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  30867. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  30868. })(BABYLON || (BABYLON = {}));
  30869. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  30870. var BABYLON;
  30871. (function (BABYLON) {
  30872. var ArcRotateCameraMouseWheelInput = (function () {
  30873. function ArcRotateCameraMouseWheelInput() {
  30874. this.wheelPrecision = 3.0;
  30875. }
  30876. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  30877. var _this = this;
  30878. this._wheel = function (p, s) {
  30879. //sanity check - this should be a PointerWheel event.
  30880. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  30881. return;
  30882. var event = p.event;
  30883. var delta = 0;
  30884. if (event.wheelDelta) {
  30885. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  30886. }
  30887. else if (event.detail) {
  30888. delta = -event.detail / _this.wheelPrecision;
  30889. }
  30890. if (delta)
  30891. _this.camera.inertialRadiusOffset += delta;
  30892. if (event.preventDefault) {
  30893. if (!noPreventDefault) {
  30894. event.preventDefault();
  30895. }
  30896. }
  30897. };
  30898. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  30899. };
  30900. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  30901. if (this._observer && element) {
  30902. this.camera.getScene().onPointerObservable.remove(this._observer);
  30903. this._observer = null;
  30904. this._wheel = null;
  30905. }
  30906. };
  30907. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  30908. return "ArcRotateCameraMouseWheelInput";
  30909. };
  30910. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  30911. return "mousewheel";
  30912. };
  30913. return ArcRotateCameraMouseWheelInput;
  30914. }());
  30915. __decorate([
  30916. BABYLON.serialize()
  30917. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  30918. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  30919. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  30920. })(BABYLON || (BABYLON = {}));
  30921. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  30922. var BABYLON;
  30923. (function (BABYLON) {
  30924. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  30925. var ArcRotateCameraPointersInput = (function () {
  30926. function ArcRotateCameraPointersInput() {
  30927. this.buttons = [0, 1, 2];
  30928. this.angularSensibilityX = 1000.0;
  30929. this.angularSensibilityY = 1000.0;
  30930. this.pinchPrecision = 6.0;
  30931. this.panningSensibility = 50.0;
  30932. this._isPanClick = false;
  30933. this.pinchInwards = true;
  30934. }
  30935. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  30936. var _this = this;
  30937. var engine = this.camera.getEngine();
  30938. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  30939. var pointA, pointB;
  30940. var previousPinchDistance = 0;
  30941. this._pointerInput = function (p, s) {
  30942. var evt = p.event;
  30943. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  30944. return;
  30945. }
  30946. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  30947. try {
  30948. evt.srcElement.setPointerCapture(evt.pointerId);
  30949. }
  30950. catch (e) {
  30951. //Nothing to do with the error. Execution will continue.
  30952. }
  30953. // Manage panning with pan button click
  30954. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  30955. // manage pointers
  30956. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  30957. if (pointA === undefined) {
  30958. pointA = cacheSoloPointer;
  30959. }
  30960. else if (pointB === undefined) {
  30961. pointB = cacheSoloPointer;
  30962. }
  30963. if (!noPreventDefault) {
  30964. evt.preventDefault();
  30965. element.focus();
  30966. }
  30967. }
  30968. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  30969. try {
  30970. evt.srcElement.releasePointerCapture(evt.pointerId);
  30971. }
  30972. catch (e) {
  30973. //Nothing to do with the error.
  30974. }
  30975. cacheSoloPointer = null;
  30976. previousPinchDistance = 0;
  30977. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  30978. //but emptying completly pointers collection is required to fix a bug on iPhone :
  30979. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  30980. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  30981. pointA = pointB = undefined;
  30982. if (!noPreventDefault) {
  30983. evt.preventDefault();
  30984. }
  30985. }
  30986. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  30987. if (!noPreventDefault) {
  30988. evt.preventDefault();
  30989. }
  30990. // One button down
  30991. if (pointA && pointB === undefined) {
  30992. if (_this.panningSensibility !== 0 &&
  30993. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  30994. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  30995. _this.camera
  30996. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  30997. _this.camera
  30998. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  30999. }
  31000. else {
  31001. var offsetX = evt.clientX - cacheSoloPointer.x;
  31002. var offsetY = evt.clientY - cacheSoloPointer.y;
  31003. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  31004. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  31005. }
  31006. cacheSoloPointer.x = evt.clientX;
  31007. cacheSoloPointer.y = evt.clientY;
  31008. }
  31009. else if (pointA && pointB) {
  31010. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  31011. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  31012. ed.x = evt.clientX;
  31013. ed.y = evt.clientY;
  31014. var direction = _this.pinchInwards ? 1 : -1;
  31015. var distX = pointA.x - pointB.x;
  31016. var distY = pointA.y - pointB.y;
  31017. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  31018. if (previousPinchDistance === 0) {
  31019. previousPinchDistance = pinchSquaredDistance;
  31020. return;
  31021. }
  31022. if (pinchSquaredDistance !== previousPinchDistance) {
  31023. _this.camera
  31024. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  31025. (_this.pinchPrecision *
  31026. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  31027. direction);
  31028. previousPinchDistance = pinchSquaredDistance;
  31029. }
  31030. }
  31031. }
  31032. };
  31033. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  31034. this._onContextMenu = function (evt) {
  31035. evt.preventDefault();
  31036. };
  31037. if (!this.camera._useCtrlForPanning) {
  31038. element.addEventListener("contextmenu", this._onContextMenu, false);
  31039. }
  31040. this._onLostFocus = function () {
  31041. //this._keys = [];
  31042. pointA = pointB = undefined;
  31043. previousPinchDistance = 0;
  31044. cacheSoloPointer = null;
  31045. };
  31046. this._onMouseMove = function (evt) {
  31047. if (!engine.isPointerLock) {
  31048. return;
  31049. }
  31050. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  31051. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  31052. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  31053. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  31054. if (!noPreventDefault) {
  31055. evt.preventDefault();
  31056. }
  31057. };
  31058. this._onGestureStart = function (e) {
  31059. if (window.MSGesture === undefined) {
  31060. return;
  31061. }
  31062. if (!_this._MSGestureHandler) {
  31063. _this._MSGestureHandler = new MSGesture();
  31064. _this._MSGestureHandler.target = element;
  31065. }
  31066. _this._MSGestureHandler.addPointer(e.pointerId);
  31067. };
  31068. this._onGesture = function (e) {
  31069. _this.camera.radius *= e.scale;
  31070. if (e.preventDefault) {
  31071. if (!noPreventDefault) {
  31072. e.stopPropagation();
  31073. e.preventDefault();
  31074. }
  31075. }
  31076. };
  31077. element.addEventListener("mousemove", this._onMouseMove, false);
  31078. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  31079. element.addEventListener("MSGestureChange", this._onGesture, false);
  31080. element.addEventListener("keydown", this._onKeyDown, false);
  31081. element.addEventListener("keyup", this._onKeyUp, false);
  31082. BABYLON.Tools.RegisterTopRootEvents([
  31083. { name: "blur", handler: this._onLostFocus }
  31084. ]);
  31085. };
  31086. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  31087. if (element && this._observer) {
  31088. this.camera.getScene().onPointerObservable.remove(this._observer);
  31089. this._observer = null;
  31090. element.removeEventListener("contextmenu", this._onContextMenu);
  31091. element.removeEventListener("mousemove", this._onMouseMove);
  31092. element.removeEventListener("MSPointerDown", this._onGestureStart);
  31093. element.removeEventListener("MSGestureChange", this._onGesture);
  31094. element.removeEventListener("keydown", this._onKeyDown);
  31095. element.removeEventListener("keyup", this._onKeyUp);
  31096. this._isPanClick = false;
  31097. this.pinchInwards = true;
  31098. this._onKeyDown = null;
  31099. this._onKeyUp = null;
  31100. this._onMouseMove = null;
  31101. this._onGestureStart = null;
  31102. this._onGesture = null;
  31103. this._MSGestureHandler = null;
  31104. this._onLostFocus = null;
  31105. this._onContextMenu = null;
  31106. }
  31107. BABYLON.Tools.UnregisterTopRootEvents([
  31108. { name: "blur", handler: this._onLostFocus }
  31109. ]);
  31110. };
  31111. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  31112. return "ArcRotateCameraPointersInput";
  31113. };
  31114. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  31115. return "pointers";
  31116. };
  31117. return ArcRotateCameraPointersInput;
  31118. }());
  31119. __decorate([
  31120. BABYLON.serialize()
  31121. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  31122. __decorate([
  31123. BABYLON.serialize()
  31124. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  31125. __decorate([
  31126. BABYLON.serialize()
  31127. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  31128. __decorate([
  31129. BABYLON.serialize()
  31130. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  31131. __decorate([
  31132. BABYLON.serialize()
  31133. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  31134. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  31135. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  31136. })(BABYLON || (BABYLON = {}));
  31137. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  31138. /// <reference path="babylon.targetCamera.ts" />
  31139. /// <reference path="..\Tools\babylon.tools.ts" />
  31140. var BABYLON;
  31141. (function (BABYLON) {
  31142. var ArcRotateCamera = (function (_super) {
  31143. __extends(ArcRotateCamera, _super);
  31144. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  31145. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  31146. _this.inertialAlphaOffset = 0;
  31147. _this.inertialBetaOffset = 0;
  31148. _this.inertialRadiusOffset = 0;
  31149. _this.lowerAlphaLimit = null;
  31150. _this.upperAlphaLimit = null;
  31151. _this.lowerBetaLimit = 0.01;
  31152. _this.upperBetaLimit = Math.PI;
  31153. _this.lowerRadiusLimit = null;
  31154. _this.upperRadiusLimit = null;
  31155. _this.inertialPanningX = 0;
  31156. _this.inertialPanningY = 0;
  31157. //-- end properties for backward compatibility for inputs
  31158. _this.zoomOnFactor = 1;
  31159. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  31160. _this.allowUpsideDown = true;
  31161. _this._viewMatrix = new BABYLON.Matrix();
  31162. // Panning
  31163. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  31164. _this.checkCollisions = false;
  31165. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  31166. _this._previousPosition = BABYLON.Vector3.Zero();
  31167. _this._collisionVelocity = BABYLON.Vector3.Zero();
  31168. _this._newPosition = BABYLON.Vector3.Zero();
  31169. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  31170. if (collidedMesh === void 0) { collidedMesh = null; }
  31171. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  31172. newPosition.multiplyInPlace(_this._collider.radius);
  31173. }
  31174. if (!collidedMesh) {
  31175. _this._previousPosition.copyFrom(_this.position);
  31176. }
  31177. else {
  31178. _this.setPosition(newPosition);
  31179. if (_this.onCollide) {
  31180. _this.onCollide(collidedMesh);
  31181. }
  31182. }
  31183. // Recompute because of constraints
  31184. var cosa = Math.cos(_this.alpha);
  31185. var sina = Math.sin(_this.alpha);
  31186. var cosb = Math.cos(_this.beta);
  31187. var sinb = Math.sin(_this.beta);
  31188. if (sinb === 0) {
  31189. sinb = 0.0001;
  31190. }
  31191. var target = _this._getTargetPosition();
  31192. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  31193. _this.position.copyFrom(_this._newPosition);
  31194. var up = _this.upVector;
  31195. if (_this.allowUpsideDown && _this.beta < 0) {
  31196. up = up.clone();
  31197. up = up.negate();
  31198. }
  31199. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  31200. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  31201. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  31202. _this._collisionTriggered = false;
  31203. };
  31204. _this._target = BABYLON.Vector3.Zero();
  31205. if (target) {
  31206. _this.setTarget(target);
  31207. }
  31208. _this.alpha = alpha;
  31209. _this.beta = beta;
  31210. _this.radius = radius;
  31211. _this.getViewMatrix();
  31212. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  31213. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  31214. return _this;
  31215. }
  31216. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  31217. get: function () {
  31218. return this._target;
  31219. },
  31220. set: function (value) {
  31221. this.setTarget(value);
  31222. },
  31223. enumerable: true,
  31224. configurable: true
  31225. });
  31226. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  31227. //-- begin properties for backward compatibility for inputs
  31228. get: function () {
  31229. var pointers = this.inputs.attached["pointers"];
  31230. if (pointers)
  31231. return pointers.angularSensibilityX;
  31232. },
  31233. set: function (value) {
  31234. var pointers = this.inputs.attached["pointers"];
  31235. if (pointers) {
  31236. pointers.angularSensibilityX = value;
  31237. }
  31238. },
  31239. enumerable: true,
  31240. configurable: true
  31241. });
  31242. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  31243. get: function () {
  31244. var pointers = this.inputs.attached["pointers"];
  31245. if (pointers)
  31246. return pointers.angularSensibilityY;
  31247. },
  31248. set: function (value) {
  31249. var pointers = this.inputs.attached["pointers"];
  31250. if (pointers) {
  31251. pointers.angularSensibilityY = value;
  31252. }
  31253. },
  31254. enumerable: true,
  31255. configurable: true
  31256. });
  31257. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  31258. get: function () {
  31259. var pointers = this.inputs.attached["pointers"];
  31260. if (pointers)
  31261. return pointers.pinchPrecision;
  31262. },
  31263. set: function (value) {
  31264. var pointers = this.inputs.attached["pointers"];
  31265. if (pointers) {
  31266. pointers.pinchPrecision = value;
  31267. }
  31268. },
  31269. enumerable: true,
  31270. configurable: true
  31271. });
  31272. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  31273. get: function () {
  31274. var pointers = this.inputs.attached["pointers"];
  31275. if (pointers)
  31276. return pointers.panningSensibility;
  31277. },
  31278. set: function (value) {
  31279. var pointers = this.inputs.attached["pointers"];
  31280. if (pointers) {
  31281. pointers.panningSensibility = value;
  31282. }
  31283. },
  31284. enumerable: true,
  31285. configurable: true
  31286. });
  31287. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  31288. get: function () {
  31289. var keyboard = this.inputs.attached["keyboard"];
  31290. if (keyboard)
  31291. return keyboard.keysUp;
  31292. },
  31293. set: function (value) {
  31294. var keyboard = this.inputs.attached["keyboard"];
  31295. if (keyboard)
  31296. keyboard.keysUp = value;
  31297. },
  31298. enumerable: true,
  31299. configurable: true
  31300. });
  31301. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  31302. get: function () {
  31303. var keyboard = this.inputs.attached["keyboard"];
  31304. if (keyboard)
  31305. return keyboard.keysDown;
  31306. },
  31307. set: function (value) {
  31308. var keyboard = this.inputs.attached["keyboard"];
  31309. if (keyboard)
  31310. keyboard.keysDown = value;
  31311. },
  31312. enumerable: true,
  31313. configurable: true
  31314. });
  31315. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  31316. get: function () {
  31317. var keyboard = this.inputs.attached["keyboard"];
  31318. if (keyboard)
  31319. return keyboard.keysLeft;
  31320. },
  31321. set: function (value) {
  31322. var keyboard = this.inputs.attached["keyboard"];
  31323. if (keyboard)
  31324. keyboard.keysLeft = value;
  31325. },
  31326. enumerable: true,
  31327. configurable: true
  31328. });
  31329. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  31330. get: function () {
  31331. var keyboard = this.inputs.attached["keyboard"];
  31332. if (keyboard)
  31333. return keyboard.keysRight;
  31334. },
  31335. set: function (value) {
  31336. var keyboard = this.inputs.attached["keyboard"];
  31337. if (keyboard)
  31338. keyboard.keysRight = value;
  31339. },
  31340. enumerable: true,
  31341. configurable: true
  31342. });
  31343. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  31344. get: function () {
  31345. var mousewheel = this.inputs.attached["mousewheel"];
  31346. if (mousewheel)
  31347. return mousewheel.wheelPrecision;
  31348. },
  31349. set: function (value) {
  31350. var mousewheel = this.inputs.attached["mousewheel"];
  31351. if (mousewheel)
  31352. mousewheel.wheelPrecision = value;
  31353. },
  31354. enumerable: true,
  31355. configurable: true
  31356. });
  31357. // Cache
  31358. ArcRotateCamera.prototype._initCache = function () {
  31359. _super.prototype._initCache.call(this);
  31360. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31361. this._cache.alpha = undefined;
  31362. this._cache.beta = undefined;
  31363. this._cache.radius = undefined;
  31364. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  31365. };
  31366. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  31367. if (!ignoreParentClass) {
  31368. _super.prototype._updateCache.call(this);
  31369. }
  31370. this._cache._target.copyFrom(this._getTargetPosition());
  31371. this._cache.alpha = this.alpha;
  31372. this._cache.beta = this.beta;
  31373. this._cache.radius = this.radius;
  31374. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  31375. };
  31376. ArcRotateCamera.prototype._getTargetPosition = function () {
  31377. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  31378. var pos = this._targetHost.getAbsolutePosition();
  31379. if (this._targetBoundingCenter) {
  31380. pos.addToRef(this._targetBoundingCenter, this._target);
  31381. }
  31382. else {
  31383. this._target.copyFrom(pos);
  31384. }
  31385. }
  31386. return this._target;
  31387. };
  31388. // Synchronized
  31389. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  31390. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  31391. return false;
  31392. return this._cache._target.equals(this._target)
  31393. && this._cache.alpha === this.alpha
  31394. && this._cache.beta === this.beta
  31395. && this._cache.radius === this.radius
  31396. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  31397. };
  31398. // Methods
  31399. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  31400. var _this = this;
  31401. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  31402. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  31403. this._useCtrlForPanning = useCtrlForPanning;
  31404. this._panningMouseButton = panningMouseButton;
  31405. this.inputs.attachElement(element, noPreventDefault);
  31406. this._reset = function () {
  31407. _this.inertialAlphaOffset = 0;
  31408. _this.inertialBetaOffset = 0;
  31409. _this.inertialRadiusOffset = 0;
  31410. };
  31411. };
  31412. ArcRotateCamera.prototype.detachControl = function (element) {
  31413. this.inputs.detachElement(element);
  31414. if (this._reset) {
  31415. this._reset();
  31416. }
  31417. };
  31418. ArcRotateCamera.prototype._checkInputs = function () {
  31419. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  31420. if (this._collisionTriggered) {
  31421. return;
  31422. }
  31423. this.inputs.checkInputs();
  31424. // Inertia
  31425. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  31426. if (this.getScene().useRightHandedSystem) {
  31427. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  31428. }
  31429. else {
  31430. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  31431. }
  31432. this.beta += this.inertialBetaOffset;
  31433. this.radius -= this.inertialRadiusOffset;
  31434. this.inertialAlphaOffset *= this.inertia;
  31435. this.inertialBetaOffset *= this.inertia;
  31436. this.inertialRadiusOffset *= this.inertia;
  31437. if (Math.abs(this.inertialAlphaOffset) < this.speed * BABYLON.Epsilon)
  31438. this.inertialAlphaOffset = 0;
  31439. if (Math.abs(this.inertialBetaOffset) < this.speed * BABYLON.Epsilon)
  31440. this.inertialBetaOffset = 0;
  31441. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  31442. this.inertialRadiusOffset = 0;
  31443. }
  31444. // Panning inertia
  31445. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  31446. if (!this._localDirection) {
  31447. this._localDirection = BABYLON.Vector3.Zero();
  31448. this._transformedDirection = BABYLON.Vector3.Zero();
  31449. }
  31450. this.inertialPanningX *= this.inertia;
  31451. this.inertialPanningY *= this.inertia;
  31452. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  31453. this.inertialPanningX = 0;
  31454. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  31455. this.inertialPanningY = 0;
  31456. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  31457. this._localDirection.multiplyInPlace(this.panningAxis);
  31458. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  31459. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  31460. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  31461. if (!this.panningAxis.y) {
  31462. this._transformedDirection.y = 0;
  31463. }
  31464. if (!this._targetHost) {
  31465. this._target.addInPlace(this._transformedDirection);
  31466. }
  31467. }
  31468. // Limits
  31469. this._checkLimits();
  31470. _super.prototype._checkInputs.call(this);
  31471. };
  31472. ArcRotateCamera.prototype._checkLimits = function () {
  31473. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  31474. if (this.allowUpsideDown && this.beta > Math.PI) {
  31475. this.beta = this.beta - (2 * Math.PI);
  31476. }
  31477. }
  31478. else {
  31479. if (this.beta < this.lowerBetaLimit) {
  31480. this.beta = this.lowerBetaLimit;
  31481. }
  31482. }
  31483. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  31484. if (this.allowUpsideDown && this.beta < -Math.PI) {
  31485. this.beta = this.beta + (2 * Math.PI);
  31486. }
  31487. }
  31488. else {
  31489. if (this.beta > this.upperBetaLimit) {
  31490. this.beta = this.upperBetaLimit;
  31491. }
  31492. }
  31493. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  31494. this.alpha = this.lowerAlphaLimit;
  31495. }
  31496. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  31497. this.alpha = this.upperAlphaLimit;
  31498. }
  31499. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  31500. this.radius = this.lowerRadiusLimit;
  31501. }
  31502. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  31503. this.radius = this.upperRadiusLimit;
  31504. }
  31505. };
  31506. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  31507. var radiusv3 = this.position.subtract(this._getTargetPosition());
  31508. this.radius = radiusv3.length();
  31509. // Alpha
  31510. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  31511. if (radiusv3.z < 0) {
  31512. this.alpha = 2 * Math.PI - this.alpha;
  31513. }
  31514. // Beta
  31515. this.beta = Math.acos(radiusv3.y / this.radius);
  31516. this._checkLimits();
  31517. };
  31518. ArcRotateCamera.prototype.setPosition = function (position) {
  31519. if (this.position.equals(position)) {
  31520. return;
  31521. }
  31522. this.position.copyFrom(position);
  31523. this.rebuildAnglesAndRadius();
  31524. };
  31525. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  31526. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  31527. if (allowSamePosition === void 0) { allowSamePosition = false; }
  31528. if (target.getBoundingInfo) {
  31529. if (toBoundingCenter) {
  31530. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  31531. }
  31532. else {
  31533. this._targetBoundingCenter = null;
  31534. }
  31535. this._targetHost = target;
  31536. this._target = this._getTargetPosition();
  31537. }
  31538. else {
  31539. var newTarget = target;
  31540. var currentTarget = this._getTargetPosition();
  31541. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  31542. return;
  31543. }
  31544. this._target = newTarget;
  31545. this._targetBoundingCenter = null;
  31546. }
  31547. this.rebuildAnglesAndRadius();
  31548. };
  31549. ArcRotateCamera.prototype._getViewMatrix = function () {
  31550. // Compute
  31551. var cosa = Math.cos(this.alpha);
  31552. var sina = Math.sin(this.alpha);
  31553. var cosb = Math.cos(this.beta);
  31554. var sinb = Math.sin(this.beta);
  31555. if (sinb === 0) {
  31556. sinb = 0.0001;
  31557. }
  31558. var target = this._getTargetPosition();
  31559. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  31560. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  31561. if (!this._collider) {
  31562. this._collider = new BABYLON.Collider();
  31563. }
  31564. this._collider.radius = this.collisionRadius;
  31565. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  31566. this._collisionTriggered = true;
  31567. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  31568. }
  31569. else {
  31570. this.position.copyFrom(this._newPosition);
  31571. var up = this.upVector;
  31572. if (this.allowUpsideDown && sinb < 0) {
  31573. up = up.clone();
  31574. up = up.negate();
  31575. }
  31576. if (this.getScene().useRightHandedSystem) {
  31577. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  31578. }
  31579. else {
  31580. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  31581. }
  31582. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  31583. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  31584. }
  31585. this._currentTarget = target;
  31586. return this._viewMatrix;
  31587. };
  31588. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  31589. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  31590. meshes = meshes || this.getScene().meshes;
  31591. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  31592. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  31593. this.radius = distance * this.zoomOnFactor;
  31594. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  31595. };
  31596. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  31597. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  31598. var meshesOrMinMaxVector;
  31599. var distance;
  31600. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  31601. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  31602. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  31603. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  31604. }
  31605. else {
  31606. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  31607. distance = meshesOrMinMaxVectorAndDistance.distance;
  31608. }
  31609. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  31610. if (!doNotUpdateMaxZ) {
  31611. this.maxZ = distance * 2;
  31612. }
  31613. };
  31614. /**
  31615. * @override
  31616. * Override Camera.createRigCamera
  31617. */
  31618. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  31619. var alphaShift;
  31620. switch (this.cameraRigMode) {
  31621. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  31622. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  31623. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  31624. case BABYLON.Camera.RIG_MODE_VR:
  31625. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  31626. break;
  31627. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  31628. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  31629. break;
  31630. }
  31631. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  31632. rigCam._cameraRigParams = {};
  31633. return rigCam;
  31634. };
  31635. /**
  31636. * @override
  31637. * Override Camera._updateRigCameras
  31638. */
  31639. ArcRotateCamera.prototype._updateRigCameras = function () {
  31640. var camLeft = this._rigCameras[0];
  31641. var camRight = this._rigCameras[1];
  31642. camLeft.beta = camRight.beta = this.beta;
  31643. camLeft.radius = camRight.radius = this.radius;
  31644. switch (this.cameraRigMode) {
  31645. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  31646. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  31647. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  31648. case BABYLON.Camera.RIG_MODE_VR:
  31649. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  31650. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  31651. break;
  31652. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  31653. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  31654. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  31655. break;
  31656. }
  31657. _super.prototype._updateRigCameras.call(this);
  31658. };
  31659. ArcRotateCamera.prototype.dispose = function () {
  31660. this.inputs.clear();
  31661. _super.prototype.dispose.call(this);
  31662. };
  31663. ArcRotateCamera.prototype.getClassName = function () {
  31664. return "ArcRotateCamera";
  31665. };
  31666. return ArcRotateCamera;
  31667. }(BABYLON.TargetCamera));
  31668. __decorate([
  31669. BABYLON.serialize()
  31670. ], ArcRotateCamera.prototype, "alpha", void 0);
  31671. __decorate([
  31672. BABYLON.serialize()
  31673. ], ArcRotateCamera.prototype, "beta", void 0);
  31674. __decorate([
  31675. BABYLON.serialize()
  31676. ], ArcRotateCamera.prototype, "radius", void 0);
  31677. __decorate([
  31678. BABYLON.serializeAsVector3("target")
  31679. ], ArcRotateCamera.prototype, "_target", void 0);
  31680. __decorate([
  31681. BABYLON.serialize()
  31682. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  31683. __decorate([
  31684. BABYLON.serialize()
  31685. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  31686. __decorate([
  31687. BABYLON.serialize()
  31688. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  31689. __decorate([
  31690. BABYLON.serialize()
  31691. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  31692. __decorate([
  31693. BABYLON.serialize()
  31694. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  31695. __decorate([
  31696. BABYLON.serialize()
  31697. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  31698. __decorate([
  31699. BABYLON.serialize()
  31700. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  31701. __decorate([
  31702. BABYLON.serialize()
  31703. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  31704. __decorate([
  31705. BABYLON.serialize()
  31706. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  31707. __decorate([
  31708. BABYLON.serialize()
  31709. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  31710. __decorate([
  31711. BABYLON.serialize()
  31712. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  31713. __decorate([
  31714. BABYLON.serialize()
  31715. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  31716. __decorate([
  31717. BABYLON.serialize()
  31718. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  31719. BABYLON.ArcRotateCamera = ArcRotateCamera;
  31720. })(BABYLON || (BABYLON = {}));
  31721. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  31722. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  31723. var BABYLON;
  31724. (function (BABYLON) {
  31725. var ArcRotateCameraInputsManager = (function (_super) {
  31726. __extends(ArcRotateCameraInputsManager, _super);
  31727. function ArcRotateCameraInputsManager(camera) {
  31728. return _super.call(this, camera) || this;
  31729. }
  31730. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  31731. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  31732. return this;
  31733. };
  31734. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  31735. this.add(new BABYLON.ArcRotateCameraPointersInput());
  31736. return this;
  31737. };
  31738. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  31739. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  31740. return this;
  31741. };
  31742. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  31743. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  31744. return this;
  31745. };
  31746. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  31747. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  31748. return this;
  31749. };
  31750. return ArcRotateCameraInputsManager;
  31751. }(BABYLON.CameraInputsManager));
  31752. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  31753. })(BABYLON || (BABYLON = {}));
  31754. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  31755. var BABYLON;
  31756. (function (BABYLON) {
  31757. var HemisphericLight = (function (_super) {
  31758. __extends(HemisphericLight, _super);
  31759. /**
  31760. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  31761. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  31762. * The HemisphericLight can't cast shadows.
  31763. * Documentation : http://doc.babylonjs.com/tutorials/lights
  31764. */
  31765. function HemisphericLight(name, direction, scene) {
  31766. var _this = _super.call(this, name, scene) || this;
  31767. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  31768. _this.direction = direction || BABYLON.Vector3.Up();
  31769. return _this;
  31770. }
  31771. HemisphericLight.prototype._buildUniformLayout = function () {
  31772. this._uniformBuffer.addUniform("vLightData", 4);
  31773. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  31774. this._uniformBuffer.addUniform("vLightSpecular", 3);
  31775. this._uniformBuffer.addUniform("vLightGround", 3);
  31776. this._uniformBuffer.addUniform("shadowsInfo", 3);
  31777. this._uniformBuffer.create();
  31778. };
  31779. /**
  31780. * Returns the string "HemisphericLight".
  31781. */
  31782. HemisphericLight.prototype.getClassName = function () {
  31783. return "HemisphericLight";
  31784. };
  31785. /**
  31786. * Sets the HemisphericLight direction towards the passed target (Vector3).
  31787. * Returns the updated direction.
  31788. */
  31789. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  31790. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  31791. return this.direction;
  31792. };
  31793. HemisphericLight.prototype.getShadowGenerator = function () {
  31794. return null;
  31795. };
  31796. /**
  31797. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  31798. * Returns the HemisphericLight.
  31799. */
  31800. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  31801. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  31802. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  31803. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  31804. return this;
  31805. };
  31806. HemisphericLight.prototype._getWorldMatrix = function () {
  31807. if (!this._worldMatrix) {
  31808. this._worldMatrix = BABYLON.Matrix.Identity();
  31809. }
  31810. return this._worldMatrix;
  31811. };
  31812. /**
  31813. * Returns the integer 3.
  31814. */
  31815. HemisphericLight.prototype.getTypeID = function () {
  31816. return 3;
  31817. };
  31818. return HemisphericLight;
  31819. }(BABYLON.Light));
  31820. __decorate([
  31821. BABYLON.serializeAsColor3()
  31822. ], HemisphericLight.prototype, "groundColor", void 0);
  31823. __decorate([
  31824. BABYLON.serializeAsVector3()
  31825. ], HemisphericLight.prototype, "direction", void 0);
  31826. BABYLON.HemisphericLight = HemisphericLight;
  31827. })(BABYLON || (BABYLON = {}));
  31828. //# sourceMappingURL=babylon.hemisphericLight.js.map
  31829. var BABYLON;
  31830. (function (BABYLON) {
  31831. var PointLight = (function (_super) {
  31832. __extends(PointLight, _super);
  31833. /**
  31834. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  31835. * A PointLight emits the light in every direction.
  31836. * It can cast shadows.
  31837. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  31838. * ```javascript
  31839. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  31840. * ```
  31841. * Documentation : http://doc.babylonjs.com/tutorials/lights
  31842. */
  31843. function PointLight(name, position, scene) {
  31844. var _this = _super.call(this, name, scene) || this;
  31845. _this.position = position;
  31846. return _this;
  31847. }
  31848. PointLight.prototype._buildUniformLayout = function () {
  31849. this._uniformBuffer.addUniform("vLightData", 4);
  31850. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  31851. this._uniformBuffer.addUniform("vLightSpecular", 3);
  31852. this._uniformBuffer.addUniform("shadowsInfo", 3);
  31853. this._uniformBuffer.create();
  31854. };
  31855. /**
  31856. * Returns the string "PointLight"
  31857. */
  31858. PointLight.prototype.getClassName = function () {
  31859. return "PointLight";
  31860. };
  31861. /**
  31862. * Returns a Vector3, the PointLight absolute position in the World.
  31863. */
  31864. PointLight.prototype.getAbsolutePosition = function () {
  31865. return this.transformedPosition ? this.transformedPosition : this.position;
  31866. };
  31867. /**
  31868. * Computes the PointLight transformed position if parented. Returns true if ok, false if not parented.
  31869. */
  31870. PointLight.prototype.computeTransformedPosition = function () {
  31871. if (this.parent && this.parent.getWorldMatrix) {
  31872. if (!this.transformedPosition) {
  31873. this.transformedPosition = BABYLON.Vector3.Zero();
  31874. }
  31875. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  31876. return true;
  31877. }
  31878. return false;
  31879. };
  31880. /**
  31881. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  31882. * Returns the PointLight.
  31883. */
  31884. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  31885. if (this.parent && this.parent.getWorldMatrix) {
  31886. this.computeTransformedPosition();
  31887. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  31888. return this;
  31889. }
  31890. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  31891. return this;
  31892. };
  31893. /**
  31894. * Boolean : returns true by default.
  31895. */
  31896. PointLight.prototype.needCube = function () {
  31897. return true;
  31898. };
  31899. /**
  31900. * Boolean : returns false by default.
  31901. */
  31902. PointLight.prototype.needRefreshPerFrame = function () {
  31903. return false;
  31904. };
  31905. /**
  31906. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  31907. */
  31908. PointLight.prototype.getShadowDirection = function (faceIndex) {
  31909. switch (faceIndex) {
  31910. case 0:
  31911. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  31912. case 1:
  31913. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  31914. case 2:
  31915. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  31916. case 3:
  31917. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  31918. case 4:
  31919. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  31920. case 5:
  31921. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  31922. }
  31923. return BABYLON.Vector3.Zero();
  31924. };
  31925. /**
  31926. * Return the depth scale used for the shadow map.
  31927. */
  31928. PointLight.prototype.getDepthScale = function () {
  31929. return 30.0;
  31930. };
  31931. /**
  31932. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  31933. * - fov = PI / 2
  31934. * - aspect ratio : 1.0
  31935. * - z-near and far equal to the active camera minZ and maxZ.
  31936. * Returns the PointLight.
  31937. */
  31938. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  31939. if (this.customProjectionMatrixBuilder) {
  31940. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  31941. }
  31942. else {
  31943. var activeCamera = this.getScene().activeCamera;
  31944. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  31945. }
  31946. return this;
  31947. };
  31948. PointLight.prototype._getWorldMatrix = function () {
  31949. if (!this._worldMatrix) {
  31950. this._worldMatrix = BABYLON.Matrix.Identity();
  31951. }
  31952. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  31953. return this._worldMatrix;
  31954. };
  31955. /**
  31956. * Returns the integer 0.
  31957. */
  31958. PointLight.prototype.getTypeID = function () {
  31959. return 0;
  31960. };
  31961. return PointLight;
  31962. }(BABYLON.Light));
  31963. __decorate([
  31964. BABYLON.serializeAsVector3()
  31965. ], PointLight.prototype, "position", void 0);
  31966. __decorate([
  31967. BABYLON.serialize()
  31968. ], PointLight.prototype, "shadowMinZ", void 0);
  31969. __decorate([
  31970. BABYLON.serialize()
  31971. ], PointLight.prototype, "shadowMaxZ", void 0);
  31972. BABYLON.PointLight = PointLight;
  31973. })(BABYLON || (BABYLON = {}));
  31974. //# sourceMappingURL=babylon.pointLight.js.map
  31975. /// <reference path="babylon.light.ts" />
  31976. var BABYLON;
  31977. (function (BABYLON) {
  31978. var DirectionalLight = (function (_super) {
  31979. __extends(DirectionalLight, _super);
  31980. /**
  31981. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  31982. * The directional light is emitted from everywhere in the given direction.
  31983. * It can cast shawdows.
  31984. * Documentation : http://doc.babylonjs.com/tutorials/lights
  31985. */
  31986. function DirectionalLight(name, direction, scene) {
  31987. var _this = _super.call(this, name, scene) || this;
  31988. _this.shadowOrthoScale = 0.5;
  31989. _this.autoUpdateExtends = true;
  31990. // Cache
  31991. _this._orthoLeft = Number.MAX_VALUE;
  31992. _this._orthoRight = Number.MIN_VALUE;
  31993. _this._orthoTop = Number.MIN_VALUE;
  31994. _this._orthoBottom = Number.MAX_VALUE;
  31995. _this.position = direction.scale(-1.0);
  31996. _this.direction = direction;
  31997. return _this;
  31998. }
  31999. DirectionalLight.prototype._buildUniformLayout = function () {
  32000. this._uniformBuffer.addUniform("vLightData", 4);
  32001. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  32002. this._uniformBuffer.addUniform("vLightSpecular", 3);
  32003. this._uniformBuffer.addUniform("shadowsInfo", 3);
  32004. this._uniformBuffer.create();
  32005. };
  32006. /**
  32007. * Returns the string "DirectionalLight".
  32008. */
  32009. DirectionalLight.prototype.getClassName = function () {
  32010. return "DirectionalLight";
  32011. };
  32012. /**
  32013. * Returns the DirectionalLight absolute position in the World.
  32014. */
  32015. DirectionalLight.prototype.getAbsolutePosition = function () {
  32016. return this.transformedPosition ? this.transformedPosition : this.position;
  32017. };
  32018. /**
  32019. * Sets the DirectionalLight direction toward the passed target (Vector3).
  32020. * Returns the updated DirectionalLight direction (Vector3).
  32021. */
  32022. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  32023. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  32024. return this.direction;
  32025. };
  32026. /**
  32027. * Return the depth scale used for the shadow map.
  32028. */
  32029. DirectionalLight.prototype.getDepthScale = function () {
  32030. return 30.0;
  32031. };
  32032. /**
  32033. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  32034. * Returns the DirectionalLight.
  32035. */
  32036. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  32037. if (this.customProjectionMatrixBuilder) {
  32038. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  32039. }
  32040. else {
  32041. var activeCamera = this.getScene().activeCamera;
  32042. // Check extends
  32043. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  32044. var tempVector3 = BABYLON.Vector3.Zero();
  32045. this._orthoLeft = Number.MAX_VALUE;
  32046. this._orthoRight = Number.MIN_VALUE;
  32047. this._orthoTop = Number.MIN_VALUE;
  32048. this._orthoBottom = Number.MAX_VALUE;
  32049. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  32050. var mesh = renderList[meshIndex];
  32051. if (!mesh) {
  32052. continue;
  32053. }
  32054. var boundingInfo = mesh.getBoundingInfo();
  32055. if (!boundingInfo) {
  32056. continue;
  32057. }
  32058. var boundingBox = boundingInfo.boundingBox;
  32059. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  32060. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  32061. if (tempVector3.x < this._orthoLeft)
  32062. this._orthoLeft = tempVector3.x;
  32063. if (tempVector3.y < this._orthoBottom)
  32064. this._orthoBottom = tempVector3.y;
  32065. if (tempVector3.x > this._orthoRight)
  32066. this._orthoRight = tempVector3.x;
  32067. if (tempVector3.y > this._orthoTop)
  32068. this._orthoTop = tempVector3.y;
  32069. }
  32070. }
  32071. }
  32072. var xOffset = this._orthoRight - this._orthoLeft;
  32073. var yOffset = this._orthoTop - this._orthoBottom;
  32074. BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  32075. }
  32076. return this;
  32077. };
  32078. /**
  32079. * Boolean : true by default.
  32080. */
  32081. DirectionalLight.prototype.needRefreshPerFrame = function () {
  32082. return true;
  32083. };
  32084. /**
  32085. * Boolean : false by default.
  32086. */
  32087. DirectionalLight.prototype.needCube = function () {
  32088. return false;
  32089. };
  32090. /**
  32091. * Returns the light direction (Vector3) for any passed face index.
  32092. */
  32093. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  32094. return this.direction;
  32095. };
  32096. /**
  32097. * Computes the light transformed position in case the light is parented. Returns true if parented, else false.
  32098. */
  32099. DirectionalLight.prototype.computeTransformedPosition = function () {
  32100. if (this.parent && this.parent.getWorldMatrix) {
  32101. if (!this.transformedPosition) {
  32102. this.transformedPosition = BABYLON.Vector3.Zero();
  32103. }
  32104. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  32105. return true;
  32106. }
  32107. return false;
  32108. };
  32109. /**
  32110. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  32111. * Returns the DirectionalLight.
  32112. */
  32113. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  32114. if (this.parent && this.parent.getWorldMatrix) {
  32115. if (!this._transformedDirection) {
  32116. this._transformedDirection = BABYLON.Vector3.Zero();
  32117. }
  32118. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  32119. this._uniformBuffer.updateFloat4("vLightData", this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1, lightIndex);
  32120. return this;
  32121. }
  32122. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  32123. return this;
  32124. };
  32125. DirectionalLight.prototype._getWorldMatrix = function () {
  32126. if (!this._worldMatrix) {
  32127. this._worldMatrix = BABYLON.Matrix.Identity();
  32128. }
  32129. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  32130. return this._worldMatrix;
  32131. };
  32132. /**
  32133. * Returns the integer 1.
  32134. */
  32135. DirectionalLight.prototype.getTypeID = function () {
  32136. return 1;
  32137. };
  32138. return DirectionalLight;
  32139. }(BABYLON.Light));
  32140. __decorate([
  32141. BABYLON.serializeAsVector3()
  32142. ], DirectionalLight.prototype, "position", void 0);
  32143. __decorate([
  32144. BABYLON.serializeAsVector3()
  32145. ], DirectionalLight.prototype, "direction", void 0);
  32146. __decorate([
  32147. BABYLON.serialize()
  32148. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  32149. __decorate([
  32150. BABYLON.serialize()
  32151. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  32152. __decorate([
  32153. BABYLON.serialize()
  32154. ], DirectionalLight.prototype, "shadowMinZ", void 0);
  32155. __decorate([
  32156. BABYLON.serialize()
  32157. ], DirectionalLight.prototype, "shadowMaxZ", void 0);
  32158. BABYLON.DirectionalLight = DirectionalLight;
  32159. })(BABYLON || (BABYLON = {}));
  32160. //# sourceMappingURL=babylon.directionalLight.js.map
  32161. var BABYLON;
  32162. (function (BABYLON) {
  32163. var SpotLight = (function (_super) {
  32164. __extends(SpotLight, _super);
  32165. /**
  32166. * Creates a SpotLight object in the scene with the passed parameters :
  32167. * - `position` (Vector3) is the initial SpotLight position,
  32168. * - `direction` (Vector3) is the initial SpotLight direction,
  32169. * - `angle` (float, in radians) is the spot light cone angle,
  32170. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  32171. * A spot light is a simply light oriented cone.
  32172. * It can cast shadows.
  32173. * Documentation : http://doc.babylonjs.com/tutorials/lights
  32174. */
  32175. function SpotLight(name, position, direction, angle, exponent, scene) {
  32176. var _this = _super.call(this, name, scene) || this;
  32177. _this.position = position;
  32178. _this.direction = direction;
  32179. _this.angle = angle;
  32180. _this.exponent = exponent;
  32181. return _this;
  32182. }
  32183. SpotLight.prototype._buildUniformLayout = function () {
  32184. this._uniformBuffer.addUniform("vLightData", 4);
  32185. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  32186. this._uniformBuffer.addUniform("vLightSpecular", 3);
  32187. this._uniformBuffer.addUniform("vLightDirection", 3);
  32188. this._uniformBuffer.addUniform("shadowsInfo", 3);
  32189. this._uniformBuffer.create();
  32190. };
  32191. /**
  32192. * Returns the string "SpotLight".
  32193. */
  32194. SpotLight.prototype.getClassName = function () {
  32195. return "SpotLight";
  32196. };
  32197. /**
  32198. * Returns the SpotLight absolute position in the World (Vector3).
  32199. */
  32200. SpotLight.prototype.getAbsolutePosition = function () {
  32201. return this.transformedPosition ? this.transformedPosition : this.position;
  32202. };
  32203. /**
  32204. * Return the depth scale used for the shadow map.
  32205. */
  32206. SpotLight.prototype.getDepthScale = function () {
  32207. return 30.0;
  32208. };
  32209. /**
  32210. * Sets the passed matrix "matrix" as perspective projection matrix for the shadows and the passed view matrix with the fov equal to the SpotLight angle and and aspect ratio of 1.0.
  32211. * Returns the SpotLight.
  32212. */
  32213. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  32214. if (this.customProjectionMatrixBuilder) {
  32215. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  32216. }
  32217. else {
  32218. var activeCamera = this.getScene().activeCamera;
  32219. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  32220. }
  32221. return this;
  32222. };
  32223. /**
  32224. * Boolean : false by default.
  32225. */
  32226. SpotLight.prototype.needCube = function () {
  32227. return false;
  32228. };
  32229. /**
  32230. * Boolean : false by default.
  32231. */
  32232. SpotLight.prototype.needRefreshPerFrame = function () {
  32233. return false;
  32234. };
  32235. /**
  32236. * Returns the SpotLight direction (Vector3) for any passed face index.
  32237. */
  32238. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  32239. return this.direction;
  32240. };
  32241. /**
  32242. * Updates the SpotLight direction towards the passed target (Vector3).
  32243. * Returns the updated direction.
  32244. */
  32245. SpotLight.prototype.setDirectionToTarget = function (target) {
  32246. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  32247. return this.direction;
  32248. };
  32249. /**
  32250. * Computes the SpotLight transformed position if parented. Returns true if parented, else false.
  32251. */
  32252. SpotLight.prototype.computeTransformedPosition = function () {
  32253. if (this.parent && this.parent.getWorldMatrix) {
  32254. if (!this.transformedPosition) {
  32255. this.transformedPosition = BABYLON.Vector3.Zero();
  32256. }
  32257. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  32258. return true;
  32259. }
  32260. return false;
  32261. };
  32262. /**
  32263. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  32264. * Return the SpotLight.
  32265. */
  32266. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  32267. var normalizeDirection;
  32268. if (this.parent && this.parent.getWorldMatrix) {
  32269. if (!this._transformedDirection) {
  32270. this._transformedDirection = BABYLON.Vector3.Zero();
  32271. }
  32272. this.computeTransformedPosition();
  32273. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  32274. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  32275. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  32276. }
  32277. else {
  32278. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  32279. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  32280. }
  32281. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  32282. return this;
  32283. };
  32284. SpotLight.prototype._getWorldMatrix = function () {
  32285. if (!this._worldMatrix) {
  32286. this._worldMatrix = BABYLON.Matrix.Identity();
  32287. }
  32288. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  32289. return this._worldMatrix;
  32290. };
  32291. /**
  32292. * Returns the integer 2.
  32293. */
  32294. SpotLight.prototype.getTypeID = function () {
  32295. return 2;
  32296. };
  32297. /**
  32298. * Returns the SpotLight rotation (Vector3).
  32299. */
  32300. SpotLight.prototype.getRotation = function () {
  32301. this.direction.normalize();
  32302. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  32303. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  32304. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  32305. };
  32306. return SpotLight;
  32307. }(BABYLON.Light));
  32308. __decorate([
  32309. BABYLON.serializeAsVector3()
  32310. ], SpotLight.prototype, "position", void 0);
  32311. __decorate([
  32312. BABYLON.serializeAsVector3()
  32313. ], SpotLight.prototype, "direction", void 0);
  32314. __decorate([
  32315. BABYLON.serialize()
  32316. ], SpotLight.prototype, "angle", void 0);
  32317. __decorate([
  32318. BABYLON.serialize()
  32319. ], SpotLight.prototype, "exponent", void 0);
  32320. __decorate([
  32321. BABYLON.serialize()
  32322. ], SpotLight.prototype, "shadowMinZ", void 0);
  32323. __decorate([
  32324. BABYLON.serialize()
  32325. ], SpotLight.prototype, "shadowMaxZ", void 0);
  32326. BABYLON.SpotLight = SpotLight;
  32327. })(BABYLON || (BABYLON = {}));
  32328. //# sourceMappingURL=babylon.spotLight.js.map
  32329. var BABYLON;
  32330. (function (BABYLON) {
  32331. var AnimationRange = (function () {
  32332. function AnimationRange(name, from, to) {
  32333. this.name = name;
  32334. this.from = from;
  32335. this.to = to;
  32336. }
  32337. AnimationRange.prototype.clone = function () {
  32338. return new AnimationRange(this.name, this.from, this.to);
  32339. };
  32340. return AnimationRange;
  32341. }());
  32342. BABYLON.AnimationRange = AnimationRange;
  32343. /**
  32344. * Composed of a frame, and an action function
  32345. */
  32346. var AnimationEvent = (function () {
  32347. function AnimationEvent(frame, action, onlyOnce) {
  32348. this.frame = frame;
  32349. this.action = action;
  32350. this.onlyOnce = onlyOnce;
  32351. this.isDone = false;
  32352. }
  32353. return AnimationEvent;
  32354. }());
  32355. BABYLON.AnimationEvent = AnimationEvent;
  32356. var PathCursor = (function () {
  32357. function PathCursor(path) {
  32358. this.path = path;
  32359. this._onchange = new Array();
  32360. this.value = 0;
  32361. this.animations = new Array();
  32362. }
  32363. PathCursor.prototype.getPoint = function () {
  32364. var point = this.path.getPointAtLengthPosition(this.value);
  32365. return new BABYLON.Vector3(point.x, 0, point.y);
  32366. };
  32367. PathCursor.prototype.moveAhead = function (step) {
  32368. if (step === void 0) { step = 0.002; }
  32369. this.move(step);
  32370. return this;
  32371. };
  32372. PathCursor.prototype.moveBack = function (step) {
  32373. if (step === void 0) { step = 0.002; }
  32374. this.move(-step);
  32375. return this;
  32376. };
  32377. PathCursor.prototype.move = function (step) {
  32378. if (Math.abs(step) > 1) {
  32379. throw "step size should be less than 1.";
  32380. }
  32381. this.value += step;
  32382. this.ensureLimits();
  32383. this.raiseOnChange();
  32384. return this;
  32385. };
  32386. PathCursor.prototype.ensureLimits = function () {
  32387. while (this.value > 1) {
  32388. this.value -= 1;
  32389. }
  32390. while (this.value < 0) {
  32391. this.value += 1;
  32392. }
  32393. return this;
  32394. };
  32395. // used by animation engine
  32396. PathCursor.prototype.markAsDirty = function (propertyName) {
  32397. this.ensureLimits();
  32398. this.raiseOnChange();
  32399. return this;
  32400. };
  32401. PathCursor.prototype.raiseOnChange = function () {
  32402. var _this = this;
  32403. this._onchange.forEach(function (f) { return f(_this); });
  32404. return this;
  32405. };
  32406. PathCursor.prototype.onchange = function (f) {
  32407. this._onchange.push(f);
  32408. return this;
  32409. };
  32410. return PathCursor;
  32411. }());
  32412. BABYLON.PathCursor = PathCursor;
  32413. var Animation = (function () {
  32414. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  32415. this.name = name;
  32416. this.targetProperty = targetProperty;
  32417. this.framePerSecond = framePerSecond;
  32418. this.dataType = dataType;
  32419. this.loopMode = loopMode;
  32420. this.enableBlending = enableBlending;
  32421. this._offsetsCache = {};
  32422. this._highLimitsCache = {};
  32423. this._stopped = false;
  32424. this._blendingFactor = 0;
  32425. // The set of event that will be linked to this animation
  32426. this._events = new Array();
  32427. this.allowMatricesInterpolation = false;
  32428. this.blendingSpeed = 0.01;
  32429. this._ranges = {};
  32430. this.targetPropertyPath = targetProperty.split(".");
  32431. this.dataType = dataType;
  32432. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  32433. }
  32434. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  32435. var dataType = undefined;
  32436. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  32437. dataType = Animation.ANIMATIONTYPE_FLOAT;
  32438. }
  32439. else if (from instanceof BABYLON.Quaternion) {
  32440. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  32441. }
  32442. else if (from instanceof BABYLON.Vector3) {
  32443. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  32444. }
  32445. else if (from instanceof BABYLON.Vector2) {
  32446. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  32447. }
  32448. else if (from instanceof BABYLON.Color3) {
  32449. dataType = Animation.ANIMATIONTYPE_COLOR3;
  32450. }
  32451. else if (from instanceof BABYLON.Size) {
  32452. dataType = Animation.ANIMATIONTYPE_SIZE;
  32453. }
  32454. if (dataType == undefined) {
  32455. return null;
  32456. }
  32457. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  32458. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  32459. animation.setKeys(keys);
  32460. if (easingFunction !== undefined) {
  32461. animation.setEasingFunction(easingFunction);
  32462. }
  32463. return animation;
  32464. };
  32465. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  32466. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  32467. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  32468. };
  32469. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  32470. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  32471. node.animations.push(animation);
  32472. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  32473. };
  32474. // Methods
  32475. /**
  32476. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  32477. */
  32478. Animation.prototype.toString = function (fullDetails) {
  32479. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  32480. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  32481. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  32482. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  32483. if (fullDetails) {
  32484. ret += ", Ranges: {";
  32485. var first = true;
  32486. for (var name in this._ranges) {
  32487. if (first) {
  32488. ret += ", ";
  32489. first = false;
  32490. }
  32491. ret += name;
  32492. }
  32493. ret += "}";
  32494. }
  32495. return ret;
  32496. };
  32497. /**
  32498. * Add an event to this animation.
  32499. */
  32500. Animation.prototype.addEvent = function (event) {
  32501. this._events.push(event);
  32502. };
  32503. /**
  32504. * Remove all events found at the given frame
  32505. * @param frame
  32506. */
  32507. Animation.prototype.removeEvents = function (frame) {
  32508. for (var index = 0; index < this._events.length; index++) {
  32509. if (this._events[index].frame === frame) {
  32510. this._events.splice(index, 1);
  32511. index--;
  32512. }
  32513. }
  32514. };
  32515. Animation.prototype.createRange = function (name, from, to) {
  32516. // check name not already in use; could happen for bones after serialized
  32517. if (!this._ranges[name]) {
  32518. this._ranges[name] = new AnimationRange(name, from, to);
  32519. }
  32520. };
  32521. Animation.prototype.deleteRange = function (name, deleteFrames) {
  32522. if (deleteFrames === void 0) { deleteFrames = true; }
  32523. if (this._ranges[name]) {
  32524. if (deleteFrames) {
  32525. var from = this._ranges[name].from;
  32526. var to = this._ranges[name].to;
  32527. // this loop MUST go high to low for multiple splices to work
  32528. for (var key = this._keys.length - 1; key >= 0; key--) {
  32529. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  32530. this._keys.splice(key, 1);
  32531. }
  32532. }
  32533. }
  32534. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  32535. }
  32536. };
  32537. Animation.prototype.getRange = function (name) {
  32538. return this._ranges[name];
  32539. };
  32540. Animation.prototype.reset = function () {
  32541. this._offsetsCache = {};
  32542. this._highLimitsCache = {};
  32543. this.currentFrame = 0;
  32544. this._blendingFactor = 0;
  32545. this._originalBlendValue = null;
  32546. };
  32547. Animation.prototype.isStopped = function () {
  32548. return this._stopped;
  32549. };
  32550. Animation.prototype.getKeys = function () {
  32551. return this._keys;
  32552. };
  32553. Animation.prototype.getHighestFrame = function () {
  32554. var ret = 0;
  32555. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  32556. if (ret < this._keys[key].frame) {
  32557. ret = this._keys[key].frame;
  32558. }
  32559. }
  32560. return ret;
  32561. };
  32562. Animation.prototype.getEasingFunction = function () {
  32563. return this._easingFunction;
  32564. };
  32565. Animation.prototype.setEasingFunction = function (easingFunction) {
  32566. this._easingFunction = easingFunction;
  32567. };
  32568. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  32569. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  32570. };
  32571. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  32572. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  32573. };
  32574. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  32575. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  32576. };
  32577. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  32578. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  32579. };
  32580. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  32581. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  32582. };
  32583. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  32584. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  32585. };
  32586. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  32587. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  32588. };
  32589. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  32590. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  32591. };
  32592. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  32593. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  32594. };
  32595. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  32596. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  32597. };
  32598. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  32599. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  32600. };
  32601. Animation.prototype.clone = function () {
  32602. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  32603. clone.enableBlending = this.enableBlending;
  32604. clone.blendingSpeed = this.blendingSpeed;
  32605. if (this._keys) {
  32606. clone.setKeys(this._keys);
  32607. }
  32608. if (this._ranges) {
  32609. clone._ranges = {};
  32610. for (var name in this._ranges) {
  32611. clone._ranges[name] = this._ranges[name].clone();
  32612. }
  32613. }
  32614. return clone;
  32615. };
  32616. Animation.prototype.setKeys = function (values) {
  32617. this._keys = values.slice(0);
  32618. this._offsetsCache = {};
  32619. this._highLimitsCache = {};
  32620. };
  32621. Animation.prototype._getKeyValue = function (value) {
  32622. if (typeof value === "function") {
  32623. return value();
  32624. }
  32625. return value;
  32626. };
  32627. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  32628. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  32629. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  32630. }
  32631. this.currentFrame = currentFrame;
  32632. // Try to get a hash to find the right key
  32633. var startKeyIndex = 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));
  32634. if (this._keys[startKeyIndex].frame >= currentFrame) {
  32635. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  32636. startKeyIndex--;
  32637. }
  32638. }
  32639. for (var key = startKeyIndex; key < this._keys.length; key++) {
  32640. var endKey = this._keys[key + 1];
  32641. if (endKey.frame >= currentFrame) {
  32642. var startKey = this._keys[key];
  32643. var startValue = this._getKeyValue(startKey.value);
  32644. var endValue = this._getKeyValue(endKey.value);
  32645. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  32646. var frameDelta = endKey.frame - startKey.frame;
  32647. // gradient : percent of currentFrame between the frame inf and the frame sup
  32648. var gradient = (currentFrame - startKey.frame) / frameDelta;
  32649. // check for easingFunction and correction of gradient
  32650. if (this._easingFunction != null) {
  32651. gradient = this._easingFunction.ease(gradient);
  32652. }
  32653. switch (this.dataType) {
  32654. // Float
  32655. case Animation.ANIMATIONTYPE_FLOAT:
  32656. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  32657. switch (loopMode) {
  32658. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32659. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32660. return floatValue;
  32661. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32662. return offsetValue * repeatCount + floatValue;
  32663. }
  32664. break;
  32665. // Quaternion
  32666. case Animation.ANIMATIONTYPE_QUATERNION:
  32667. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  32668. switch (loopMode) {
  32669. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32670. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32671. return quatValue;
  32672. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32673. return quatValue.add(offsetValue.scale(repeatCount));
  32674. }
  32675. return quatValue;
  32676. // Vector3
  32677. case Animation.ANIMATIONTYPE_VECTOR3:
  32678. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  32679. switch (loopMode) {
  32680. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32681. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32682. return vec3Value;
  32683. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32684. return vec3Value.add(offsetValue.scale(repeatCount));
  32685. }
  32686. // Vector2
  32687. case Animation.ANIMATIONTYPE_VECTOR2:
  32688. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  32689. switch (loopMode) {
  32690. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32691. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32692. return vec2Value;
  32693. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32694. return vec2Value.add(offsetValue.scale(repeatCount));
  32695. }
  32696. // Size
  32697. case Animation.ANIMATIONTYPE_SIZE:
  32698. switch (loopMode) {
  32699. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32700. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32701. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  32702. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32703. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32704. }
  32705. // Color3
  32706. case Animation.ANIMATIONTYPE_COLOR3:
  32707. switch (loopMode) {
  32708. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32709. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32710. return this.color3InterpolateFunction(startValue, endValue, gradient);
  32711. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32712. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32713. }
  32714. // Matrix
  32715. case Animation.ANIMATIONTYPE_MATRIX:
  32716. switch (loopMode) {
  32717. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32718. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32719. if (this.allowMatricesInterpolation) {
  32720. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  32721. }
  32722. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32723. return startValue;
  32724. }
  32725. default:
  32726. break;
  32727. }
  32728. break;
  32729. }
  32730. }
  32731. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  32732. };
  32733. Animation.prototype.setValue = function (currentValue, blend) {
  32734. if (blend === void 0) { blend = false; }
  32735. // Set value
  32736. var path;
  32737. var destination;
  32738. if (this.targetPropertyPath.length > 1) {
  32739. var property = this._target[this.targetPropertyPath[0]];
  32740. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  32741. property = property[this.targetPropertyPath[index]];
  32742. }
  32743. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  32744. destination = property;
  32745. }
  32746. else {
  32747. path = this.targetPropertyPath[0];
  32748. destination = this._target;
  32749. }
  32750. // Blending
  32751. if (this.enableBlending && this._blendingFactor <= 1.0) {
  32752. if (!this._originalBlendValue) {
  32753. if (destination[path].clone) {
  32754. this._originalBlendValue = destination[path].clone();
  32755. }
  32756. else {
  32757. this._originalBlendValue = destination[path];
  32758. }
  32759. }
  32760. if (this._originalBlendValue.prototype) {
  32761. if (this._originalBlendValue.prototype.Lerp) {
  32762. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  32763. }
  32764. else {
  32765. destination[path] = currentValue;
  32766. }
  32767. }
  32768. else if (this._originalBlendValue.m) {
  32769. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  32770. }
  32771. else {
  32772. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  32773. }
  32774. this._blendingFactor += this.blendingSpeed;
  32775. }
  32776. else {
  32777. destination[path] = currentValue;
  32778. }
  32779. if (this._target.markAsDirty) {
  32780. this._target.markAsDirty(this.targetProperty);
  32781. }
  32782. };
  32783. Animation.prototype.goToFrame = function (frame) {
  32784. if (frame < this._keys[0].frame) {
  32785. frame = this._keys[0].frame;
  32786. }
  32787. else if (frame > this._keys[this._keys.length - 1].frame) {
  32788. frame = this._keys[this._keys.length - 1].frame;
  32789. }
  32790. var currentValue = this._interpolate(frame, 0, this.loopMode);
  32791. this.setValue(currentValue);
  32792. };
  32793. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  32794. if (blend === void 0) { blend = false; }
  32795. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  32796. this._stopped = true;
  32797. return false;
  32798. }
  32799. var returnValue = true;
  32800. // Adding a start key at frame 0 if missing
  32801. if (this._keys[0].frame !== 0) {
  32802. var newKey = { frame: 0, value: this._keys[0].value };
  32803. this._keys.splice(0, 0, newKey);
  32804. }
  32805. // Check limits
  32806. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  32807. from = this._keys[0].frame;
  32808. }
  32809. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  32810. to = this._keys[this._keys.length - 1].frame;
  32811. }
  32812. //to and from cannot be the same key
  32813. if (from === to) {
  32814. from++;
  32815. }
  32816. // Compute ratio
  32817. var range = to - from;
  32818. var offsetValue;
  32819. // ratio represents the frame delta between from and to
  32820. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  32821. var highLimitValue = 0;
  32822. if (ratio > range && !loop) {
  32823. returnValue = false;
  32824. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  32825. }
  32826. else {
  32827. // Get max value if required
  32828. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  32829. var keyOffset = to.toString() + from.toString();
  32830. if (!this._offsetsCache[keyOffset]) {
  32831. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  32832. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  32833. switch (this.dataType) {
  32834. // Float
  32835. case Animation.ANIMATIONTYPE_FLOAT:
  32836. this._offsetsCache[keyOffset] = toValue - fromValue;
  32837. break;
  32838. // Quaternion
  32839. case Animation.ANIMATIONTYPE_QUATERNION:
  32840. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32841. break;
  32842. // Vector3
  32843. case Animation.ANIMATIONTYPE_VECTOR3:
  32844. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32845. // Vector2
  32846. case Animation.ANIMATIONTYPE_VECTOR2:
  32847. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32848. // Size
  32849. case Animation.ANIMATIONTYPE_SIZE:
  32850. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32851. // Color3
  32852. case Animation.ANIMATIONTYPE_COLOR3:
  32853. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32854. default:
  32855. break;
  32856. }
  32857. this._highLimitsCache[keyOffset] = toValue;
  32858. }
  32859. highLimitValue = this._highLimitsCache[keyOffset];
  32860. offsetValue = this._offsetsCache[keyOffset];
  32861. }
  32862. }
  32863. if (offsetValue === undefined) {
  32864. switch (this.dataType) {
  32865. // Float
  32866. case Animation.ANIMATIONTYPE_FLOAT:
  32867. offsetValue = 0;
  32868. break;
  32869. // Quaternion
  32870. case Animation.ANIMATIONTYPE_QUATERNION:
  32871. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  32872. break;
  32873. // Vector3
  32874. case Animation.ANIMATIONTYPE_VECTOR3:
  32875. offsetValue = BABYLON.Vector3.Zero();
  32876. break;
  32877. // Vector2
  32878. case Animation.ANIMATIONTYPE_VECTOR2:
  32879. offsetValue = BABYLON.Vector2.Zero();
  32880. break;
  32881. // Size
  32882. case Animation.ANIMATIONTYPE_SIZE:
  32883. offsetValue = BABYLON.Size.Zero();
  32884. break;
  32885. // Color3
  32886. case Animation.ANIMATIONTYPE_COLOR3:
  32887. offsetValue = BABYLON.Color3.Black();
  32888. }
  32889. }
  32890. // Compute value
  32891. var repeatCount = (ratio / range) >> 0;
  32892. var currentFrame = returnValue ? from + ratio % range : to;
  32893. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  32894. // Set value
  32895. this.setValue(currentValue);
  32896. // Check events
  32897. for (var index = 0; index < this._events.length; index++) {
  32898. if (currentFrame >= this._events[index].frame) {
  32899. var event = this._events[index];
  32900. if (!event.isDone) {
  32901. // If event should be done only once, remove it.
  32902. if (event.onlyOnce) {
  32903. this._events.splice(index, 1);
  32904. index--;
  32905. }
  32906. event.isDone = true;
  32907. event.action();
  32908. } // Don't do anything if the event has already be done.
  32909. }
  32910. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  32911. // reset event, the animation is looping
  32912. this._events[index].isDone = false;
  32913. }
  32914. }
  32915. if (!returnValue) {
  32916. this._stopped = true;
  32917. }
  32918. return returnValue;
  32919. };
  32920. Animation.prototype.serialize = function () {
  32921. var serializationObject = {};
  32922. serializationObject.name = this.name;
  32923. serializationObject.property = this.targetProperty;
  32924. serializationObject.framePerSecond = this.framePerSecond;
  32925. serializationObject.dataType = this.dataType;
  32926. serializationObject.loopBehavior = this.loopMode;
  32927. serializationObject.enableBlending = this.enableBlending;
  32928. serializationObject.blendingSpeed = this.blendingSpeed;
  32929. var dataType = this.dataType;
  32930. serializationObject.keys = [];
  32931. var keys = this.getKeys();
  32932. for (var index = 0; index < keys.length; index++) {
  32933. var animationKey = keys[index];
  32934. var key = {};
  32935. key.frame = animationKey.frame;
  32936. switch (dataType) {
  32937. case Animation.ANIMATIONTYPE_FLOAT:
  32938. key.values = [animationKey.value];
  32939. break;
  32940. case Animation.ANIMATIONTYPE_QUATERNION:
  32941. case Animation.ANIMATIONTYPE_MATRIX:
  32942. case Animation.ANIMATIONTYPE_VECTOR3:
  32943. case Animation.ANIMATIONTYPE_COLOR3:
  32944. key.values = animationKey.value.asArray();
  32945. break;
  32946. }
  32947. serializationObject.keys.push(key);
  32948. }
  32949. serializationObject.ranges = [];
  32950. for (var name in this._ranges) {
  32951. var range = {};
  32952. range.name = name;
  32953. range.from = this._ranges[name].from;
  32954. range.to = this._ranges[name].to;
  32955. serializationObject.ranges.push(range);
  32956. }
  32957. return serializationObject;
  32958. };
  32959. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  32960. get: function () {
  32961. return Animation._ANIMATIONTYPE_FLOAT;
  32962. },
  32963. enumerable: true,
  32964. configurable: true
  32965. });
  32966. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  32967. get: function () {
  32968. return Animation._ANIMATIONTYPE_VECTOR3;
  32969. },
  32970. enumerable: true,
  32971. configurable: true
  32972. });
  32973. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  32974. get: function () {
  32975. return Animation._ANIMATIONTYPE_VECTOR2;
  32976. },
  32977. enumerable: true,
  32978. configurable: true
  32979. });
  32980. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  32981. get: function () {
  32982. return Animation._ANIMATIONTYPE_SIZE;
  32983. },
  32984. enumerable: true,
  32985. configurable: true
  32986. });
  32987. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  32988. get: function () {
  32989. return Animation._ANIMATIONTYPE_QUATERNION;
  32990. },
  32991. enumerable: true,
  32992. configurable: true
  32993. });
  32994. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  32995. get: function () {
  32996. return Animation._ANIMATIONTYPE_MATRIX;
  32997. },
  32998. enumerable: true,
  32999. configurable: true
  33000. });
  33001. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  33002. get: function () {
  33003. return Animation._ANIMATIONTYPE_COLOR3;
  33004. },
  33005. enumerable: true,
  33006. configurable: true
  33007. });
  33008. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  33009. get: function () {
  33010. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  33011. },
  33012. enumerable: true,
  33013. configurable: true
  33014. });
  33015. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  33016. get: function () {
  33017. return Animation._ANIMATIONLOOPMODE_CYCLE;
  33018. },
  33019. enumerable: true,
  33020. configurable: true
  33021. });
  33022. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  33023. get: function () {
  33024. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  33025. },
  33026. enumerable: true,
  33027. configurable: true
  33028. });
  33029. Animation.Parse = function (parsedAnimation) {
  33030. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  33031. var dataType = parsedAnimation.dataType;
  33032. var keys = [];
  33033. var data;
  33034. var index;
  33035. if (parsedAnimation.enableBlending) {
  33036. animation.enableBlending = parsedAnimation.enableBlending;
  33037. }
  33038. if (parsedAnimation.blendingSpeed) {
  33039. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  33040. }
  33041. for (index = 0; index < parsedAnimation.keys.length; index++) {
  33042. var key = parsedAnimation.keys[index];
  33043. switch (dataType) {
  33044. case Animation.ANIMATIONTYPE_FLOAT:
  33045. data = key.values[0];
  33046. break;
  33047. case Animation.ANIMATIONTYPE_QUATERNION:
  33048. data = BABYLON.Quaternion.FromArray(key.values);
  33049. break;
  33050. case Animation.ANIMATIONTYPE_MATRIX:
  33051. data = BABYLON.Matrix.FromArray(key.values);
  33052. break;
  33053. case Animation.ANIMATIONTYPE_COLOR3:
  33054. data = BABYLON.Color3.FromArray(key.values);
  33055. break;
  33056. case Animation.ANIMATIONTYPE_VECTOR3:
  33057. default:
  33058. data = BABYLON.Vector3.FromArray(key.values);
  33059. break;
  33060. }
  33061. keys.push({
  33062. frame: key.frame,
  33063. value: data
  33064. });
  33065. }
  33066. animation.setKeys(keys);
  33067. if (parsedAnimation.ranges) {
  33068. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  33069. data = parsedAnimation.ranges[index];
  33070. animation.createRange(data.name, data.from, data.to);
  33071. }
  33072. }
  33073. return animation;
  33074. };
  33075. Animation.AppendSerializedAnimations = function (source, destination) {
  33076. if (source.animations) {
  33077. destination.animations = [];
  33078. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  33079. var animation = source.animations[animationIndex];
  33080. destination.animations.push(animation.serialize());
  33081. }
  33082. }
  33083. };
  33084. return Animation;
  33085. }());
  33086. // Statics
  33087. Animation._ANIMATIONTYPE_FLOAT = 0;
  33088. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  33089. Animation._ANIMATIONTYPE_QUATERNION = 2;
  33090. Animation._ANIMATIONTYPE_MATRIX = 3;
  33091. Animation._ANIMATIONTYPE_COLOR3 = 4;
  33092. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  33093. Animation._ANIMATIONTYPE_SIZE = 6;
  33094. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  33095. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  33096. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  33097. BABYLON.Animation = Animation;
  33098. })(BABYLON || (BABYLON = {}));
  33099. //# sourceMappingURL=babylon.animation.js.map
  33100. var BABYLON;
  33101. (function (BABYLON) {
  33102. var Animatable = (function () {
  33103. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  33104. if (fromFrame === void 0) { fromFrame = 0; }
  33105. if (toFrame === void 0) { toFrame = 100; }
  33106. if (loopAnimation === void 0) { loopAnimation = false; }
  33107. if (speedRatio === void 0) { speedRatio = 1.0; }
  33108. this.target = target;
  33109. this.fromFrame = fromFrame;
  33110. this.toFrame = toFrame;
  33111. this.loopAnimation = loopAnimation;
  33112. this.speedRatio = speedRatio;
  33113. this.onAnimationEnd = onAnimationEnd;
  33114. this._localDelayOffset = null;
  33115. this._pausedDelay = null;
  33116. this._animations = new Array();
  33117. this._paused = false;
  33118. this.animationStarted = false;
  33119. if (animations) {
  33120. this.appendAnimations(target, animations);
  33121. }
  33122. this._scene = scene;
  33123. scene._activeAnimatables.push(this);
  33124. }
  33125. // Methods
  33126. Animatable.prototype.getAnimations = function () {
  33127. return this._animations;
  33128. };
  33129. Animatable.prototype.appendAnimations = function (target, animations) {
  33130. for (var index = 0; index < animations.length; index++) {
  33131. var animation = animations[index];
  33132. animation._target = target;
  33133. this._animations.push(animation);
  33134. }
  33135. };
  33136. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  33137. var animations = this._animations;
  33138. for (var index = 0; index < animations.length; index++) {
  33139. if (animations[index].targetProperty === property) {
  33140. return animations[index];
  33141. }
  33142. }
  33143. return null;
  33144. };
  33145. Animatable.prototype.reset = function () {
  33146. var animations = this._animations;
  33147. for (var index = 0; index < animations.length; index++) {
  33148. animations[index].reset();
  33149. }
  33150. this._localDelayOffset = null;
  33151. this._pausedDelay = null;
  33152. };
  33153. Animatable.prototype.enableBlending = function (blendingSpeed) {
  33154. var animations = this._animations;
  33155. for (var index = 0; index < animations.length; index++) {
  33156. animations[index].enableBlending = true;
  33157. animations[index].blendingSpeed = blendingSpeed;
  33158. }
  33159. };
  33160. Animatable.prototype.disableBlending = function () {
  33161. var animations = this._animations;
  33162. for (var index = 0; index < animations.length; index++) {
  33163. animations[index].enableBlending = false;
  33164. }
  33165. };
  33166. Animatable.prototype.goToFrame = function (frame) {
  33167. var animations = this._animations;
  33168. if (animations[0]) {
  33169. var fps = animations[0].framePerSecond;
  33170. var currentFrame = animations[0].currentFrame;
  33171. var adjustTime = frame - currentFrame;
  33172. var delay = adjustTime * 1000 / fps;
  33173. this._localDelayOffset -= delay;
  33174. }
  33175. for (var index = 0; index < animations.length; index++) {
  33176. animations[index].goToFrame(frame);
  33177. }
  33178. };
  33179. Animatable.prototype.pause = function () {
  33180. if (this._paused) {
  33181. return;
  33182. }
  33183. this._paused = true;
  33184. };
  33185. Animatable.prototype.restart = function () {
  33186. this._paused = false;
  33187. };
  33188. Animatable.prototype.stop = function (animationName) {
  33189. if (animationName) {
  33190. var idx = this._scene._activeAnimatables.indexOf(this);
  33191. if (idx > -1) {
  33192. var animations = this._animations;
  33193. for (var index = animations.length - 1; index >= 0; index--) {
  33194. if (typeof animationName === "string" && animations[index].name != animationName) {
  33195. continue;
  33196. }
  33197. animations[index].reset();
  33198. animations.splice(index, 1);
  33199. }
  33200. if (animations.length == 0) {
  33201. this._scene._activeAnimatables.splice(idx, 1);
  33202. if (this.onAnimationEnd) {
  33203. this.onAnimationEnd();
  33204. }
  33205. }
  33206. }
  33207. }
  33208. else {
  33209. var index = this._scene._activeAnimatables.indexOf(this);
  33210. if (index > -1) {
  33211. this._scene._activeAnimatables.splice(index, 1);
  33212. var animations = this._animations;
  33213. for (var index = 0; index < animations.length; index++) {
  33214. animations[index].reset();
  33215. }
  33216. if (this.onAnimationEnd) {
  33217. this.onAnimationEnd();
  33218. }
  33219. }
  33220. }
  33221. };
  33222. Animatable.prototype._animate = function (delay) {
  33223. if (this._paused) {
  33224. this.animationStarted = false;
  33225. if (this._pausedDelay === null) {
  33226. this._pausedDelay = delay;
  33227. }
  33228. return true;
  33229. }
  33230. if (this._localDelayOffset === null) {
  33231. this._localDelayOffset = delay;
  33232. }
  33233. else if (this._pausedDelay !== null) {
  33234. this._localDelayOffset += delay - this._pausedDelay;
  33235. this._pausedDelay = null;
  33236. }
  33237. // Animating
  33238. var running = false;
  33239. var animations = this._animations;
  33240. var index;
  33241. for (index = 0; index < animations.length; index++) {
  33242. var animation = animations[index];
  33243. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  33244. running = running || isRunning;
  33245. }
  33246. this.animationStarted = running;
  33247. if (!running) {
  33248. // Remove from active animatables
  33249. index = this._scene._activeAnimatables.indexOf(this);
  33250. this._scene._activeAnimatables.splice(index, 1);
  33251. }
  33252. if (!running && this.onAnimationEnd) {
  33253. this.onAnimationEnd();
  33254. this.onAnimationEnd = null;
  33255. }
  33256. return running;
  33257. };
  33258. return Animatable;
  33259. }());
  33260. BABYLON.Animatable = Animatable;
  33261. })(BABYLON || (BABYLON = {}));
  33262. //# sourceMappingURL=babylon.animatable.js.map
  33263. var BABYLON;
  33264. (function (BABYLON) {
  33265. var EasingFunction = (function () {
  33266. function EasingFunction() {
  33267. // Properties
  33268. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  33269. }
  33270. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  33271. get: function () {
  33272. return EasingFunction._EASINGMODE_EASEIN;
  33273. },
  33274. enumerable: true,
  33275. configurable: true
  33276. });
  33277. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  33278. get: function () {
  33279. return EasingFunction._EASINGMODE_EASEOUT;
  33280. },
  33281. enumerable: true,
  33282. configurable: true
  33283. });
  33284. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  33285. get: function () {
  33286. return EasingFunction._EASINGMODE_EASEINOUT;
  33287. },
  33288. enumerable: true,
  33289. configurable: true
  33290. });
  33291. EasingFunction.prototype.setEasingMode = function (easingMode) {
  33292. var n = Math.min(Math.max(easingMode, 0), 2);
  33293. this._easingMode = n;
  33294. };
  33295. EasingFunction.prototype.getEasingMode = function () {
  33296. return this._easingMode;
  33297. };
  33298. EasingFunction.prototype.easeInCore = function (gradient) {
  33299. throw new Error('You must implement this method');
  33300. };
  33301. EasingFunction.prototype.ease = function (gradient) {
  33302. switch (this._easingMode) {
  33303. case EasingFunction.EASINGMODE_EASEIN:
  33304. return this.easeInCore(gradient);
  33305. case EasingFunction.EASINGMODE_EASEOUT:
  33306. return (1 - this.easeInCore(1 - gradient));
  33307. }
  33308. if (gradient >= 0.5) {
  33309. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  33310. }
  33311. return (this.easeInCore(gradient * 2) * 0.5);
  33312. };
  33313. return EasingFunction;
  33314. }());
  33315. //Statics
  33316. EasingFunction._EASINGMODE_EASEIN = 0;
  33317. EasingFunction._EASINGMODE_EASEOUT = 1;
  33318. EasingFunction._EASINGMODE_EASEINOUT = 2;
  33319. BABYLON.EasingFunction = EasingFunction;
  33320. var CircleEase = (function (_super) {
  33321. __extends(CircleEase, _super);
  33322. function CircleEase() {
  33323. return _super !== null && _super.apply(this, arguments) || this;
  33324. }
  33325. CircleEase.prototype.easeInCore = function (gradient) {
  33326. gradient = Math.max(0, Math.min(1, gradient));
  33327. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  33328. };
  33329. return CircleEase;
  33330. }(EasingFunction));
  33331. BABYLON.CircleEase = CircleEase;
  33332. var BackEase = (function (_super) {
  33333. __extends(BackEase, _super);
  33334. function BackEase(amplitude) {
  33335. if (amplitude === void 0) { amplitude = 1; }
  33336. var _this = _super.call(this) || this;
  33337. _this.amplitude = amplitude;
  33338. return _this;
  33339. }
  33340. BackEase.prototype.easeInCore = function (gradient) {
  33341. var num = Math.max(0, this.amplitude);
  33342. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  33343. };
  33344. return BackEase;
  33345. }(EasingFunction));
  33346. BABYLON.BackEase = BackEase;
  33347. var BounceEase = (function (_super) {
  33348. __extends(BounceEase, _super);
  33349. function BounceEase(bounces, bounciness) {
  33350. if (bounces === void 0) { bounces = 3; }
  33351. if (bounciness === void 0) { bounciness = 2; }
  33352. var _this = _super.call(this) || this;
  33353. _this.bounces = bounces;
  33354. _this.bounciness = bounciness;
  33355. return _this;
  33356. }
  33357. BounceEase.prototype.easeInCore = function (gradient) {
  33358. var y = Math.max(0.0, this.bounces);
  33359. var bounciness = this.bounciness;
  33360. if (bounciness <= 1.0) {
  33361. bounciness = 1.001;
  33362. }
  33363. var num9 = Math.pow(bounciness, y);
  33364. var num5 = 1.0 - bounciness;
  33365. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  33366. var num15 = gradient * num4;
  33367. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  33368. var num3 = Math.floor(num65);
  33369. var num13 = num3 + 1.0;
  33370. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  33371. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  33372. var num7 = (num8 + num12) * 0.5;
  33373. var num6 = gradient - num7;
  33374. var num2 = num7 - num8;
  33375. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  33376. };
  33377. return BounceEase;
  33378. }(EasingFunction));
  33379. BABYLON.BounceEase = BounceEase;
  33380. var CubicEase = (function (_super) {
  33381. __extends(CubicEase, _super);
  33382. function CubicEase() {
  33383. return _super !== null && _super.apply(this, arguments) || this;
  33384. }
  33385. CubicEase.prototype.easeInCore = function (gradient) {
  33386. return (gradient * gradient * gradient);
  33387. };
  33388. return CubicEase;
  33389. }(EasingFunction));
  33390. BABYLON.CubicEase = CubicEase;
  33391. var ElasticEase = (function (_super) {
  33392. __extends(ElasticEase, _super);
  33393. function ElasticEase(oscillations, springiness) {
  33394. if (oscillations === void 0) { oscillations = 3; }
  33395. if (springiness === void 0) { springiness = 3; }
  33396. var _this = _super.call(this) || this;
  33397. _this.oscillations = oscillations;
  33398. _this.springiness = springiness;
  33399. return _this;
  33400. }
  33401. ElasticEase.prototype.easeInCore = function (gradient) {
  33402. var num2;
  33403. var num3 = Math.max(0.0, this.oscillations);
  33404. var num = Math.max(0.0, this.springiness);
  33405. if (num == 0) {
  33406. num2 = gradient;
  33407. }
  33408. else {
  33409. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  33410. }
  33411. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  33412. };
  33413. return ElasticEase;
  33414. }(EasingFunction));
  33415. BABYLON.ElasticEase = ElasticEase;
  33416. var ExponentialEase = (function (_super) {
  33417. __extends(ExponentialEase, _super);
  33418. function ExponentialEase(exponent) {
  33419. if (exponent === void 0) { exponent = 2; }
  33420. var _this = _super.call(this) || this;
  33421. _this.exponent = exponent;
  33422. return _this;
  33423. }
  33424. ExponentialEase.prototype.easeInCore = function (gradient) {
  33425. if (this.exponent <= 0) {
  33426. return gradient;
  33427. }
  33428. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  33429. };
  33430. return ExponentialEase;
  33431. }(EasingFunction));
  33432. BABYLON.ExponentialEase = ExponentialEase;
  33433. var PowerEase = (function (_super) {
  33434. __extends(PowerEase, _super);
  33435. function PowerEase(power) {
  33436. if (power === void 0) { power = 2; }
  33437. var _this = _super.call(this) || this;
  33438. _this.power = power;
  33439. return _this;
  33440. }
  33441. PowerEase.prototype.easeInCore = function (gradient) {
  33442. var y = Math.max(0.0, this.power);
  33443. return Math.pow(gradient, y);
  33444. };
  33445. return PowerEase;
  33446. }(EasingFunction));
  33447. BABYLON.PowerEase = PowerEase;
  33448. var QuadraticEase = (function (_super) {
  33449. __extends(QuadraticEase, _super);
  33450. function QuadraticEase() {
  33451. return _super !== null && _super.apply(this, arguments) || this;
  33452. }
  33453. QuadraticEase.prototype.easeInCore = function (gradient) {
  33454. return (gradient * gradient);
  33455. };
  33456. return QuadraticEase;
  33457. }(EasingFunction));
  33458. BABYLON.QuadraticEase = QuadraticEase;
  33459. var QuarticEase = (function (_super) {
  33460. __extends(QuarticEase, _super);
  33461. function QuarticEase() {
  33462. return _super !== null && _super.apply(this, arguments) || this;
  33463. }
  33464. QuarticEase.prototype.easeInCore = function (gradient) {
  33465. return (gradient * gradient * gradient * gradient);
  33466. };
  33467. return QuarticEase;
  33468. }(EasingFunction));
  33469. BABYLON.QuarticEase = QuarticEase;
  33470. var QuinticEase = (function (_super) {
  33471. __extends(QuinticEase, _super);
  33472. function QuinticEase() {
  33473. return _super !== null && _super.apply(this, arguments) || this;
  33474. }
  33475. QuinticEase.prototype.easeInCore = function (gradient) {
  33476. return (gradient * gradient * gradient * gradient * gradient);
  33477. };
  33478. return QuinticEase;
  33479. }(EasingFunction));
  33480. BABYLON.QuinticEase = QuinticEase;
  33481. var SineEase = (function (_super) {
  33482. __extends(SineEase, _super);
  33483. function SineEase() {
  33484. return _super !== null && _super.apply(this, arguments) || this;
  33485. }
  33486. SineEase.prototype.easeInCore = function (gradient) {
  33487. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  33488. };
  33489. return SineEase;
  33490. }(EasingFunction));
  33491. BABYLON.SineEase = SineEase;
  33492. var BezierCurveEase = (function (_super) {
  33493. __extends(BezierCurveEase, _super);
  33494. function BezierCurveEase(x1, y1, x2, y2) {
  33495. if (x1 === void 0) { x1 = 0; }
  33496. if (y1 === void 0) { y1 = 0; }
  33497. if (x2 === void 0) { x2 = 1; }
  33498. if (y2 === void 0) { y2 = 1; }
  33499. var _this = _super.call(this) || this;
  33500. _this.x1 = x1;
  33501. _this.y1 = y1;
  33502. _this.x2 = x2;
  33503. _this.y2 = y2;
  33504. return _this;
  33505. }
  33506. BezierCurveEase.prototype.easeInCore = function (gradient) {
  33507. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  33508. };
  33509. return BezierCurveEase;
  33510. }(EasingFunction));
  33511. BABYLON.BezierCurveEase = BezierCurveEase;
  33512. })(BABYLON || (BABYLON = {}));
  33513. //# sourceMappingURL=babylon.easing.js.map
  33514. var BABYLON;
  33515. (function (BABYLON) {
  33516. var Condition = (function () {
  33517. function Condition(actionManager) {
  33518. this._actionManager = actionManager;
  33519. }
  33520. Condition.prototype.isValid = function () {
  33521. return true;
  33522. };
  33523. Condition.prototype._getProperty = function (propertyPath) {
  33524. return this._actionManager._getProperty(propertyPath);
  33525. };
  33526. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  33527. return this._actionManager._getEffectiveTarget(target, propertyPath);
  33528. };
  33529. Condition.prototype.serialize = function () {
  33530. };
  33531. Condition.prototype._serialize = function (serializedCondition) {
  33532. return {
  33533. type: 2,
  33534. children: [],
  33535. name: serializedCondition.name,
  33536. properties: serializedCondition.properties
  33537. };
  33538. };
  33539. return Condition;
  33540. }());
  33541. BABYLON.Condition = Condition;
  33542. var ValueCondition = (function (_super) {
  33543. __extends(ValueCondition, _super);
  33544. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  33545. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  33546. var _this = _super.call(this, actionManager) || this;
  33547. _this.propertyPath = propertyPath;
  33548. _this.value = value;
  33549. _this.operator = operator;
  33550. _this._target = target;
  33551. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  33552. _this._property = _this._getProperty(_this.propertyPath);
  33553. return _this;
  33554. }
  33555. Object.defineProperty(ValueCondition, "IsEqual", {
  33556. get: function () {
  33557. return ValueCondition._IsEqual;
  33558. },
  33559. enumerable: true,
  33560. configurable: true
  33561. });
  33562. Object.defineProperty(ValueCondition, "IsDifferent", {
  33563. get: function () {
  33564. return ValueCondition._IsDifferent;
  33565. },
  33566. enumerable: true,
  33567. configurable: true
  33568. });
  33569. Object.defineProperty(ValueCondition, "IsGreater", {
  33570. get: function () {
  33571. return ValueCondition._IsGreater;
  33572. },
  33573. enumerable: true,
  33574. configurable: true
  33575. });
  33576. Object.defineProperty(ValueCondition, "IsLesser", {
  33577. get: function () {
  33578. return ValueCondition._IsLesser;
  33579. },
  33580. enumerable: true,
  33581. configurable: true
  33582. });
  33583. // Methods
  33584. ValueCondition.prototype.isValid = function () {
  33585. switch (this.operator) {
  33586. case ValueCondition.IsGreater:
  33587. return this._effectiveTarget[this._property] > this.value;
  33588. case ValueCondition.IsLesser:
  33589. return this._effectiveTarget[this._property] < this.value;
  33590. case ValueCondition.IsEqual:
  33591. case ValueCondition.IsDifferent:
  33592. var check;
  33593. if (this.value.equals) {
  33594. check = this.value.equals(this._effectiveTarget[this._property]);
  33595. }
  33596. else {
  33597. check = this.value === this._effectiveTarget[this._property];
  33598. }
  33599. return this.operator === ValueCondition.IsEqual ? check : !check;
  33600. }
  33601. return false;
  33602. };
  33603. ValueCondition.prototype.serialize = function () {
  33604. return this._serialize({
  33605. name: "ValueCondition",
  33606. properties: [
  33607. BABYLON.Action._GetTargetProperty(this._target),
  33608. { name: "propertyPath", value: this.propertyPath },
  33609. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  33610. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  33611. ]
  33612. });
  33613. };
  33614. ValueCondition.GetOperatorName = function (operator) {
  33615. switch (operator) {
  33616. case ValueCondition._IsEqual: return "IsEqual";
  33617. case ValueCondition._IsDifferent: return "IsDifferent";
  33618. case ValueCondition._IsGreater: return "IsGreater";
  33619. case ValueCondition._IsLesser: return "IsLesser";
  33620. default: return "";
  33621. }
  33622. };
  33623. return ValueCondition;
  33624. }(Condition));
  33625. // Statics
  33626. ValueCondition._IsEqual = 0;
  33627. ValueCondition._IsDifferent = 1;
  33628. ValueCondition._IsGreater = 2;
  33629. ValueCondition._IsLesser = 3;
  33630. BABYLON.ValueCondition = ValueCondition;
  33631. var PredicateCondition = (function (_super) {
  33632. __extends(PredicateCondition, _super);
  33633. function PredicateCondition(actionManager, predicate) {
  33634. var _this = _super.call(this, actionManager) || this;
  33635. _this.predicate = predicate;
  33636. return _this;
  33637. }
  33638. PredicateCondition.prototype.isValid = function () {
  33639. return this.predicate();
  33640. };
  33641. return PredicateCondition;
  33642. }(Condition));
  33643. BABYLON.PredicateCondition = PredicateCondition;
  33644. var StateCondition = (function (_super) {
  33645. __extends(StateCondition, _super);
  33646. function StateCondition(actionManager, target, value) {
  33647. var _this = _super.call(this, actionManager) || this;
  33648. _this.value = value;
  33649. _this._target = target;
  33650. return _this;
  33651. }
  33652. // Methods
  33653. StateCondition.prototype.isValid = function () {
  33654. return this._target.state === this.value;
  33655. };
  33656. StateCondition.prototype.serialize = function () {
  33657. return this._serialize({
  33658. name: "StateCondition",
  33659. properties: [
  33660. BABYLON.Action._GetTargetProperty(this._target),
  33661. { name: "value", value: this.value }
  33662. ]
  33663. });
  33664. };
  33665. return StateCondition;
  33666. }(Condition));
  33667. BABYLON.StateCondition = StateCondition;
  33668. })(BABYLON || (BABYLON = {}));
  33669. //# sourceMappingURL=babylon.condition.js.map
  33670. var BABYLON;
  33671. (function (BABYLON) {
  33672. var Action = (function () {
  33673. function Action(triggerOptions, condition) {
  33674. this.triggerOptions = triggerOptions;
  33675. if (triggerOptions.parameter) {
  33676. this.trigger = triggerOptions.trigger;
  33677. this._triggerParameter = triggerOptions.parameter;
  33678. }
  33679. else {
  33680. this.trigger = triggerOptions;
  33681. }
  33682. this._nextActiveAction = this;
  33683. this._condition = condition;
  33684. }
  33685. // Methods
  33686. Action.prototype._prepare = function () {
  33687. };
  33688. Action.prototype.getTriggerParameter = function () {
  33689. return this._triggerParameter;
  33690. };
  33691. Action.prototype._executeCurrent = function (evt) {
  33692. if (this._nextActiveAction._condition) {
  33693. var condition = this._nextActiveAction._condition;
  33694. var currentRenderId = this._actionManager.getScene().getRenderId();
  33695. // We cache the current evaluation for the current frame
  33696. if (condition._evaluationId === currentRenderId) {
  33697. if (!condition._currentResult) {
  33698. return;
  33699. }
  33700. }
  33701. else {
  33702. condition._evaluationId = currentRenderId;
  33703. if (!condition.isValid()) {
  33704. condition._currentResult = false;
  33705. return;
  33706. }
  33707. condition._currentResult = true;
  33708. }
  33709. }
  33710. this._nextActiveAction.execute(evt);
  33711. this.skipToNextActiveAction();
  33712. };
  33713. Action.prototype.execute = function (evt) {
  33714. };
  33715. Action.prototype.skipToNextActiveAction = function () {
  33716. if (this._nextActiveAction._child) {
  33717. if (!this._nextActiveAction._child._actionManager) {
  33718. this._nextActiveAction._child._actionManager = this._actionManager;
  33719. }
  33720. this._nextActiveAction = this._nextActiveAction._child;
  33721. }
  33722. else {
  33723. this._nextActiveAction = this;
  33724. }
  33725. };
  33726. Action.prototype.then = function (action) {
  33727. this._child = action;
  33728. action._actionManager = this._actionManager;
  33729. action._prepare();
  33730. return action;
  33731. };
  33732. Action.prototype._getProperty = function (propertyPath) {
  33733. return this._actionManager._getProperty(propertyPath);
  33734. };
  33735. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  33736. return this._actionManager._getEffectiveTarget(target, propertyPath);
  33737. };
  33738. Action.prototype.serialize = function (parent) {
  33739. };
  33740. // Called by BABYLON.Action objects in serialize(...). Internal use
  33741. Action.prototype._serialize = function (serializedAction, parent) {
  33742. var serializationObject = {
  33743. type: 1,
  33744. children: [],
  33745. name: serializedAction.name,
  33746. properties: serializedAction.properties || []
  33747. };
  33748. // Serialize child
  33749. if (this._child) {
  33750. this._child.serialize(serializationObject);
  33751. }
  33752. // Check if "this" has a condition
  33753. if (this._condition) {
  33754. var serializedCondition = this._condition.serialize();
  33755. serializedCondition.children.push(serializationObject);
  33756. if (parent) {
  33757. parent.children.push(serializedCondition);
  33758. }
  33759. return serializedCondition;
  33760. }
  33761. if (parent) {
  33762. parent.children.push(serializationObject);
  33763. }
  33764. return serializationObject;
  33765. };
  33766. return Action;
  33767. }());
  33768. Action._SerializeValueAsString = function (value) {
  33769. if (typeof value === "number") {
  33770. return value.toString();
  33771. }
  33772. if (typeof value === "boolean") {
  33773. return value ? "true" : "false";
  33774. }
  33775. if (value instanceof BABYLON.Vector2) {
  33776. return value.x + ", " + value.y;
  33777. }
  33778. if (value instanceof BABYLON.Vector3) {
  33779. return value.x + ", " + value.y + ", " + value.z;
  33780. }
  33781. if (value instanceof BABYLON.Color3) {
  33782. return value.r + ", " + value.g + ", " + value.b;
  33783. }
  33784. if (value instanceof BABYLON.Color4) {
  33785. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  33786. }
  33787. return value; // string
  33788. };
  33789. Action._GetTargetProperty = function (target) {
  33790. return {
  33791. name: "target",
  33792. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  33793. : target instanceof BABYLON.Light ? "LightProperties"
  33794. : target instanceof BABYLON.Camera ? "CameraProperties"
  33795. : "SceneProperties",
  33796. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  33797. };
  33798. };
  33799. BABYLON.Action = Action;
  33800. })(BABYLON || (BABYLON = {}));
  33801. //# sourceMappingURL=babylon.action.js.map
  33802. var BABYLON;
  33803. (function (BABYLON) {
  33804. /**
  33805. * ActionEvent is the event beint sent when an action is triggered.
  33806. */
  33807. var ActionEvent = (function () {
  33808. /**
  33809. * @constructor
  33810. * @param source The mesh or sprite that triggered the action.
  33811. * @param pointerX The X mouse cursor position at the time of the event
  33812. * @param pointerY The Y mouse cursor position at the time of the event
  33813. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  33814. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  33815. */
  33816. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  33817. this.source = source;
  33818. this.pointerX = pointerX;
  33819. this.pointerY = pointerY;
  33820. this.meshUnderPointer = meshUnderPointer;
  33821. this.sourceEvent = sourceEvent;
  33822. this.additionalData = additionalData;
  33823. }
  33824. /**
  33825. * Helper function to auto-create an ActionEvent from a source mesh.
  33826. * @param source The source mesh that triggered the event
  33827. * @param evt {Event} The original (browser) event
  33828. */
  33829. ActionEvent.CreateNew = function (source, evt, additionalData) {
  33830. var scene = source.getScene();
  33831. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  33832. };
  33833. /**
  33834. * Helper function to auto-create an ActionEvent from a source mesh.
  33835. * @param source The source sprite that triggered the event
  33836. * @param scene Scene associated with the sprite
  33837. * @param evt {Event} The original (browser) event
  33838. */
  33839. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  33840. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  33841. };
  33842. /**
  33843. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  33844. * @param scene the scene where the event occurred
  33845. * @param evt {Event} The original (browser) event
  33846. */
  33847. ActionEvent.CreateNewFromScene = function (scene, evt) {
  33848. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  33849. };
  33850. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  33851. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  33852. };
  33853. return ActionEvent;
  33854. }());
  33855. BABYLON.ActionEvent = ActionEvent;
  33856. /**
  33857. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  33858. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  33859. */
  33860. var ActionManager = (function () {
  33861. function ActionManager(scene) {
  33862. // Members
  33863. this.actions = new Array();
  33864. this.hoverCursor = '';
  33865. this._scene = scene;
  33866. scene._actionManagers.push(this);
  33867. }
  33868. Object.defineProperty(ActionManager, "NothingTrigger", {
  33869. get: function () {
  33870. return ActionManager._NothingTrigger;
  33871. },
  33872. enumerable: true,
  33873. configurable: true
  33874. });
  33875. Object.defineProperty(ActionManager, "OnPickTrigger", {
  33876. get: function () {
  33877. return ActionManager._OnPickTrigger;
  33878. },
  33879. enumerable: true,
  33880. configurable: true
  33881. });
  33882. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  33883. get: function () {
  33884. return ActionManager._OnLeftPickTrigger;
  33885. },
  33886. enumerable: true,
  33887. configurable: true
  33888. });
  33889. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  33890. get: function () {
  33891. return ActionManager._OnRightPickTrigger;
  33892. },
  33893. enumerable: true,
  33894. configurable: true
  33895. });
  33896. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  33897. get: function () {
  33898. return ActionManager._OnCenterPickTrigger;
  33899. },
  33900. enumerable: true,
  33901. configurable: true
  33902. });
  33903. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  33904. get: function () {
  33905. return ActionManager._OnPickDownTrigger;
  33906. },
  33907. enumerable: true,
  33908. configurable: true
  33909. });
  33910. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  33911. get: function () {
  33912. return ActionManager._OnDoublePickTrigger;
  33913. },
  33914. enumerable: true,
  33915. configurable: true
  33916. });
  33917. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  33918. get: function () {
  33919. return ActionManager._OnPickUpTrigger;
  33920. },
  33921. enumerable: true,
  33922. configurable: true
  33923. });
  33924. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  33925. /// This trigger will only be raised if you also declared a OnPickDown
  33926. get: function () {
  33927. return ActionManager._OnPickOutTrigger;
  33928. },
  33929. enumerable: true,
  33930. configurable: true
  33931. });
  33932. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  33933. get: function () {
  33934. return ActionManager._OnLongPressTrigger;
  33935. },
  33936. enumerable: true,
  33937. configurable: true
  33938. });
  33939. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  33940. get: function () {
  33941. return ActionManager._OnPointerOverTrigger;
  33942. },
  33943. enumerable: true,
  33944. configurable: true
  33945. });
  33946. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  33947. get: function () {
  33948. return ActionManager._OnPointerOutTrigger;
  33949. },
  33950. enumerable: true,
  33951. configurable: true
  33952. });
  33953. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  33954. get: function () {
  33955. return ActionManager._OnEveryFrameTrigger;
  33956. },
  33957. enumerable: true,
  33958. configurable: true
  33959. });
  33960. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  33961. get: function () {
  33962. return ActionManager._OnIntersectionEnterTrigger;
  33963. },
  33964. enumerable: true,
  33965. configurable: true
  33966. });
  33967. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  33968. get: function () {
  33969. return ActionManager._OnIntersectionExitTrigger;
  33970. },
  33971. enumerable: true,
  33972. configurable: true
  33973. });
  33974. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  33975. get: function () {
  33976. return ActionManager._OnKeyDownTrigger;
  33977. },
  33978. enumerable: true,
  33979. configurable: true
  33980. });
  33981. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  33982. get: function () {
  33983. return ActionManager._OnKeyUpTrigger;
  33984. },
  33985. enumerable: true,
  33986. configurable: true
  33987. });
  33988. // Methods
  33989. ActionManager.prototype.dispose = function () {
  33990. var index = this._scene._actionManagers.indexOf(this);
  33991. for (var i = 0; i < this.actions.length; i++) {
  33992. var action = this.actions[i];
  33993. ActionManager.Triggers[action.trigger]--;
  33994. if (ActionManager.Triggers[action.trigger] === 0) {
  33995. delete ActionManager.Triggers[action.trigger];
  33996. }
  33997. }
  33998. if (index > -1) {
  33999. this._scene._actionManagers.splice(index, 1);
  34000. }
  34001. };
  34002. ActionManager.prototype.getScene = function () {
  34003. return this._scene;
  34004. };
  34005. /**
  34006. * Does this action manager handles actions of any of the given triggers
  34007. * @param {number[]} triggers - the triggers to be tested
  34008. * @return {boolean} whether one (or more) of the triggers is handeled
  34009. */
  34010. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  34011. for (var index = 0; index < this.actions.length; index++) {
  34012. var action = this.actions[index];
  34013. if (triggers.indexOf(action.trigger) > -1) {
  34014. return true;
  34015. }
  34016. }
  34017. return false;
  34018. };
  34019. /**
  34020. * Does this action manager handles actions of a given trigger
  34021. * @param {number} trigger - the trigger to be tested
  34022. * @return {boolean} whether the trigger is handeled
  34023. */
  34024. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  34025. for (var index = 0; index < this.actions.length; index++) {
  34026. var action = this.actions[index];
  34027. if (action.trigger === trigger) {
  34028. return true;
  34029. }
  34030. }
  34031. return false;
  34032. };
  34033. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  34034. /**
  34035. * Does this action manager has pointer triggers
  34036. * @return {boolean} whether or not it has pointer triggers
  34037. */
  34038. get: function () {
  34039. for (var index = 0; index < this.actions.length; index++) {
  34040. var action = this.actions[index];
  34041. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  34042. return true;
  34043. }
  34044. }
  34045. return false;
  34046. },
  34047. enumerable: true,
  34048. configurable: true
  34049. });
  34050. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  34051. /**
  34052. * Does this action manager has pick triggers
  34053. * @return {boolean} whether or not it has pick triggers
  34054. */
  34055. get: function () {
  34056. for (var index = 0; index < this.actions.length; index++) {
  34057. var action = this.actions[index];
  34058. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  34059. return true;
  34060. }
  34061. }
  34062. return false;
  34063. },
  34064. enumerable: true,
  34065. configurable: true
  34066. });
  34067. Object.defineProperty(ActionManager, "HasTriggers", {
  34068. /**
  34069. * Does exist one action manager with at least one trigger
  34070. * @return {boolean} whether or not it exists one action manager with one trigger
  34071. **/
  34072. get: function () {
  34073. for (var t in ActionManager.Triggers) {
  34074. if (ActionManager.Triggers.hasOwnProperty(t)) {
  34075. return true;
  34076. }
  34077. }
  34078. return false;
  34079. },
  34080. enumerable: true,
  34081. configurable: true
  34082. });
  34083. Object.defineProperty(ActionManager, "HasPickTriggers", {
  34084. /**
  34085. * Does exist one action manager with at least one pick trigger
  34086. * @return {boolean} whether or not it exists one action manager with one pick trigger
  34087. **/
  34088. get: function () {
  34089. for (var t in ActionManager.Triggers) {
  34090. if (ActionManager.Triggers.hasOwnProperty(t)) {
  34091. var t_int = parseInt(t);
  34092. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  34093. return true;
  34094. }
  34095. }
  34096. }
  34097. return false;
  34098. },
  34099. enumerable: true,
  34100. configurable: true
  34101. });
  34102. /**
  34103. * Does exist one action manager that handles actions of a given trigger
  34104. * @param {number} trigger - the trigger to be tested
  34105. * @return {boolean} whether the trigger is handeled by at least one action manager
  34106. **/
  34107. ActionManager.HasSpecificTrigger = function (trigger) {
  34108. for (var t in ActionManager.Triggers) {
  34109. if (ActionManager.Triggers.hasOwnProperty(t)) {
  34110. var t_int = parseInt(t);
  34111. if (t_int === trigger) {
  34112. return true;
  34113. }
  34114. }
  34115. }
  34116. return false;
  34117. };
  34118. /**
  34119. * Registers an action to this action manager
  34120. * @param {BABYLON.Action} action - the action to be registered
  34121. * @return {BABYLON.Action} the action amended (prepared) after registration
  34122. */
  34123. ActionManager.prototype.registerAction = function (action) {
  34124. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  34125. if (this.getScene().actionManager !== this) {
  34126. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  34127. return null;
  34128. }
  34129. }
  34130. this.actions.push(action);
  34131. if (ActionManager.Triggers[action.trigger]) {
  34132. ActionManager.Triggers[action.trigger]++;
  34133. }
  34134. else {
  34135. ActionManager.Triggers[action.trigger] = 1;
  34136. }
  34137. action._actionManager = this;
  34138. action._prepare();
  34139. return action;
  34140. };
  34141. /**
  34142. * Process a specific trigger
  34143. * @param {number} trigger - the trigger to process
  34144. * @param evt {BABYLON.ActionEvent} the event details to be processed
  34145. */
  34146. ActionManager.prototype.processTrigger = function (trigger, evt) {
  34147. for (var index = 0; index < this.actions.length; index++) {
  34148. var action = this.actions[index];
  34149. if (action.trigger === trigger) {
  34150. if (trigger === ActionManager.OnKeyUpTrigger
  34151. || trigger === ActionManager.OnKeyDownTrigger) {
  34152. var parameter = action.getTriggerParameter();
  34153. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  34154. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  34155. var actualkey = String.fromCharCode(unicode).toLowerCase();
  34156. if (actualkey !== parameter.toLowerCase()) {
  34157. continue;
  34158. }
  34159. }
  34160. }
  34161. action._executeCurrent(evt);
  34162. }
  34163. }
  34164. };
  34165. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  34166. var properties = propertyPath.split(".");
  34167. for (var index = 0; index < properties.length - 1; index++) {
  34168. target = target[properties[index]];
  34169. }
  34170. return target;
  34171. };
  34172. ActionManager.prototype._getProperty = function (propertyPath) {
  34173. var properties = propertyPath.split(".");
  34174. return properties[properties.length - 1];
  34175. };
  34176. ActionManager.prototype.serialize = function (name) {
  34177. var root = {
  34178. children: [],
  34179. name: name,
  34180. type: 3,
  34181. properties: [] // Empty for root but required
  34182. };
  34183. for (var i = 0; i < this.actions.length; i++) {
  34184. var triggerObject = {
  34185. type: 0,
  34186. children: [],
  34187. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  34188. properties: []
  34189. };
  34190. var triggerOptions = this.actions[i].triggerOptions;
  34191. if (triggerOptions && typeof triggerOptions !== "number") {
  34192. if (triggerOptions.parameter instanceof BABYLON.Node) {
  34193. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  34194. }
  34195. else {
  34196. var parameter = {};
  34197. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  34198. if (triggerOptions.parameter.mesh) {
  34199. parameter._meshId = triggerOptions.parameter.mesh.id;
  34200. }
  34201. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  34202. }
  34203. }
  34204. // Serialize child action, recursively
  34205. this.actions[i].serialize(triggerObject);
  34206. // Add serialized trigger
  34207. root.children.push(triggerObject);
  34208. }
  34209. return root;
  34210. };
  34211. ActionManager.Parse = function (parsedActions, object, scene) {
  34212. var actionManager = new BABYLON.ActionManager(scene);
  34213. if (object === null)
  34214. scene.actionManager = actionManager;
  34215. else
  34216. object.actionManager = actionManager;
  34217. // instanciate a new object
  34218. var instanciate = function (name, params) {
  34219. var newInstance = Object.create(BABYLON[name].prototype);
  34220. newInstance.constructor.apply(newInstance, params);
  34221. return newInstance;
  34222. };
  34223. var parseParameter = function (name, value, target, propertyPath) {
  34224. if (propertyPath === null) {
  34225. // String, boolean or float
  34226. var floatValue = parseFloat(value);
  34227. if (value === "true" || value === "false")
  34228. return value === "true";
  34229. else
  34230. return isNaN(floatValue) ? value : floatValue;
  34231. }
  34232. var effectiveTarget = propertyPath.split(".");
  34233. var values = value.split(",");
  34234. // Get effective Target
  34235. for (var i = 0; i < effectiveTarget.length; i++) {
  34236. target = target[effectiveTarget[i]];
  34237. }
  34238. // Return appropriate value with its type
  34239. if (typeof (target) === "boolean")
  34240. return values[0] === "true";
  34241. if (typeof (target) === "string")
  34242. return values[0];
  34243. // Parameters with multiple values such as Vector3 etc.
  34244. var split = new Array();
  34245. for (var i = 0; i < values.length; i++)
  34246. split.push(parseFloat(values[i]));
  34247. if (target instanceof BABYLON.Vector3)
  34248. return BABYLON.Vector3.FromArray(split);
  34249. if (target instanceof BABYLON.Vector4)
  34250. return BABYLON.Vector4.FromArray(split);
  34251. if (target instanceof BABYLON.Color3)
  34252. return BABYLON.Color3.FromArray(split);
  34253. if (target instanceof BABYLON.Color4)
  34254. return BABYLON.Color4.FromArray(split);
  34255. return parseFloat(values[0]);
  34256. };
  34257. // traverse graph per trigger
  34258. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  34259. if (combineArray === void 0) { combineArray = null; }
  34260. if (parsedAction.detached)
  34261. return;
  34262. var parameters = new Array();
  34263. var target = null;
  34264. var propertyPath = null;
  34265. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  34266. // Parameters
  34267. if (parsedAction.type === 2)
  34268. parameters.push(actionManager);
  34269. else
  34270. parameters.push(trigger);
  34271. if (combine) {
  34272. var actions = new Array();
  34273. for (var j = 0; j < parsedAction.combine.length; j++) {
  34274. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  34275. }
  34276. parameters.push(actions);
  34277. }
  34278. else {
  34279. for (var i = 0; i < parsedAction.properties.length; i++) {
  34280. var value = parsedAction.properties[i].value;
  34281. var name = parsedAction.properties[i].name;
  34282. var targetType = parsedAction.properties[i].targetType;
  34283. if (name === "target")
  34284. if (targetType !== null && targetType === "SceneProperties")
  34285. value = target = scene;
  34286. else
  34287. value = target = scene.getNodeByName(value);
  34288. else if (name === "parent")
  34289. value = scene.getNodeByName(value);
  34290. else if (name === "sound")
  34291. value = scene.getSoundByName(value);
  34292. else if (name !== "propertyPath") {
  34293. if (parsedAction.type === 2 && name === "operator")
  34294. value = BABYLON.ValueCondition[value];
  34295. else
  34296. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  34297. }
  34298. else {
  34299. propertyPath = value;
  34300. }
  34301. parameters.push(value);
  34302. }
  34303. }
  34304. if (combineArray === null) {
  34305. parameters.push(condition);
  34306. }
  34307. else {
  34308. parameters.push(null);
  34309. }
  34310. // If interpolate value action
  34311. if (parsedAction.name === "InterpolateValueAction") {
  34312. var param = parameters[parameters.length - 2];
  34313. parameters[parameters.length - 1] = param;
  34314. parameters[parameters.length - 2] = condition;
  34315. }
  34316. // Action or condition(s) and not CombineAction
  34317. var newAction = instanciate(parsedAction.name, parameters);
  34318. if (newAction instanceof BABYLON.Condition && condition !== null) {
  34319. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  34320. if (action)
  34321. action.then(nothing);
  34322. else
  34323. actionManager.registerAction(nothing);
  34324. action = nothing;
  34325. }
  34326. if (combineArray === null) {
  34327. if (newAction instanceof BABYLON.Condition) {
  34328. condition = newAction;
  34329. newAction = action;
  34330. }
  34331. else {
  34332. condition = null;
  34333. if (action)
  34334. action.then(newAction);
  34335. else
  34336. actionManager.registerAction(newAction);
  34337. }
  34338. }
  34339. else {
  34340. combineArray.push(newAction);
  34341. }
  34342. for (var i = 0; i < parsedAction.children.length; i++)
  34343. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  34344. };
  34345. // triggers
  34346. for (var i = 0; i < parsedActions.children.length; i++) {
  34347. var triggerParams;
  34348. var trigger = parsedActions.children[i];
  34349. if (trigger.properties.length > 0) {
  34350. var param = trigger.properties[0].value;
  34351. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  34352. if (value._meshId) {
  34353. value.mesh = scene.getMeshByID(value._meshId);
  34354. }
  34355. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  34356. }
  34357. else
  34358. triggerParams = BABYLON.ActionManager[trigger.name];
  34359. for (var j = 0; j < trigger.children.length; j++) {
  34360. if (!trigger.detached)
  34361. traverse(trigger.children[j], triggerParams, null, null);
  34362. }
  34363. }
  34364. };
  34365. ActionManager.GetTriggerName = function (trigger) {
  34366. switch (trigger) {
  34367. case 0: return "NothingTrigger";
  34368. case 1: return "OnPickTrigger";
  34369. case 2: return "OnLeftPickTrigger";
  34370. case 3: return "OnRightPickTrigger";
  34371. case 4: return "OnCenterPickTrigger";
  34372. case 5: return "OnPickDownTrigger";
  34373. case 6: return "OnPickUpTrigger";
  34374. case 7: return "OnLongPressTrigger";
  34375. case 8: return "OnPointerOverTrigger";
  34376. case 9: return "OnPointerOutTrigger";
  34377. case 10: return "OnEveryFrameTrigger";
  34378. case 11: return "OnIntersectionEnterTrigger";
  34379. case 12: return "OnIntersectionExitTrigger";
  34380. case 13: return "OnKeyDownTrigger";
  34381. case 14: return "OnKeyUpTrigger";
  34382. case 15: return "OnPickOutTrigger";
  34383. default: return "";
  34384. }
  34385. };
  34386. return ActionManager;
  34387. }());
  34388. // Statics
  34389. ActionManager._NothingTrigger = 0;
  34390. ActionManager._OnPickTrigger = 1;
  34391. ActionManager._OnLeftPickTrigger = 2;
  34392. ActionManager._OnRightPickTrigger = 3;
  34393. ActionManager._OnCenterPickTrigger = 4;
  34394. ActionManager._OnPickDownTrigger = 5;
  34395. ActionManager._OnDoublePickTrigger = 6;
  34396. ActionManager._OnPickUpTrigger = 7;
  34397. ActionManager._OnLongPressTrigger = 8;
  34398. ActionManager._OnPointerOverTrigger = 9;
  34399. ActionManager._OnPointerOutTrigger = 10;
  34400. ActionManager._OnEveryFrameTrigger = 11;
  34401. ActionManager._OnIntersectionEnterTrigger = 12;
  34402. ActionManager._OnIntersectionExitTrigger = 13;
  34403. ActionManager._OnKeyDownTrigger = 14;
  34404. ActionManager._OnKeyUpTrigger = 15;
  34405. ActionManager._OnPickOutTrigger = 16;
  34406. ActionManager.Triggers = {};
  34407. BABYLON.ActionManager = ActionManager;
  34408. })(BABYLON || (BABYLON = {}));
  34409. //# sourceMappingURL=babylon.actionManager.js.map
  34410. var BABYLON;
  34411. (function (BABYLON) {
  34412. var InterpolateValueAction = (function (_super) {
  34413. __extends(InterpolateValueAction, _super);
  34414. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  34415. if (duration === void 0) { duration = 1000; }
  34416. var _this = _super.call(this, triggerOptions, condition) || this;
  34417. _this.propertyPath = propertyPath;
  34418. _this.value = value;
  34419. _this.duration = duration;
  34420. _this.stopOtherAnimations = stopOtherAnimations;
  34421. _this.onInterpolationDone = onInterpolationDone;
  34422. _this._target = _this._effectiveTarget = target;
  34423. return _this;
  34424. }
  34425. InterpolateValueAction.prototype._prepare = function () {
  34426. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34427. this._property = this._getProperty(this.propertyPath);
  34428. };
  34429. InterpolateValueAction.prototype.execute = function () {
  34430. var scene = this._actionManager.getScene();
  34431. var keys = [
  34432. {
  34433. frame: 0,
  34434. value: this._effectiveTarget[this._property]
  34435. }, {
  34436. frame: 100,
  34437. value: this.value
  34438. }
  34439. ];
  34440. var dataType;
  34441. if (typeof this.value === "number") {
  34442. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  34443. }
  34444. else if (this.value instanceof BABYLON.Color3) {
  34445. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  34446. }
  34447. else if (this.value instanceof BABYLON.Vector3) {
  34448. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  34449. }
  34450. else if (this.value instanceof BABYLON.Matrix) {
  34451. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  34452. }
  34453. else if (this.value instanceof BABYLON.Quaternion) {
  34454. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  34455. }
  34456. else {
  34457. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  34458. return;
  34459. }
  34460. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  34461. animation.setKeys(keys);
  34462. if (this.stopOtherAnimations) {
  34463. scene.stopAnimation(this._effectiveTarget);
  34464. }
  34465. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  34466. };
  34467. InterpolateValueAction.prototype.serialize = function (parent) {
  34468. return _super.prototype._serialize.call(this, {
  34469. name: "InterpolateValueAction",
  34470. properties: [
  34471. BABYLON.Action._GetTargetProperty(this._target),
  34472. { name: "propertyPath", value: this.propertyPath },
  34473. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  34474. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  34475. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  34476. ]
  34477. }, parent);
  34478. };
  34479. return InterpolateValueAction;
  34480. }(BABYLON.Action));
  34481. BABYLON.InterpolateValueAction = InterpolateValueAction;
  34482. })(BABYLON || (BABYLON = {}));
  34483. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  34484. var BABYLON;
  34485. (function (BABYLON) {
  34486. var SwitchBooleanAction = (function (_super) {
  34487. __extends(SwitchBooleanAction, _super);
  34488. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  34489. var _this = _super.call(this, triggerOptions, condition) || this;
  34490. _this.propertyPath = propertyPath;
  34491. _this._target = _this._effectiveTarget = target;
  34492. return _this;
  34493. }
  34494. SwitchBooleanAction.prototype._prepare = function () {
  34495. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34496. this._property = this._getProperty(this.propertyPath);
  34497. };
  34498. SwitchBooleanAction.prototype.execute = function () {
  34499. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  34500. };
  34501. SwitchBooleanAction.prototype.serialize = function (parent) {
  34502. return _super.prototype._serialize.call(this, {
  34503. name: "SwitchBooleanAction",
  34504. properties: [
  34505. BABYLON.Action._GetTargetProperty(this._target),
  34506. { name: "propertyPath", value: this.propertyPath }
  34507. ]
  34508. }, parent);
  34509. };
  34510. return SwitchBooleanAction;
  34511. }(BABYLON.Action));
  34512. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  34513. var SetStateAction = (function (_super) {
  34514. __extends(SetStateAction, _super);
  34515. function SetStateAction(triggerOptions, target, value, condition) {
  34516. var _this = _super.call(this, triggerOptions, condition) || this;
  34517. _this.value = value;
  34518. _this._target = target;
  34519. return _this;
  34520. }
  34521. SetStateAction.prototype.execute = function () {
  34522. this._target.state = this.value;
  34523. };
  34524. SetStateAction.prototype.serialize = function (parent) {
  34525. return _super.prototype._serialize.call(this, {
  34526. name: "SetStateAction",
  34527. properties: [
  34528. BABYLON.Action._GetTargetProperty(this._target),
  34529. { name: "value", value: this.value }
  34530. ]
  34531. }, parent);
  34532. };
  34533. return SetStateAction;
  34534. }(BABYLON.Action));
  34535. BABYLON.SetStateAction = SetStateAction;
  34536. var SetValueAction = (function (_super) {
  34537. __extends(SetValueAction, _super);
  34538. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  34539. var _this = _super.call(this, triggerOptions, condition) || this;
  34540. _this.propertyPath = propertyPath;
  34541. _this.value = value;
  34542. _this._target = _this._effectiveTarget = target;
  34543. return _this;
  34544. }
  34545. SetValueAction.prototype._prepare = function () {
  34546. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34547. this._property = this._getProperty(this.propertyPath);
  34548. };
  34549. SetValueAction.prototype.execute = function () {
  34550. this._effectiveTarget[this._property] = this.value;
  34551. if (this._target.markAsDirty) {
  34552. this._target.markAsDirty(this._property);
  34553. }
  34554. };
  34555. SetValueAction.prototype.serialize = function (parent) {
  34556. return _super.prototype._serialize.call(this, {
  34557. name: "SetValueAction",
  34558. properties: [
  34559. BABYLON.Action._GetTargetProperty(this._target),
  34560. { name: "propertyPath", value: this.propertyPath },
  34561. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  34562. ]
  34563. }, parent);
  34564. };
  34565. return SetValueAction;
  34566. }(BABYLON.Action));
  34567. BABYLON.SetValueAction = SetValueAction;
  34568. var IncrementValueAction = (function (_super) {
  34569. __extends(IncrementValueAction, _super);
  34570. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  34571. var _this = _super.call(this, triggerOptions, condition) || this;
  34572. _this.propertyPath = propertyPath;
  34573. _this.value = value;
  34574. _this._target = _this._effectiveTarget = target;
  34575. return _this;
  34576. }
  34577. IncrementValueAction.prototype._prepare = function () {
  34578. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34579. this._property = this._getProperty(this.propertyPath);
  34580. if (typeof this._effectiveTarget[this._property] !== "number") {
  34581. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  34582. }
  34583. };
  34584. IncrementValueAction.prototype.execute = function () {
  34585. this._effectiveTarget[this._property] += this.value;
  34586. if (this._target.markAsDirty) {
  34587. this._target.markAsDirty(this._property);
  34588. }
  34589. };
  34590. IncrementValueAction.prototype.serialize = function (parent) {
  34591. return _super.prototype._serialize.call(this, {
  34592. name: "IncrementValueAction",
  34593. properties: [
  34594. BABYLON.Action._GetTargetProperty(this._target),
  34595. { name: "propertyPath", value: this.propertyPath },
  34596. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  34597. ]
  34598. }, parent);
  34599. };
  34600. return IncrementValueAction;
  34601. }(BABYLON.Action));
  34602. BABYLON.IncrementValueAction = IncrementValueAction;
  34603. var PlayAnimationAction = (function (_super) {
  34604. __extends(PlayAnimationAction, _super);
  34605. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  34606. var _this = _super.call(this, triggerOptions, condition) || this;
  34607. _this.from = from;
  34608. _this.to = to;
  34609. _this.loop = loop;
  34610. _this._target = target;
  34611. return _this;
  34612. }
  34613. PlayAnimationAction.prototype._prepare = function () {
  34614. };
  34615. PlayAnimationAction.prototype.execute = function () {
  34616. var scene = this._actionManager.getScene();
  34617. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  34618. };
  34619. PlayAnimationAction.prototype.serialize = function (parent) {
  34620. return _super.prototype._serialize.call(this, {
  34621. name: "PlayAnimationAction",
  34622. properties: [
  34623. BABYLON.Action._GetTargetProperty(this._target),
  34624. { name: "from", value: String(this.from) },
  34625. { name: "to", value: String(this.to) },
  34626. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  34627. ]
  34628. }, parent);
  34629. };
  34630. return PlayAnimationAction;
  34631. }(BABYLON.Action));
  34632. BABYLON.PlayAnimationAction = PlayAnimationAction;
  34633. var StopAnimationAction = (function (_super) {
  34634. __extends(StopAnimationAction, _super);
  34635. function StopAnimationAction(triggerOptions, target, condition) {
  34636. var _this = _super.call(this, triggerOptions, condition) || this;
  34637. _this._target = target;
  34638. return _this;
  34639. }
  34640. StopAnimationAction.prototype._prepare = function () {
  34641. };
  34642. StopAnimationAction.prototype.execute = function () {
  34643. var scene = this._actionManager.getScene();
  34644. scene.stopAnimation(this._target);
  34645. };
  34646. StopAnimationAction.prototype.serialize = function (parent) {
  34647. return _super.prototype._serialize.call(this, {
  34648. name: "StopAnimationAction",
  34649. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  34650. }, parent);
  34651. };
  34652. return StopAnimationAction;
  34653. }(BABYLON.Action));
  34654. BABYLON.StopAnimationAction = StopAnimationAction;
  34655. var DoNothingAction = (function (_super) {
  34656. __extends(DoNothingAction, _super);
  34657. function DoNothingAction(triggerOptions, condition) {
  34658. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  34659. return _super.call(this, triggerOptions, condition) || this;
  34660. }
  34661. DoNothingAction.prototype.execute = function () {
  34662. };
  34663. DoNothingAction.prototype.serialize = function (parent) {
  34664. return _super.prototype._serialize.call(this, {
  34665. name: "DoNothingAction",
  34666. properties: []
  34667. }, parent);
  34668. };
  34669. return DoNothingAction;
  34670. }(BABYLON.Action));
  34671. BABYLON.DoNothingAction = DoNothingAction;
  34672. var CombineAction = (function (_super) {
  34673. __extends(CombineAction, _super);
  34674. function CombineAction(triggerOptions, children, condition) {
  34675. var _this = _super.call(this, triggerOptions, condition) || this;
  34676. _this.children = children;
  34677. return _this;
  34678. }
  34679. CombineAction.prototype._prepare = function () {
  34680. for (var index = 0; index < this.children.length; index++) {
  34681. this.children[index]._actionManager = this._actionManager;
  34682. this.children[index]._prepare();
  34683. }
  34684. };
  34685. CombineAction.prototype.execute = function (evt) {
  34686. for (var index = 0; index < this.children.length; index++) {
  34687. this.children[index].execute(evt);
  34688. }
  34689. };
  34690. CombineAction.prototype.serialize = function (parent) {
  34691. var serializationObject = _super.prototype._serialize.call(this, {
  34692. name: "CombineAction",
  34693. properties: [],
  34694. combine: []
  34695. }, parent);
  34696. for (var i = 0; i < this.children.length; i++) {
  34697. serializationObject.combine.push(this.children[i].serialize(null));
  34698. }
  34699. return serializationObject;
  34700. };
  34701. return CombineAction;
  34702. }(BABYLON.Action));
  34703. BABYLON.CombineAction = CombineAction;
  34704. var ExecuteCodeAction = (function (_super) {
  34705. __extends(ExecuteCodeAction, _super);
  34706. function ExecuteCodeAction(triggerOptions, func, condition) {
  34707. var _this = _super.call(this, triggerOptions, condition) || this;
  34708. _this.func = func;
  34709. return _this;
  34710. }
  34711. ExecuteCodeAction.prototype.execute = function (evt) {
  34712. this.func(evt);
  34713. };
  34714. return ExecuteCodeAction;
  34715. }(BABYLON.Action));
  34716. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  34717. var SetParentAction = (function (_super) {
  34718. __extends(SetParentAction, _super);
  34719. function SetParentAction(triggerOptions, target, parent, condition) {
  34720. var _this = _super.call(this, triggerOptions, condition) || this;
  34721. _this._target = target;
  34722. _this._parent = parent;
  34723. return _this;
  34724. }
  34725. SetParentAction.prototype._prepare = function () {
  34726. };
  34727. SetParentAction.prototype.execute = function () {
  34728. if (this._target.parent === this._parent) {
  34729. return;
  34730. }
  34731. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  34732. invertParentWorldMatrix.invert();
  34733. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  34734. this._target.parent = this._parent;
  34735. };
  34736. SetParentAction.prototype.serialize = function (parent) {
  34737. return _super.prototype._serialize.call(this, {
  34738. name: "SetParentAction",
  34739. properties: [
  34740. BABYLON.Action._GetTargetProperty(this._target),
  34741. BABYLON.Action._GetTargetProperty(this._parent),
  34742. ]
  34743. }, parent);
  34744. };
  34745. return SetParentAction;
  34746. }(BABYLON.Action));
  34747. BABYLON.SetParentAction = SetParentAction;
  34748. var PlaySoundAction = (function (_super) {
  34749. __extends(PlaySoundAction, _super);
  34750. function PlaySoundAction(triggerOptions, sound, condition) {
  34751. var _this = _super.call(this, triggerOptions, condition) || this;
  34752. _this._sound = sound;
  34753. return _this;
  34754. }
  34755. PlaySoundAction.prototype._prepare = function () {
  34756. };
  34757. PlaySoundAction.prototype.execute = function () {
  34758. if (this._sound !== undefined)
  34759. this._sound.play();
  34760. };
  34761. PlaySoundAction.prototype.serialize = function (parent) {
  34762. return _super.prototype._serialize.call(this, {
  34763. name: "PlaySoundAction",
  34764. properties: [{ name: "sound", value: this._sound.name }]
  34765. }, parent);
  34766. };
  34767. return PlaySoundAction;
  34768. }(BABYLON.Action));
  34769. BABYLON.PlaySoundAction = PlaySoundAction;
  34770. var StopSoundAction = (function (_super) {
  34771. __extends(StopSoundAction, _super);
  34772. function StopSoundAction(triggerOptions, sound, condition) {
  34773. var _this = _super.call(this, triggerOptions, condition) || this;
  34774. _this._sound = sound;
  34775. return _this;
  34776. }
  34777. StopSoundAction.prototype._prepare = function () {
  34778. };
  34779. StopSoundAction.prototype.execute = function () {
  34780. if (this._sound !== undefined)
  34781. this._sound.stop();
  34782. };
  34783. StopSoundAction.prototype.serialize = function (parent) {
  34784. return _super.prototype._serialize.call(this, {
  34785. name: "StopSoundAction",
  34786. properties: [{ name: "sound", value: this._sound.name }]
  34787. }, parent);
  34788. };
  34789. return StopSoundAction;
  34790. }(BABYLON.Action));
  34791. BABYLON.StopSoundAction = StopSoundAction;
  34792. })(BABYLON || (BABYLON = {}));
  34793. //# sourceMappingURL=babylon.directActions.js.map
  34794. var BABYLON;
  34795. (function (BABYLON) {
  34796. var SpriteManager = (function () {
  34797. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  34798. if (epsilon === void 0) { epsilon = 0.01; }
  34799. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34800. this.name = name;
  34801. this.sprites = new Array();
  34802. this.renderingGroupId = 0;
  34803. this.layerMask = 0x0FFFFFFF;
  34804. this.fogEnabled = true;
  34805. this.isPickable = false;
  34806. /**
  34807. * An event triggered when the manager is disposed.
  34808. * @type {BABYLON.Observable}
  34809. */
  34810. this.onDisposeObservable = new BABYLON.Observable();
  34811. this._vertexBuffers = {};
  34812. this._capacity = capacity;
  34813. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  34814. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34815. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34816. if (cellSize.width && cellSize.height) {
  34817. this.cellWidth = cellSize.width;
  34818. this.cellHeight = cellSize.height;
  34819. }
  34820. else if (cellSize !== undefined) {
  34821. this.cellWidth = cellSize;
  34822. this.cellHeight = cellSize;
  34823. }
  34824. else {
  34825. return;
  34826. }
  34827. this._epsilon = epsilon;
  34828. this._scene = scene;
  34829. this._scene.spriteManagers.push(this);
  34830. var indices = [];
  34831. var index = 0;
  34832. for (var count = 0; count < capacity; count++) {
  34833. indices.push(index);
  34834. indices.push(index + 1);
  34835. indices.push(index + 2);
  34836. indices.push(index);
  34837. indices.push(index + 2);
  34838. indices.push(index + 3);
  34839. index += 4;
  34840. }
  34841. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  34842. // VBO
  34843. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  34844. this._vertexData = new Float32Array(capacity * 16 * 4);
  34845. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  34846. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  34847. var options = this._buffer.createVertexBuffer("options", 4, 4);
  34848. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  34849. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  34850. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  34851. this._vertexBuffers["options"] = options;
  34852. this._vertexBuffers["cellInfo"] = cellInfo;
  34853. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  34854. // Effects
  34855. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  34856. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  34857. }
  34858. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  34859. set: function (callback) {
  34860. if (this._onDisposeObserver) {
  34861. this.onDisposeObservable.remove(this._onDisposeObserver);
  34862. }
  34863. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34864. },
  34865. enumerable: true,
  34866. configurable: true
  34867. });
  34868. Object.defineProperty(SpriteManager.prototype, "texture", {
  34869. get: function () {
  34870. return this._spriteTexture;
  34871. },
  34872. set: function (value) {
  34873. this._spriteTexture = value;
  34874. },
  34875. enumerable: true,
  34876. configurable: true
  34877. });
  34878. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  34879. var arrayOffset = index * 16;
  34880. if (offsetX === 0)
  34881. offsetX = this._epsilon;
  34882. else if (offsetX === 1)
  34883. offsetX = 1 - this._epsilon;
  34884. if (offsetY === 0)
  34885. offsetY = this._epsilon;
  34886. else if (offsetY === 1)
  34887. offsetY = 1 - this._epsilon;
  34888. this._vertexData[arrayOffset] = sprite.position.x;
  34889. this._vertexData[arrayOffset + 1] = sprite.position.y;
  34890. this._vertexData[arrayOffset + 2] = sprite.position.z;
  34891. this._vertexData[arrayOffset + 3] = sprite.angle;
  34892. this._vertexData[arrayOffset + 4] = sprite.width;
  34893. this._vertexData[arrayOffset + 5] = sprite.height;
  34894. this._vertexData[arrayOffset + 6] = offsetX;
  34895. this._vertexData[arrayOffset + 7] = offsetY;
  34896. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  34897. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  34898. var offset = (sprite.cellIndex / rowSize) >> 0;
  34899. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  34900. this._vertexData[arrayOffset + 11] = offset;
  34901. // Color
  34902. this._vertexData[arrayOffset + 12] = sprite.color.r;
  34903. this._vertexData[arrayOffset + 13] = sprite.color.g;
  34904. this._vertexData[arrayOffset + 14] = sprite.color.b;
  34905. this._vertexData[arrayOffset + 15] = sprite.color.a;
  34906. };
  34907. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  34908. var count = Math.min(this._capacity, this.sprites.length);
  34909. var min = BABYLON.Vector3.Zero();
  34910. var max = BABYLON.Vector3.Zero();
  34911. var distance = Number.MAX_VALUE;
  34912. var currentSprite;
  34913. var cameraSpacePosition = BABYLON.Vector3.Zero();
  34914. var cameraView = camera.getViewMatrix();
  34915. for (var index = 0; index < count; index++) {
  34916. var sprite = this.sprites[index];
  34917. if (!sprite) {
  34918. continue;
  34919. }
  34920. if (predicate) {
  34921. if (!predicate(sprite)) {
  34922. continue;
  34923. }
  34924. }
  34925. else if (!sprite.isPickable) {
  34926. continue;
  34927. }
  34928. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  34929. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  34930. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  34931. if (ray.intersectsBoxMinMax(min, max)) {
  34932. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  34933. if (distance > currentDistance) {
  34934. distance = currentDistance;
  34935. currentSprite = sprite;
  34936. if (fastCheck) {
  34937. break;
  34938. }
  34939. }
  34940. }
  34941. }
  34942. if (currentSprite) {
  34943. var result = new BABYLON.PickingInfo();
  34944. result.hit = true;
  34945. result.pickedSprite = currentSprite;
  34946. result.distance = distance;
  34947. return result;
  34948. }
  34949. return null;
  34950. };
  34951. SpriteManager.prototype.render = function () {
  34952. // Check
  34953. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  34954. return;
  34955. var engine = this._scene.getEngine();
  34956. var baseSize = this._spriteTexture.getBaseSize();
  34957. // Sprites
  34958. var deltaTime = engine.getDeltaTime();
  34959. var max = Math.min(this._capacity, this.sprites.length);
  34960. var rowSize = baseSize.width / this.cellWidth;
  34961. var offset = 0;
  34962. for (var index = 0; index < max; index++) {
  34963. var sprite = this.sprites[index];
  34964. if (!sprite) {
  34965. continue;
  34966. }
  34967. sprite._animate(deltaTime);
  34968. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  34969. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  34970. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  34971. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  34972. }
  34973. this._buffer.update(this._vertexData);
  34974. // Render
  34975. var effect = this._effectBase;
  34976. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  34977. effect = this._effectFog;
  34978. }
  34979. engine.enableEffect(effect);
  34980. var viewMatrix = this._scene.getViewMatrix();
  34981. effect.setTexture("diffuseSampler", this._spriteTexture);
  34982. effect.setMatrix("view", viewMatrix);
  34983. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  34984. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  34985. // Fog
  34986. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  34987. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  34988. effect.setColor3("vFogColor", this._scene.fogColor);
  34989. }
  34990. // VBOs
  34991. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34992. // Draw order
  34993. engine.setDepthFunctionToLessOrEqual();
  34994. effect.setBool("alphaTest", true);
  34995. engine.setColorWrite(false);
  34996. engine.draw(true, 0, max * 6);
  34997. engine.setColorWrite(true);
  34998. effect.setBool("alphaTest", false);
  34999. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  35000. engine.draw(true, 0, max * 6);
  35001. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  35002. };
  35003. SpriteManager.prototype.dispose = function () {
  35004. if (this._buffer) {
  35005. this._buffer.dispose();
  35006. this._buffer = null;
  35007. }
  35008. if (this._indexBuffer) {
  35009. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  35010. this._indexBuffer = null;
  35011. }
  35012. if (this._spriteTexture) {
  35013. this._spriteTexture.dispose();
  35014. this._spriteTexture = null;
  35015. }
  35016. // Remove from scene
  35017. var index = this._scene.spriteManagers.indexOf(this);
  35018. this._scene.spriteManagers.splice(index, 1);
  35019. // Callback
  35020. this.onDisposeObservable.notifyObservers(this);
  35021. this.onDisposeObservable.clear();
  35022. };
  35023. return SpriteManager;
  35024. }());
  35025. BABYLON.SpriteManager = SpriteManager;
  35026. })(BABYLON || (BABYLON = {}));
  35027. //# sourceMappingURL=babylon.spriteManager.js.map
  35028. var BABYLON;
  35029. (function (BABYLON) {
  35030. var Sprite = (function () {
  35031. function Sprite(name, manager) {
  35032. this.name = name;
  35033. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  35034. this.width = 1.0;
  35035. this.height = 1.0;
  35036. this.angle = 0;
  35037. this.cellIndex = 0;
  35038. this.invertU = 0;
  35039. this.invertV = 0;
  35040. this.animations = new Array();
  35041. this.isPickable = false;
  35042. this._animationStarted = false;
  35043. this._loopAnimation = false;
  35044. this._fromIndex = 0;
  35045. this._toIndex = 0;
  35046. this._delay = 0;
  35047. this._direction = 1;
  35048. this._frameCount = 0;
  35049. this._time = 0;
  35050. this._manager = manager;
  35051. this._manager.sprites.push(this);
  35052. this.position = BABYLON.Vector3.Zero();
  35053. }
  35054. Object.defineProperty(Sprite.prototype, "size", {
  35055. get: function () {
  35056. return this.width;
  35057. },
  35058. set: function (value) {
  35059. this.width = value;
  35060. this.height = value;
  35061. },
  35062. enumerable: true,
  35063. configurable: true
  35064. });
  35065. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  35066. this._fromIndex = from;
  35067. this._toIndex = to;
  35068. this._loopAnimation = loop;
  35069. this._delay = delay;
  35070. this._animationStarted = true;
  35071. this._direction = from < to ? 1 : -1;
  35072. this.cellIndex = from;
  35073. this._time = 0;
  35074. this._onAnimationEnd = onAnimationEnd;
  35075. };
  35076. Sprite.prototype.stopAnimation = function () {
  35077. this._animationStarted = false;
  35078. };
  35079. Sprite.prototype._animate = function (deltaTime) {
  35080. if (!this._animationStarted)
  35081. return;
  35082. this._time += deltaTime;
  35083. if (this._time > this._delay) {
  35084. this._time = this._time % this._delay;
  35085. this.cellIndex += this._direction;
  35086. if (this.cellIndex === this._toIndex) {
  35087. if (this._loopAnimation) {
  35088. this.cellIndex = this._fromIndex;
  35089. }
  35090. else {
  35091. this._animationStarted = false;
  35092. if (this._onAnimationEnd) {
  35093. this._onAnimationEnd();
  35094. }
  35095. if (this.disposeWhenFinishedAnimating) {
  35096. this.dispose();
  35097. }
  35098. }
  35099. }
  35100. }
  35101. };
  35102. Sprite.prototype.dispose = function () {
  35103. for (var i = 0; i < this._manager.sprites.length; i++) {
  35104. if (this._manager.sprites[i] == this) {
  35105. this._manager.sprites.splice(i, 1);
  35106. }
  35107. }
  35108. };
  35109. return Sprite;
  35110. }());
  35111. BABYLON.Sprite = Sprite;
  35112. })(BABYLON || (BABYLON = {}));
  35113. //# sourceMappingURL=babylon.sprite.js.map
  35114. var BABYLON;
  35115. (function (BABYLON) {
  35116. var IntersectionInfo = (function () {
  35117. function IntersectionInfo(bu, bv, distance) {
  35118. this.bu = bu;
  35119. this.bv = bv;
  35120. this.distance = distance;
  35121. this.faceId = 0;
  35122. this.subMeshId = 0;
  35123. }
  35124. return IntersectionInfo;
  35125. }());
  35126. BABYLON.IntersectionInfo = IntersectionInfo;
  35127. var PickingInfo = (function () {
  35128. function PickingInfo() {
  35129. this.hit = false;
  35130. this.distance = 0;
  35131. this.pickedPoint = null;
  35132. this.pickedMesh = null;
  35133. this.bu = 0;
  35134. this.bv = 0;
  35135. this.faceId = -1;
  35136. this.subMeshId = 0;
  35137. this.pickedSprite = null;
  35138. }
  35139. // Methods
  35140. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  35141. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  35142. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  35143. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35144. return null;
  35145. }
  35146. var indices = this.pickedMesh.getIndices();
  35147. var result;
  35148. if (useVerticesNormals) {
  35149. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35150. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  35151. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  35152. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  35153. normal0 = normal0.scale(this.bu);
  35154. normal1 = normal1.scale(this.bv);
  35155. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  35156. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  35157. }
  35158. else {
  35159. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35160. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  35161. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  35162. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  35163. var p1p2 = vertex1.subtract(vertex2);
  35164. var p3p2 = vertex3.subtract(vertex2);
  35165. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  35166. }
  35167. if (useWorldCoordinates) {
  35168. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  35169. }
  35170. return BABYLON.Vector3.Normalize(result);
  35171. };
  35172. PickingInfo.prototype.getTextureCoordinates = function () {
  35173. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35174. return null;
  35175. }
  35176. var indices = this.pickedMesh.getIndices();
  35177. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  35178. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  35179. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  35180. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  35181. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  35182. uv1 = uv1.scale(this.bu);
  35183. uv2 = uv2.scale(this.bv);
  35184. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  35185. };
  35186. return PickingInfo;
  35187. }());
  35188. BABYLON.PickingInfo = PickingInfo;
  35189. })(BABYLON || (BABYLON = {}));
  35190. //# sourceMappingURL=babylon.pickingInfo.js.map
  35191. var BABYLON;
  35192. (function (BABYLON) {
  35193. var Ray = (function () {
  35194. function Ray(origin, direction, length) {
  35195. if (length === void 0) { length = Number.MAX_VALUE; }
  35196. this.origin = origin;
  35197. this.direction = direction;
  35198. this.length = length;
  35199. }
  35200. // Methods
  35201. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  35202. var d = 0.0;
  35203. var maxValue = Number.MAX_VALUE;
  35204. var inv;
  35205. var min;
  35206. var max;
  35207. var temp;
  35208. if (Math.abs(this.direction.x) < 0.0000001) {
  35209. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  35210. return false;
  35211. }
  35212. }
  35213. else {
  35214. inv = 1.0 / this.direction.x;
  35215. min = (minimum.x - this.origin.x) * inv;
  35216. max = (maximum.x - this.origin.x) * inv;
  35217. if (max === -Infinity) {
  35218. max = Infinity;
  35219. }
  35220. if (min > max) {
  35221. temp = min;
  35222. min = max;
  35223. max = temp;
  35224. }
  35225. d = Math.max(min, d);
  35226. maxValue = Math.min(max, maxValue);
  35227. if (d > maxValue) {
  35228. return false;
  35229. }
  35230. }
  35231. if (Math.abs(this.direction.y) < 0.0000001) {
  35232. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  35233. return false;
  35234. }
  35235. }
  35236. else {
  35237. inv = 1.0 / this.direction.y;
  35238. min = (minimum.y - this.origin.y) * inv;
  35239. max = (maximum.y - this.origin.y) * inv;
  35240. if (max === -Infinity) {
  35241. max = Infinity;
  35242. }
  35243. if (min > max) {
  35244. temp = min;
  35245. min = max;
  35246. max = temp;
  35247. }
  35248. d = Math.max(min, d);
  35249. maxValue = Math.min(max, maxValue);
  35250. if (d > maxValue) {
  35251. return false;
  35252. }
  35253. }
  35254. if (Math.abs(this.direction.z) < 0.0000001) {
  35255. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  35256. return false;
  35257. }
  35258. }
  35259. else {
  35260. inv = 1.0 / this.direction.z;
  35261. min = (minimum.z - this.origin.z) * inv;
  35262. max = (maximum.z - this.origin.z) * inv;
  35263. if (max === -Infinity) {
  35264. max = Infinity;
  35265. }
  35266. if (min > max) {
  35267. temp = min;
  35268. min = max;
  35269. max = temp;
  35270. }
  35271. d = Math.max(min, d);
  35272. maxValue = Math.min(max, maxValue);
  35273. if (d > maxValue) {
  35274. return false;
  35275. }
  35276. }
  35277. return true;
  35278. };
  35279. Ray.prototype.intersectsBox = function (box) {
  35280. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  35281. };
  35282. Ray.prototype.intersectsSphere = function (sphere) {
  35283. var x = sphere.center.x - this.origin.x;
  35284. var y = sphere.center.y - this.origin.y;
  35285. var z = sphere.center.z - this.origin.z;
  35286. var pyth = (x * x) + (y * y) + (z * z);
  35287. var rr = sphere.radius * sphere.radius;
  35288. if (pyth <= rr) {
  35289. return true;
  35290. }
  35291. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  35292. if (dot < 0.0) {
  35293. return false;
  35294. }
  35295. var temp = pyth - (dot * dot);
  35296. return temp <= rr;
  35297. };
  35298. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  35299. if (!this._edge1) {
  35300. this._edge1 = BABYLON.Vector3.Zero();
  35301. this._edge2 = BABYLON.Vector3.Zero();
  35302. this._pvec = BABYLON.Vector3.Zero();
  35303. this._tvec = BABYLON.Vector3.Zero();
  35304. this._qvec = BABYLON.Vector3.Zero();
  35305. }
  35306. vertex1.subtractToRef(vertex0, this._edge1);
  35307. vertex2.subtractToRef(vertex0, this._edge2);
  35308. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  35309. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  35310. if (det === 0) {
  35311. return null;
  35312. }
  35313. var invdet = 1 / det;
  35314. this.origin.subtractToRef(vertex0, this._tvec);
  35315. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  35316. if (bu < 0 || bu > 1.0) {
  35317. return null;
  35318. }
  35319. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  35320. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  35321. if (bv < 0 || bu + bv > 1.0) {
  35322. return null;
  35323. }
  35324. //check if the distance is longer than the predefined length.
  35325. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  35326. if (distance > this.length) {
  35327. return null;
  35328. }
  35329. return new BABYLON.IntersectionInfo(bu, bv, distance);
  35330. };
  35331. Ray.prototype.intersectsPlane = function (plane) {
  35332. var distance;
  35333. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  35334. if (Math.abs(result1) < 9.99999997475243E-07) {
  35335. return null;
  35336. }
  35337. else {
  35338. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  35339. distance = (-plane.d - result2) / result1;
  35340. if (distance < 0.0) {
  35341. if (distance < -9.99999997475243E-07) {
  35342. return null;
  35343. }
  35344. else {
  35345. return 0;
  35346. }
  35347. }
  35348. return distance;
  35349. }
  35350. };
  35351. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  35352. var tm = BABYLON.Tmp.Matrix[0];
  35353. mesh.getWorldMatrix().invertToRef(tm);
  35354. if (this._tmpRay) {
  35355. Ray.TransformToRef(this, tm, this._tmpRay);
  35356. }
  35357. else {
  35358. this._tmpRay = Ray.Transform(this, tm);
  35359. }
  35360. return mesh.intersects(this._tmpRay, fastCheck);
  35361. };
  35362. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  35363. if (results) {
  35364. results.length = 0;
  35365. }
  35366. else {
  35367. results = [];
  35368. }
  35369. for (var i = 0; i < meshes.length; i++) {
  35370. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  35371. if (pickInfo.hit) {
  35372. results.push(pickInfo);
  35373. }
  35374. }
  35375. results.sort(this._comparePickingInfo);
  35376. return results;
  35377. };
  35378. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  35379. if (pickingInfoA.distance < pickingInfoB.distance) {
  35380. return -1;
  35381. }
  35382. else if (pickingInfoA.distance > pickingInfoB.distance) {
  35383. return 1;
  35384. }
  35385. else {
  35386. return 0;
  35387. }
  35388. };
  35389. /**
  35390. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  35391. * @param sega the first point of the segment to test the intersection against
  35392. * @param segb the second point of the segment to test the intersection against
  35393. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  35394. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  35395. */
  35396. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  35397. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  35398. var u = segb.subtract(sega);
  35399. var v = rsegb.subtract(this.origin);
  35400. var w = sega.subtract(this.origin);
  35401. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  35402. var b = BABYLON.Vector3.Dot(u, v);
  35403. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  35404. var d = BABYLON.Vector3.Dot(u, w);
  35405. var e = BABYLON.Vector3.Dot(v, w);
  35406. var D = a * c - b * b; // always >= 0
  35407. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  35408. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  35409. // compute the line parameters of the two closest points
  35410. if (D < Ray.smallnum) {
  35411. sN = 0.0; // force using point P0 on segment S1
  35412. sD = 1.0; // to prevent possible division by 0.0 later
  35413. tN = e;
  35414. tD = c;
  35415. }
  35416. else {
  35417. sN = (b * e - c * d);
  35418. tN = (a * e - b * d);
  35419. if (sN < 0.0) {
  35420. sN = 0.0;
  35421. tN = e;
  35422. tD = c;
  35423. }
  35424. else if (sN > sD) {
  35425. sN = sD;
  35426. tN = e + b;
  35427. tD = c;
  35428. }
  35429. }
  35430. if (tN < 0.0) {
  35431. tN = 0.0;
  35432. // recompute sc for this edge
  35433. if (-d < 0.0) {
  35434. sN = 0.0;
  35435. }
  35436. else if (-d > a)
  35437. sN = sD;
  35438. else {
  35439. sN = -d;
  35440. sD = a;
  35441. }
  35442. }
  35443. else if (tN > tD) {
  35444. tN = tD;
  35445. // recompute sc for this edge
  35446. if ((-d + b) < 0.0) {
  35447. sN = 0;
  35448. }
  35449. else if ((-d + b) > a) {
  35450. sN = sD;
  35451. }
  35452. else {
  35453. sN = (-d + b);
  35454. sD = a;
  35455. }
  35456. }
  35457. // finally do the division to get sc and tc
  35458. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  35459. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  35460. // get the difference of the two closest points
  35461. var qtc = v.multiplyByFloats(tc, tc, tc);
  35462. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  35463. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  35464. if (isIntersected) {
  35465. return qtc.length();
  35466. }
  35467. return -1;
  35468. };
  35469. // Statics
  35470. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  35471. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  35472. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  35473. var direction = end.subtract(start);
  35474. direction.normalize();
  35475. return new Ray(start, direction);
  35476. };
  35477. /**
  35478. * 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
  35479. * transformed to the given world matrix.
  35480. * @param origin The origin point
  35481. * @param end The end point
  35482. * @param world a matrix to transform the ray to. Default is the identity matrix.
  35483. */
  35484. Ray.CreateNewFromTo = function (origin, end, world) {
  35485. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  35486. var direction = end.subtract(origin);
  35487. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  35488. direction.normalize();
  35489. return Ray.Transform(new Ray(origin, direction, length), world);
  35490. };
  35491. Ray.Transform = function (ray, matrix) {
  35492. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  35493. Ray.TransformToRef(ray, matrix, result);
  35494. return result;
  35495. };
  35496. Ray.TransformToRef = function (ray, matrix, result) {
  35497. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  35498. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  35499. result.length = ray.length;
  35500. var dir = result.direction;
  35501. var len = dir.length();
  35502. if (!(len === 0 || len === 1)) {
  35503. var num = 1.0 / len;
  35504. dir.x *= num;
  35505. dir.y *= num;
  35506. dir.z *= num;
  35507. result.length *= len;
  35508. }
  35509. };
  35510. return Ray;
  35511. }());
  35512. Ray.smallnum = 0.00000001;
  35513. Ray.rayl = 10e8;
  35514. BABYLON.Ray = Ray;
  35515. })(BABYLON || (BABYLON = {}));
  35516. //# sourceMappingURL=babylon.ray.js.map
  35517. var BABYLON;
  35518. (function (BABYLON) {
  35519. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  35520. if (boxMin.x > sphereCenter.x + sphereRadius)
  35521. return false;
  35522. if (sphereCenter.x - sphereRadius > boxMax.x)
  35523. return false;
  35524. if (boxMin.y > sphereCenter.y + sphereRadius)
  35525. return false;
  35526. if (sphereCenter.y - sphereRadius > boxMax.y)
  35527. return false;
  35528. if (boxMin.z > sphereCenter.z + sphereRadius)
  35529. return false;
  35530. if (sphereCenter.z - sphereRadius > boxMax.z)
  35531. return false;
  35532. return true;
  35533. };
  35534. var getLowestRoot = (function () {
  35535. var result = { root: 0, found: false };
  35536. return function (a, b, c, maxR) {
  35537. result.root = 0;
  35538. result.found = false;
  35539. var determinant = b * b - 4.0 * a * c;
  35540. if (determinant < 0)
  35541. return result;
  35542. var sqrtD = Math.sqrt(determinant);
  35543. var r1 = (-b - sqrtD) / (2.0 * a);
  35544. var r2 = (-b + sqrtD) / (2.0 * a);
  35545. if (r1 > r2) {
  35546. var temp = r2;
  35547. r2 = r1;
  35548. r1 = temp;
  35549. }
  35550. if (r1 > 0 && r1 < maxR) {
  35551. result.root = r1;
  35552. result.found = true;
  35553. return result;
  35554. }
  35555. if (r2 > 0 && r2 < maxR) {
  35556. result.root = r2;
  35557. result.found = true;
  35558. return result;
  35559. }
  35560. return result;
  35561. };
  35562. })();
  35563. var Collider = (function () {
  35564. function Collider() {
  35565. this.radius = new BABYLON.Vector3(1, 1, 1);
  35566. this.retry = 0;
  35567. this.basePointWorld = BABYLON.Vector3.Zero();
  35568. this.velocityWorld = BABYLON.Vector3.Zero();
  35569. this.normalizedVelocity = BABYLON.Vector3.Zero();
  35570. this._collisionPoint = BABYLON.Vector3.Zero();
  35571. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  35572. this._tempVector = BABYLON.Vector3.Zero();
  35573. this._tempVector2 = BABYLON.Vector3.Zero();
  35574. this._tempVector3 = BABYLON.Vector3.Zero();
  35575. this._tempVector4 = BABYLON.Vector3.Zero();
  35576. this._edge = BABYLON.Vector3.Zero();
  35577. this._baseToVertex = BABYLON.Vector3.Zero();
  35578. this._destinationPoint = BABYLON.Vector3.Zero();
  35579. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  35580. this._displacementVector = BABYLON.Vector3.Zero();
  35581. this._collisionMask = -1;
  35582. }
  35583. Object.defineProperty(Collider.prototype, "collisionMask", {
  35584. get: function () {
  35585. return this._collisionMask;
  35586. },
  35587. set: function (mask) {
  35588. this._collisionMask = !isNaN(mask) ? mask : -1;
  35589. },
  35590. enumerable: true,
  35591. configurable: true
  35592. });
  35593. // Methods
  35594. Collider.prototype._initialize = function (source, dir, e) {
  35595. this.velocity = dir;
  35596. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  35597. this.basePoint = source;
  35598. source.multiplyToRef(this.radius, this.basePointWorld);
  35599. dir.multiplyToRef(this.radius, this.velocityWorld);
  35600. this.velocityWorldLength = this.velocityWorld.length();
  35601. this.epsilon = e;
  35602. this.collisionFound = false;
  35603. };
  35604. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  35605. pa.subtractToRef(point, this._tempVector);
  35606. pb.subtractToRef(point, this._tempVector2);
  35607. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  35608. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  35609. if (d < 0)
  35610. return false;
  35611. pc.subtractToRef(point, this._tempVector3);
  35612. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  35613. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  35614. if (d < 0)
  35615. return false;
  35616. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  35617. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  35618. return d >= 0;
  35619. };
  35620. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  35621. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  35622. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  35623. if (distance > this.velocityWorldLength + max + sphereRadius) {
  35624. return false;
  35625. }
  35626. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  35627. return false;
  35628. return true;
  35629. };
  35630. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  35631. var t0;
  35632. var embeddedInPlane = false;
  35633. //defensive programming, actually not needed.
  35634. if (!trianglePlaneArray) {
  35635. trianglePlaneArray = [];
  35636. }
  35637. if (!trianglePlaneArray[faceIndex]) {
  35638. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  35639. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  35640. }
  35641. var trianglePlane = trianglePlaneArray[faceIndex];
  35642. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  35643. return;
  35644. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  35645. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  35646. if (normalDotVelocity == 0) {
  35647. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  35648. return;
  35649. embeddedInPlane = true;
  35650. t0 = 0;
  35651. }
  35652. else {
  35653. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  35654. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  35655. if (t0 > t1) {
  35656. var temp = t1;
  35657. t1 = t0;
  35658. t0 = temp;
  35659. }
  35660. if (t0 > 1.0 || t1 < 0.0)
  35661. return;
  35662. if (t0 < 0)
  35663. t0 = 0;
  35664. if (t0 > 1.0)
  35665. t0 = 1.0;
  35666. }
  35667. this._collisionPoint.copyFromFloats(0, 0, 0);
  35668. var found = false;
  35669. var t = 1.0;
  35670. if (!embeddedInPlane) {
  35671. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  35672. this.velocity.scaleToRef(t0, this._tempVector);
  35673. this._planeIntersectionPoint.addInPlace(this._tempVector);
  35674. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  35675. found = true;
  35676. t = t0;
  35677. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  35678. }
  35679. }
  35680. if (!found) {
  35681. var velocitySquaredLength = this.velocity.lengthSquared();
  35682. var a = velocitySquaredLength;
  35683. this.basePoint.subtractToRef(p1, this._tempVector);
  35684. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  35685. var c = this._tempVector.lengthSquared() - 1.0;
  35686. var lowestRoot = getLowestRoot(a, b, c, t);
  35687. if (lowestRoot.found) {
  35688. t = lowestRoot.root;
  35689. found = true;
  35690. this._collisionPoint.copyFrom(p1);
  35691. }
  35692. this.basePoint.subtractToRef(p2, this._tempVector);
  35693. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  35694. c = this._tempVector.lengthSquared() - 1.0;
  35695. lowestRoot = getLowestRoot(a, b, c, t);
  35696. if (lowestRoot.found) {
  35697. t = lowestRoot.root;
  35698. found = true;
  35699. this._collisionPoint.copyFrom(p2);
  35700. }
  35701. this.basePoint.subtractToRef(p3, this._tempVector);
  35702. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  35703. c = this._tempVector.lengthSquared() - 1.0;
  35704. lowestRoot = getLowestRoot(a, b, c, t);
  35705. if (lowestRoot.found) {
  35706. t = lowestRoot.root;
  35707. found = true;
  35708. this._collisionPoint.copyFrom(p3);
  35709. }
  35710. p2.subtractToRef(p1, this._edge);
  35711. p1.subtractToRef(this.basePoint, this._baseToVertex);
  35712. var edgeSquaredLength = this._edge.lengthSquared();
  35713. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  35714. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  35715. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  35716. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  35717. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  35718. lowestRoot = getLowestRoot(a, b, c, t);
  35719. if (lowestRoot.found) {
  35720. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  35721. if (f >= 0.0 && f <= 1.0) {
  35722. t = lowestRoot.root;
  35723. found = true;
  35724. this._edge.scaleInPlace(f);
  35725. p1.addToRef(this._edge, this._collisionPoint);
  35726. }
  35727. }
  35728. p3.subtractToRef(p2, this._edge);
  35729. p2.subtractToRef(this.basePoint, this._baseToVertex);
  35730. edgeSquaredLength = this._edge.lengthSquared();
  35731. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  35732. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  35733. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  35734. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  35735. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  35736. lowestRoot = getLowestRoot(a, b, c, t);
  35737. if (lowestRoot.found) {
  35738. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  35739. if (f >= 0.0 && f <= 1.0) {
  35740. t = lowestRoot.root;
  35741. found = true;
  35742. this._edge.scaleInPlace(f);
  35743. p2.addToRef(this._edge, this._collisionPoint);
  35744. }
  35745. }
  35746. p1.subtractToRef(p3, this._edge);
  35747. p3.subtractToRef(this.basePoint, this._baseToVertex);
  35748. edgeSquaredLength = this._edge.lengthSquared();
  35749. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  35750. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  35751. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  35752. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  35753. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  35754. lowestRoot = getLowestRoot(a, b, c, t);
  35755. if (lowestRoot.found) {
  35756. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  35757. if (f >= 0.0 && f <= 1.0) {
  35758. t = lowestRoot.root;
  35759. found = true;
  35760. this._edge.scaleInPlace(f);
  35761. p3.addToRef(this._edge, this._collisionPoint);
  35762. }
  35763. }
  35764. }
  35765. if (found) {
  35766. var distToCollision = t * this.velocity.length();
  35767. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  35768. if (!this.intersectionPoint) {
  35769. this.intersectionPoint = this._collisionPoint.clone();
  35770. }
  35771. else {
  35772. this.intersectionPoint.copyFrom(this._collisionPoint);
  35773. }
  35774. this.nearestDistance = distToCollision;
  35775. this.collisionFound = true;
  35776. }
  35777. }
  35778. };
  35779. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  35780. for (var i = indexStart; i < indexEnd; i += 3) {
  35781. var p1 = pts[indices[i] - decal];
  35782. var p2 = pts[indices[i + 1] - decal];
  35783. var p3 = pts[indices[i + 2] - decal];
  35784. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  35785. }
  35786. };
  35787. Collider.prototype._getResponse = function (pos, vel) {
  35788. pos.addToRef(vel, this._destinationPoint);
  35789. vel.scaleInPlace((this.nearestDistance / vel.length()));
  35790. this.basePoint.addToRef(vel, pos);
  35791. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  35792. this._slidePlaneNormal.normalize();
  35793. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  35794. pos.addInPlace(this._displacementVector);
  35795. this.intersectionPoint.addInPlace(this._displacementVector);
  35796. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  35797. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  35798. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  35799. };
  35800. return Collider;
  35801. }());
  35802. BABYLON.Collider = Collider;
  35803. })(BABYLON || (BABYLON = {}));
  35804. //# sourceMappingURL=babylon.collider.js.map
  35805. var BABYLON;
  35806. (function (BABYLON) {
  35807. //WebWorker code will be inserted to this variable.
  35808. BABYLON.CollisionWorker = "";
  35809. var WorkerTaskType;
  35810. (function (WorkerTaskType) {
  35811. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  35812. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  35813. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  35814. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  35815. var WorkerReplyType;
  35816. (function (WorkerReplyType) {
  35817. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  35818. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  35819. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  35820. var CollisionCoordinatorWorker = (function () {
  35821. function CollisionCoordinatorWorker() {
  35822. var _this = this;
  35823. this._scaledPosition = BABYLON.Vector3.Zero();
  35824. this._scaledVelocity = BABYLON.Vector3.Zero();
  35825. this.onMeshUpdated = function (mesh) {
  35826. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  35827. };
  35828. this.onGeometryUpdated = function (geometry) {
  35829. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  35830. };
  35831. this._afterRender = function () {
  35832. if (!_this._init)
  35833. return;
  35834. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  35835. return;
  35836. }
  35837. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  35838. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  35839. if (_this._runningUpdated > 4) {
  35840. return;
  35841. }
  35842. ++_this._runningUpdated;
  35843. var payload = {
  35844. updatedMeshes: _this._addUpdateMeshesList,
  35845. updatedGeometries: _this._addUpdateGeometriesList,
  35846. removedGeometries: _this._toRemoveGeometryArray,
  35847. removedMeshes: _this._toRemoveMeshesArray
  35848. };
  35849. var message = {
  35850. payload: payload,
  35851. taskType: WorkerTaskType.UPDATE
  35852. };
  35853. var serializable = [];
  35854. for (var id in payload.updatedGeometries) {
  35855. if (payload.updatedGeometries.hasOwnProperty(id)) {
  35856. //prepare transferables
  35857. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  35858. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  35859. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  35860. }
  35861. }
  35862. _this._worker.postMessage(message, serializable);
  35863. _this._addUpdateMeshesList = {};
  35864. _this._addUpdateGeometriesList = {};
  35865. _this._toRemoveGeometryArray = [];
  35866. _this._toRemoveMeshesArray = [];
  35867. };
  35868. this._onMessageFromWorker = function (e) {
  35869. var returnData = e.data;
  35870. if (returnData.error != WorkerReplyType.SUCCESS) {
  35871. //TODO what errors can be returned from the worker?
  35872. BABYLON.Tools.Warn("error returned from worker!");
  35873. return;
  35874. }
  35875. switch (returnData.taskType) {
  35876. case WorkerTaskType.INIT:
  35877. _this._init = true;
  35878. //Update the worked with ALL of the scene's current state
  35879. _this._scene.meshes.forEach(function (mesh) {
  35880. _this.onMeshAdded(mesh);
  35881. });
  35882. _this._scene.getGeometries().forEach(function (geometry) {
  35883. _this.onGeometryAdded(geometry);
  35884. });
  35885. break;
  35886. case WorkerTaskType.UPDATE:
  35887. _this._runningUpdated--;
  35888. break;
  35889. case WorkerTaskType.COLLIDE:
  35890. _this._runningCollisionTask = false;
  35891. var returnPayload = returnData.payload;
  35892. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  35893. return;
  35894. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  35895. //cleanup
  35896. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  35897. break;
  35898. }
  35899. };
  35900. this._collisionsCallbackArray = [];
  35901. this._init = false;
  35902. this._runningUpdated = 0;
  35903. this._runningCollisionTask = false;
  35904. this._addUpdateMeshesList = {};
  35905. this._addUpdateGeometriesList = {};
  35906. this._toRemoveGeometryArray = [];
  35907. this._toRemoveMeshesArray = [];
  35908. }
  35909. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  35910. if (!this._init)
  35911. return;
  35912. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  35913. return;
  35914. position.divideToRef(collider.radius, this._scaledPosition);
  35915. velocity.divideToRef(collider.radius, this._scaledVelocity);
  35916. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  35917. var payload = {
  35918. collider: {
  35919. position: this._scaledPosition.asArray(),
  35920. velocity: this._scaledVelocity.asArray(),
  35921. radius: collider.radius.asArray()
  35922. },
  35923. collisionId: collisionIndex,
  35924. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  35925. maximumRetry: maximumRetry
  35926. };
  35927. var message = {
  35928. payload: payload,
  35929. taskType: WorkerTaskType.COLLIDE
  35930. };
  35931. this._worker.postMessage(message);
  35932. };
  35933. CollisionCoordinatorWorker.prototype.init = function (scene) {
  35934. this._scene = scene;
  35935. this._scene.registerAfterRender(this._afterRender);
  35936. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  35937. this._worker = new Worker(workerUrl);
  35938. this._worker.onmessage = this._onMessageFromWorker;
  35939. var message = {
  35940. payload: {},
  35941. taskType: WorkerTaskType.INIT
  35942. };
  35943. this._worker.postMessage(message);
  35944. };
  35945. CollisionCoordinatorWorker.prototype.destroy = function () {
  35946. this._scene.unregisterAfterRender(this._afterRender);
  35947. this._worker.terminate();
  35948. };
  35949. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  35950. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  35951. this.onMeshUpdated(mesh);
  35952. };
  35953. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  35954. this._toRemoveMeshesArray.push(mesh.uniqueId);
  35955. };
  35956. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  35957. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  35958. geometry.onGeometryUpdated = this.onGeometryUpdated;
  35959. this.onGeometryUpdated(geometry);
  35960. };
  35961. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  35962. this._toRemoveGeometryArray.push(geometry.id);
  35963. };
  35964. return CollisionCoordinatorWorker;
  35965. }());
  35966. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  35967. var submeshes = [];
  35968. if (mesh.subMeshes) {
  35969. submeshes = mesh.subMeshes.map(function (sm, idx) {
  35970. return {
  35971. position: idx,
  35972. verticesStart: sm.verticesStart,
  35973. verticesCount: sm.verticesCount,
  35974. indexStart: sm.indexStart,
  35975. indexCount: sm.indexCount,
  35976. hasMaterial: !!sm.getMaterial(),
  35977. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  35978. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  35979. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  35980. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  35981. };
  35982. });
  35983. }
  35984. var geometryId = null;
  35985. if (mesh instanceof BABYLON.Mesh) {
  35986. geometryId = mesh.geometry ? mesh.geometry.id : null;
  35987. }
  35988. else if (mesh instanceof BABYLON.InstancedMesh) {
  35989. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  35990. }
  35991. return {
  35992. uniqueId: mesh.uniqueId,
  35993. id: mesh.id,
  35994. name: mesh.name,
  35995. geometryId: geometryId,
  35996. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  35997. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  35998. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  35999. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  36000. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  36001. subMeshes: submeshes,
  36002. checkCollisions: mesh.checkCollisions
  36003. };
  36004. };
  36005. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  36006. return {
  36007. id: geometry.id,
  36008. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  36009. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  36010. indices: new Uint32Array(geometry.getIndices() || []),
  36011. };
  36012. };
  36013. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  36014. var CollisionCoordinatorLegacy = (function () {
  36015. function CollisionCoordinatorLegacy() {
  36016. this._scaledPosition = BABYLON.Vector3.Zero();
  36017. this._scaledVelocity = BABYLON.Vector3.Zero();
  36018. this._finalPosition = BABYLON.Vector3.Zero();
  36019. }
  36020. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  36021. position.divideToRef(collider.radius, this._scaledPosition);
  36022. velocity.divideToRef(collider.radius, this._scaledVelocity);
  36023. collider.collidedMesh = null;
  36024. collider.retry = 0;
  36025. collider.initialVelocity = this._scaledVelocity;
  36026. collider.initialPosition = this._scaledPosition;
  36027. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  36028. this._finalPosition.multiplyInPlace(collider.radius);
  36029. //run the callback
  36030. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  36031. };
  36032. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  36033. this._scene = scene;
  36034. };
  36035. CollisionCoordinatorLegacy.prototype.destroy = function () {
  36036. //Legacy need no destruction method.
  36037. };
  36038. //No update in legacy mode
  36039. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  36040. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  36041. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  36042. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  36043. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  36044. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  36045. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  36046. if (excludedMesh === void 0) { excludedMesh = null; }
  36047. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  36048. if (collider.retry >= maximumRetry) {
  36049. finalPosition.copyFrom(position);
  36050. return;
  36051. }
  36052. // Check if this is a mesh else camera or -1
  36053. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  36054. collider._initialize(position, velocity, closeDistance);
  36055. // Check all meshes
  36056. for (var index = 0; index < this._scene.meshes.length; index++) {
  36057. var mesh = this._scene.meshes[index];
  36058. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  36059. mesh._checkCollision(collider);
  36060. }
  36061. }
  36062. if (!collider.collisionFound) {
  36063. position.addToRef(velocity, finalPosition);
  36064. return;
  36065. }
  36066. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  36067. collider._getResponse(position, velocity);
  36068. }
  36069. if (velocity.length() <= closeDistance) {
  36070. finalPosition.copyFrom(position);
  36071. return;
  36072. }
  36073. collider.retry++;
  36074. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  36075. };
  36076. return CollisionCoordinatorLegacy;
  36077. }());
  36078. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  36079. })(BABYLON || (BABYLON = {}));
  36080. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  36081. var BABYLON;
  36082. (function (BABYLON) {
  36083. var Particle = (function () {
  36084. function Particle() {
  36085. this.position = BABYLON.Vector3.Zero();
  36086. this.direction = BABYLON.Vector3.Zero();
  36087. this.color = new BABYLON.Color4(0, 0, 0, 0);
  36088. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  36089. this.lifeTime = 1.0;
  36090. this.age = 0;
  36091. this.size = 0;
  36092. this.angle = 0;
  36093. this.angularSpeed = 0;
  36094. }
  36095. Particle.prototype.copyTo = function (other) {
  36096. other.position.copyFrom(this.position);
  36097. other.direction.copyFrom(this.direction);
  36098. other.color.copyFrom(this.color);
  36099. other.colorStep.copyFrom(this.colorStep);
  36100. other.lifeTime = this.lifeTime;
  36101. other.age = this.age;
  36102. other.size = this.size;
  36103. other.angle = this.angle;
  36104. other.angularSpeed = this.angularSpeed;
  36105. };
  36106. return Particle;
  36107. }());
  36108. BABYLON.Particle = Particle;
  36109. })(BABYLON || (BABYLON = {}));
  36110. //# sourceMappingURL=babylon.particle.js.map
  36111. var BABYLON;
  36112. (function (BABYLON) {
  36113. var randomNumber = function (min, max) {
  36114. if (min === max) {
  36115. return (min);
  36116. }
  36117. var random = Math.random();
  36118. return ((random * (max - min)) + min);
  36119. };
  36120. var ParticleSystem = (function () {
  36121. function ParticleSystem(name, capacity, scene, customEffect) {
  36122. var _this = this;
  36123. this.name = name;
  36124. // Members
  36125. this.animations = [];
  36126. this.renderingGroupId = 0;
  36127. this.emitter = null;
  36128. this.emitRate = 10;
  36129. this.manualEmitCount = -1;
  36130. this.updateSpeed = 0.01;
  36131. this.targetStopDuration = 0;
  36132. this.disposeOnStop = false;
  36133. this.minEmitPower = 1;
  36134. this.maxEmitPower = 1;
  36135. this.minLifeTime = 1;
  36136. this.maxLifeTime = 1;
  36137. this.minSize = 1;
  36138. this.maxSize = 1;
  36139. this.minAngularSpeed = 0;
  36140. this.maxAngularSpeed = 0;
  36141. this.layerMask = 0x0FFFFFFF;
  36142. this.customShader = null;
  36143. this.preventAutoStart = false;
  36144. /**
  36145. * An event triggered when the system is disposed.
  36146. * @type {BABYLON.Observable}
  36147. */
  36148. this.onDisposeObservable = new BABYLON.Observable();
  36149. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  36150. this.forceDepthWrite = false;
  36151. this.gravity = BABYLON.Vector3.Zero();
  36152. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  36153. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  36154. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  36155. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  36156. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  36157. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  36158. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  36159. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  36160. this.particles = new Array();
  36161. this._stockParticles = new Array();
  36162. this._newPartsExcess = 0;
  36163. this._vertexBuffers = {};
  36164. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  36165. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  36166. this._scaledDirection = BABYLON.Vector3.Zero();
  36167. this._scaledGravity = BABYLON.Vector3.Zero();
  36168. this._currentRenderId = -1;
  36169. this._started = false;
  36170. this._stopped = false;
  36171. this._actualFrame = 0;
  36172. this.id = name;
  36173. this._capacity = capacity;
  36174. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  36175. this._customEffect = customEffect;
  36176. scene.particleSystems.push(this);
  36177. var indices = [];
  36178. var index = 0;
  36179. for (var count = 0; count < capacity; count++) {
  36180. indices.push(index);
  36181. indices.push(index + 1);
  36182. indices.push(index + 2);
  36183. indices.push(index);
  36184. indices.push(index + 2);
  36185. indices.push(index + 3);
  36186. index += 4;
  36187. }
  36188. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  36189. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  36190. this._vertexData = new Float32Array(capacity * 11 * 4);
  36191. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  36192. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  36193. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  36194. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  36195. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  36196. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  36197. this._vertexBuffers["options"] = options;
  36198. // Default behaviors
  36199. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  36200. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  36201. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  36202. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  36203. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  36204. };
  36205. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  36206. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  36207. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  36208. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  36209. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  36210. };
  36211. this.updateFunction = function (particles) {
  36212. for (var index = 0; index < particles.length; index++) {
  36213. var particle = particles[index];
  36214. particle.age += _this._scaledUpdateSpeed;
  36215. if (particle.age >= particle.lifeTime) {
  36216. _this.recycleParticle(particle);
  36217. index--;
  36218. continue;
  36219. }
  36220. else {
  36221. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  36222. particle.color.addInPlace(_this._scaledColorStep);
  36223. if (particle.color.a < 0)
  36224. particle.color.a = 0;
  36225. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  36226. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  36227. particle.position.addInPlace(_this._scaledDirection);
  36228. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  36229. particle.direction.addInPlace(_this._scaledGravity);
  36230. }
  36231. }
  36232. };
  36233. }
  36234. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  36235. set: function (callback) {
  36236. if (this._onDisposeObserver) {
  36237. this.onDisposeObservable.remove(this._onDisposeObserver);
  36238. }
  36239. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  36240. },
  36241. enumerable: true,
  36242. configurable: true
  36243. });
  36244. ParticleSystem.prototype.recycleParticle = function (particle) {
  36245. var lastParticle = this.particles.pop();
  36246. if (lastParticle !== particle) {
  36247. lastParticle.copyTo(particle);
  36248. this._stockParticles.push(lastParticle);
  36249. }
  36250. };
  36251. ParticleSystem.prototype.getCapacity = function () {
  36252. return this._capacity;
  36253. };
  36254. ParticleSystem.prototype.isAlive = function () {
  36255. return this._alive;
  36256. };
  36257. ParticleSystem.prototype.isStarted = function () {
  36258. return this._started;
  36259. };
  36260. ParticleSystem.prototype.start = function () {
  36261. this._started = true;
  36262. this._stopped = false;
  36263. this._actualFrame = 0;
  36264. };
  36265. ParticleSystem.prototype.stop = function () {
  36266. this._stopped = true;
  36267. };
  36268. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  36269. var offset = index * 11;
  36270. this._vertexData[offset] = particle.position.x;
  36271. this._vertexData[offset + 1] = particle.position.y;
  36272. this._vertexData[offset + 2] = particle.position.z;
  36273. this._vertexData[offset + 3] = particle.color.r;
  36274. this._vertexData[offset + 4] = particle.color.g;
  36275. this._vertexData[offset + 5] = particle.color.b;
  36276. this._vertexData[offset + 6] = particle.color.a;
  36277. this._vertexData[offset + 7] = particle.angle;
  36278. this._vertexData[offset + 8] = particle.size;
  36279. this._vertexData[offset + 9] = offsetX;
  36280. this._vertexData[offset + 10] = offsetY;
  36281. };
  36282. ParticleSystem.prototype._update = function (newParticles) {
  36283. // Update current
  36284. this._alive = this.particles.length > 0;
  36285. this.updateFunction(this.particles);
  36286. // Add new ones
  36287. var worldMatrix;
  36288. if (this.emitter.position) {
  36289. worldMatrix = this.emitter.getWorldMatrix();
  36290. }
  36291. else {
  36292. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  36293. }
  36294. var particle;
  36295. for (var index = 0; index < newParticles; index++) {
  36296. if (this.particles.length === this._capacity) {
  36297. break;
  36298. }
  36299. if (this._stockParticles.length !== 0) {
  36300. particle = this._stockParticles.pop();
  36301. particle.age = 0;
  36302. }
  36303. else {
  36304. particle = new BABYLON.Particle();
  36305. }
  36306. this.particles.push(particle);
  36307. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  36308. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  36309. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  36310. particle.size = randomNumber(this.minSize, this.maxSize);
  36311. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  36312. this.startPositionFunction(worldMatrix, particle.position, particle);
  36313. var step = randomNumber(0, 1.0);
  36314. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  36315. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  36316. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  36317. }
  36318. };
  36319. ParticleSystem.prototype._getEffect = function () {
  36320. if (this._customEffect) {
  36321. return this._customEffect;
  36322. }
  36323. ;
  36324. var defines = [];
  36325. if (this._scene.clipPlane) {
  36326. defines.push("#define CLIPPLANE");
  36327. }
  36328. // Effect
  36329. var join = defines.join("\n");
  36330. if (this._cachedDefines !== join) {
  36331. this._cachedDefines = join;
  36332. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  36333. }
  36334. return this._effect;
  36335. };
  36336. ParticleSystem.prototype.animate = function () {
  36337. if (!this._started)
  36338. return;
  36339. var effect = this._getEffect();
  36340. // Check
  36341. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  36342. return;
  36343. if (this._currentRenderId === this._scene.getRenderId()) {
  36344. return;
  36345. }
  36346. this._currentRenderId = this._scene.getRenderId();
  36347. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  36348. // determine the number of particles we need to create
  36349. var newParticles;
  36350. if (this.manualEmitCount > -1) {
  36351. newParticles = this.manualEmitCount;
  36352. this._newPartsExcess = 0;
  36353. this.manualEmitCount = 0;
  36354. }
  36355. else {
  36356. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  36357. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  36358. }
  36359. if (this._newPartsExcess > 1.0) {
  36360. newParticles += this._newPartsExcess >> 0;
  36361. this._newPartsExcess -= this._newPartsExcess >> 0;
  36362. }
  36363. this._alive = false;
  36364. if (!this._stopped) {
  36365. this._actualFrame += this._scaledUpdateSpeed;
  36366. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  36367. this.stop();
  36368. }
  36369. else {
  36370. newParticles = 0;
  36371. }
  36372. this._update(newParticles);
  36373. // Stopped?
  36374. if (this._stopped) {
  36375. if (!this._alive) {
  36376. this._started = false;
  36377. if (this.disposeOnStop) {
  36378. this._scene._toBeDisposed.push(this);
  36379. }
  36380. }
  36381. }
  36382. // Update VBO
  36383. var offset = 0;
  36384. for (var index = 0; index < this.particles.length; index++) {
  36385. var particle = this.particles[index];
  36386. this._appendParticleVertex(offset++, particle, 0, 0);
  36387. this._appendParticleVertex(offset++, particle, 1, 0);
  36388. this._appendParticleVertex(offset++, particle, 1, 1);
  36389. this._appendParticleVertex(offset++, particle, 0, 1);
  36390. }
  36391. this._vertexBuffer.update(this._vertexData);
  36392. };
  36393. ParticleSystem.prototype.render = function () {
  36394. var effect = this._getEffect();
  36395. // Check
  36396. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  36397. return 0;
  36398. var engine = this._scene.getEngine();
  36399. // Render
  36400. engine.enableEffect(effect);
  36401. engine.setState(false);
  36402. var viewMatrix = this._scene.getViewMatrix();
  36403. effect.setTexture("diffuseSampler", this.particleTexture);
  36404. effect.setMatrix("view", viewMatrix);
  36405. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  36406. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  36407. if (this._scene.clipPlane) {
  36408. var clipPlane = this._scene.clipPlane;
  36409. var invView = viewMatrix.clone();
  36410. invView.invert();
  36411. effect.setMatrix("invView", invView);
  36412. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  36413. }
  36414. // VBOs
  36415. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36416. // Draw order
  36417. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  36418. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  36419. }
  36420. else {
  36421. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  36422. }
  36423. if (this.forceDepthWrite) {
  36424. engine.setDepthWrite(true);
  36425. }
  36426. engine.draw(true, 0, this.particles.length * 6);
  36427. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36428. return this.particles.length;
  36429. };
  36430. ParticleSystem.prototype.dispose = function () {
  36431. if (this._vertexBuffer) {
  36432. this._vertexBuffer.dispose();
  36433. this._vertexBuffer = null;
  36434. }
  36435. if (this._indexBuffer) {
  36436. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36437. this._indexBuffer = null;
  36438. }
  36439. if (this.particleTexture) {
  36440. this.particleTexture.dispose();
  36441. this.particleTexture = null;
  36442. }
  36443. // Remove from scene
  36444. var index = this._scene.particleSystems.indexOf(this);
  36445. this._scene.particleSystems.splice(index, 1);
  36446. // Callback
  36447. this.onDisposeObservable.notifyObservers(this);
  36448. this.onDisposeObservable.clear();
  36449. };
  36450. // Clone
  36451. ParticleSystem.prototype.clone = function (name, newEmitter) {
  36452. var custom = null;
  36453. var program = null;
  36454. if (this.customShader != null) {
  36455. program = this.customShader;
  36456. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  36457. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  36458. }
  36459. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  36460. result.customShader = program;
  36461. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  36462. if (newEmitter === undefined) {
  36463. newEmitter = this.emitter;
  36464. }
  36465. result.emitter = newEmitter;
  36466. if (this.particleTexture) {
  36467. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  36468. }
  36469. if (!this.preventAutoStart) {
  36470. result.start();
  36471. }
  36472. return result;
  36473. };
  36474. ParticleSystem.prototype.serialize = function () {
  36475. var serializationObject = {};
  36476. serializationObject.name = this.name;
  36477. serializationObject.id = this.id;
  36478. // Emitter
  36479. if (this.emitter.position) {
  36480. serializationObject.emitterId = this.emitter.id;
  36481. }
  36482. else {
  36483. serializationObject.emitter = this.emitter.asArray();
  36484. }
  36485. serializationObject.capacity = this.getCapacity();
  36486. if (this.particleTexture) {
  36487. serializationObject.textureName = this.particleTexture.name;
  36488. }
  36489. // Animations
  36490. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  36491. // Particle system
  36492. serializationObject.minAngularSpeed = this.minAngularSpeed;
  36493. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  36494. serializationObject.minSize = this.minSize;
  36495. serializationObject.maxSize = this.maxSize;
  36496. serializationObject.minEmitPower = this.minEmitPower;
  36497. serializationObject.maxEmitPower = this.maxEmitPower;
  36498. serializationObject.minLifeTime = this.minLifeTime;
  36499. serializationObject.maxLifeTime = this.maxLifeTime;
  36500. serializationObject.emitRate = this.emitRate;
  36501. serializationObject.minEmitBox = this.minEmitBox.asArray();
  36502. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  36503. serializationObject.gravity = this.gravity.asArray();
  36504. serializationObject.direction1 = this.direction1.asArray();
  36505. serializationObject.direction2 = this.direction2.asArray();
  36506. serializationObject.color1 = this.color1.asArray();
  36507. serializationObject.color2 = this.color2.asArray();
  36508. serializationObject.colorDead = this.colorDead.asArray();
  36509. serializationObject.updateSpeed = this.updateSpeed;
  36510. serializationObject.targetStopDuration = this.targetStopDuration;
  36511. serializationObject.textureMask = this.textureMask.asArray();
  36512. serializationObject.blendMode = this.blendMode;
  36513. serializationObject.customShader = this.customShader;
  36514. serializationObject.preventAutoStart = this.preventAutoStart;
  36515. return serializationObject;
  36516. };
  36517. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  36518. var name = parsedParticleSystem.name;
  36519. var custom = null;
  36520. var program = null;
  36521. if (parsedParticleSystem.customShader) {
  36522. program = parsedParticleSystem.customShader;
  36523. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  36524. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  36525. }
  36526. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  36527. particleSystem.customShader = program;
  36528. if (parsedParticleSystem.id) {
  36529. particleSystem.id = parsedParticleSystem.id;
  36530. }
  36531. // Auto start
  36532. if (parsedParticleSystem.preventAutoStart) {
  36533. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  36534. }
  36535. // Texture
  36536. if (parsedParticleSystem.textureName) {
  36537. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  36538. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  36539. }
  36540. // Emitter
  36541. if (parsedParticleSystem.emitterId) {
  36542. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  36543. }
  36544. else {
  36545. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  36546. }
  36547. // Animations
  36548. if (parsedParticleSystem.animations) {
  36549. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  36550. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  36551. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  36552. }
  36553. }
  36554. if (parsedParticleSystem.autoAnimate) {
  36555. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  36556. }
  36557. // Particle system
  36558. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  36559. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  36560. particleSystem.minSize = parsedParticleSystem.minSize;
  36561. particleSystem.maxSize = parsedParticleSystem.maxSize;
  36562. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  36563. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  36564. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  36565. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  36566. particleSystem.emitRate = parsedParticleSystem.emitRate;
  36567. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  36568. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  36569. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  36570. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  36571. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  36572. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  36573. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  36574. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  36575. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  36576. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  36577. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  36578. particleSystem.blendMode = parsedParticleSystem.blendMode;
  36579. if (!particleSystem.preventAutoStart) {
  36580. particleSystem.start();
  36581. }
  36582. return particleSystem;
  36583. };
  36584. return ParticleSystem;
  36585. }());
  36586. // Statics
  36587. ParticleSystem.BLENDMODE_ONEONE = 0;
  36588. ParticleSystem.BLENDMODE_STANDARD = 1;
  36589. BABYLON.ParticleSystem = ParticleSystem;
  36590. })(BABYLON || (BABYLON = {}));
  36591. //# sourceMappingURL=babylon.particleSystem.js.map
  36592. var BABYLON;
  36593. (function (BABYLON) {
  36594. var SolidParticle = (function () {
  36595. /**
  36596. * Creates a Solid Particle object.
  36597. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  36598. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  36599. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  36600. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  36601. * `shapeId` (integer) is the model shape identifier in the SPS.
  36602. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  36603. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  36604. */
  36605. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  36606. this.idx = 0; // particle global index
  36607. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  36608. this.position = BABYLON.Vector3.Zero(); // position
  36609. this.rotation = BABYLON.Vector3.Zero(); // rotation
  36610. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  36611. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  36612. this.velocity = BABYLON.Vector3.Zero(); // velocity
  36613. this.alive = true; // alive
  36614. this.isVisible = true; // visibility
  36615. this._pos = 0; // index of this particle in the global "positions" array
  36616. this.shapeId = 0; // model shape id
  36617. this.idxInShape = 0; // index of the particle in its shape id
  36618. this.idx = particleIndex;
  36619. this._pos = positionIndex;
  36620. this._model = model;
  36621. this.shapeId = shapeId;
  36622. this.idxInShape = idxInShape;
  36623. this._sps = sps;
  36624. if (modelBoundingInfo) {
  36625. this._modelBoundingInfo = modelBoundingInfo;
  36626. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  36627. }
  36628. }
  36629. Object.defineProperty(SolidParticle.prototype, "scale", {
  36630. /**
  36631. * legacy support, changed scale to scaling
  36632. */
  36633. get: function () {
  36634. return this.scaling;
  36635. },
  36636. set: function (scale) {
  36637. this.scaling = scale;
  36638. },
  36639. enumerable: true,
  36640. configurable: true
  36641. });
  36642. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  36643. /**
  36644. * legacy support, changed quaternion to rotationQuaternion
  36645. */
  36646. get: function () {
  36647. return this.rotationQuaternion;
  36648. },
  36649. set: function (q) {
  36650. this.rotationQuaternion = q;
  36651. },
  36652. enumerable: true,
  36653. configurable: true
  36654. });
  36655. /**
  36656. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  36657. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  36658. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  36659. */
  36660. SolidParticle.prototype.intersectsMesh = function (target) {
  36661. if (!this._boundingInfo || !target._boundingInfo) {
  36662. return false;
  36663. }
  36664. if (this._sps._bSphereOnly) {
  36665. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  36666. }
  36667. return this._boundingInfo.intersects(target._boundingInfo, false);
  36668. };
  36669. return SolidParticle;
  36670. }());
  36671. BABYLON.SolidParticle = SolidParticle;
  36672. var ModelShape = (function () {
  36673. /**
  36674. * Creates a ModelShape object. This is an internal simplified reference to a mesh used as for a model to replicate particles from by the SPS.
  36675. * SPS internal tool, don't use it manually.
  36676. */
  36677. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  36678. this.shapeID = id;
  36679. this._shape = shape;
  36680. this._shapeUV = shapeUV;
  36681. this._positionFunction = posFunction;
  36682. this._vertexFunction = vtxFunction;
  36683. }
  36684. return ModelShape;
  36685. }());
  36686. BABYLON.ModelShape = ModelShape;
  36687. })(BABYLON || (BABYLON = {}));
  36688. //# sourceMappingURL=babylon.solidParticle.js.map
  36689. var BABYLON;
  36690. (function (BABYLON) {
  36691. /**
  36692. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  36693. */
  36694. var SolidParticleSystem = (function () {
  36695. /**
  36696. * Creates a SPS (Solid Particle System) object.
  36697. * `name` (String) is the SPS name, this will be the underlying mesh name.
  36698. * `scene` (Scene) is the scene in which the SPS is added.
  36699. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  36700. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  36701. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  36702. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  36703. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  36704. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  36705. */
  36706. function SolidParticleSystem(name, scene, options) {
  36707. // public members
  36708. /**
  36709. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  36710. * Example : var p = SPS.particles[i];
  36711. */
  36712. this.particles = new Array();
  36713. /**
  36714. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  36715. */
  36716. this.nbParticles = 0;
  36717. /**
  36718. * If the particles must ever face the camera (default false). Useful for planar particles.
  36719. */
  36720. this.billboard = false;
  36721. /**
  36722. * Recompute normals when adding a shape
  36723. */
  36724. this.recomputeNormals = true;
  36725. /**
  36726. * This a counter ofr your own usage. It's not set by any SPS functions.
  36727. */
  36728. this.counter = 0;
  36729. /**
  36730. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  36731. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  36732. */
  36733. this.vars = {};
  36734. this._positions = new Array();
  36735. this._indices = new Array();
  36736. this._normals = new Array();
  36737. this._colors = new Array();
  36738. this._uvs = new Array();
  36739. this._index = 0; // indices index
  36740. this._updatable = true;
  36741. this._pickable = false;
  36742. this._isVisibilityBoxLocked = false;
  36743. this._alwaysVisible = false;
  36744. this._shapeCounter = 0;
  36745. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  36746. this._color = new BABYLON.Color4(0, 0, 0, 0);
  36747. this._computeParticleColor = true;
  36748. this._computeParticleTexture = true;
  36749. this._computeParticleRotation = true;
  36750. this._computeParticleVertex = false;
  36751. this._computeBoundingBox = false;
  36752. this._cam_axisZ = BABYLON.Vector3.Zero();
  36753. this._cam_axisY = BABYLON.Vector3.Zero();
  36754. this._cam_axisX = BABYLON.Vector3.Zero();
  36755. this._axisX = BABYLON.Axis.X;
  36756. this._axisY = BABYLON.Axis.Y;
  36757. this._axisZ = BABYLON.Axis.Z;
  36758. this._camDir = BABYLON.Vector3.Zero();
  36759. this._rotMatrix = new BABYLON.Matrix();
  36760. this._invertMatrix = new BABYLON.Matrix();
  36761. this._rotated = BABYLON.Vector3.Zero();
  36762. this._quaternion = new BABYLON.Quaternion();
  36763. this._vertex = BABYLON.Vector3.Zero();
  36764. this._normal = BABYLON.Vector3.Zero();
  36765. this._yaw = 0.0;
  36766. this._pitch = 0.0;
  36767. this._roll = 0.0;
  36768. this._halfroll = 0.0;
  36769. this._halfpitch = 0.0;
  36770. this._halfyaw = 0.0;
  36771. this._sinRoll = 0.0;
  36772. this._cosRoll = 0.0;
  36773. this._sinPitch = 0.0;
  36774. this._cosPitch = 0.0;
  36775. this._sinYaw = 0.0;
  36776. this._cosYaw = 0.0;
  36777. this._w = 0.0;
  36778. this._mustUnrotateFixedNormals = false;
  36779. this._minimum = BABYLON.Tmp.Vector3[0];
  36780. this._maximum = BABYLON.Tmp.Vector3[1];
  36781. this._scale = BABYLON.Tmp.Vector3[2];
  36782. this._translation = BABYLON.Tmp.Vector3[3];
  36783. this._minBbox = BABYLON.Tmp.Vector3[4];
  36784. this._maxBbox = BABYLON.Tmp.Vector3[5];
  36785. this._particlesIntersect = false;
  36786. this._bSphereOnly = false;
  36787. this._bSphereRadiusFactor = 1.0;
  36788. this.name = name;
  36789. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  36790. this._camera = scene.activeCamera;
  36791. this._pickable = options ? options.isPickable : false;
  36792. this._particlesIntersect = options ? options.particleIntersection : false;
  36793. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  36794. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  36795. if (options && options.updatable) {
  36796. this._updatable = options.updatable;
  36797. }
  36798. else {
  36799. this._updatable = true;
  36800. }
  36801. if (this._pickable) {
  36802. this.pickedParticles = [];
  36803. }
  36804. }
  36805. /**
  36806. * Builds the SPS underlying mesh. Returns a standard Mesh.
  36807. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  36808. */
  36809. SolidParticleSystem.prototype.buildMesh = function () {
  36810. if (this.nbParticles === 0) {
  36811. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  36812. this.addShape(triangle, 1);
  36813. triangle.dispose();
  36814. }
  36815. this._positions32 = new Float32Array(this._positions);
  36816. this._uvs32 = new Float32Array(this._uvs);
  36817. this._colors32 = new Float32Array(this._colors);
  36818. if (this.recomputeNormals) {
  36819. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  36820. }
  36821. this._normals32 = new Float32Array(this._normals);
  36822. this._fixedNormal32 = new Float32Array(this._normals);
  36823. if (this._mustUnrotateFixedNormals) {
  36824. this._unrotateFixedNormals();
  36825. }
  36826. var vertexData = new BABYLON.VertexData();
  36827. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  36828. vertexData.indices = this._indices;
  36829. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  36830. if (this._uvs32) {
  36831. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  36832. ;
  36833. }
  36834. if (this._colors32) {
  36835. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  36836. }
  36837. var mesh = new BABYLON.Mesh(this.name, this._scene);
  36838. vertexData.applyToMesh(mesh, this._updatable);
  36839. this.mesh = mesh;
  36840. this.mesh.isPickable = this._pickable;
  36841. // free memory
  36842. this._positions = null;
  36843. this._normals = null;
  36844. this._uvs = null;
  36845. this._colors = null;
  36846. if (!this._updatable) {
  36847. this.particles.length = 0;
  36848. }
  36849. return mesh;
  36850. };
  36851. /**
  36852. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  36853. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  36854. * Thus the particles generated from `digest()` have their property `position` set yet.
  36855. * `mesh` ( Mesh ) is the mesh to be digested
  36856. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  36857. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  36858. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  36859. */
  36860. SolidParticleSystem.prototype.digest = function (mesh, options) {
  36861. var size = (options && options.facetNb) || 1;
  36862. var number = (options && options.number);
  36863. var delta = (options && options.delta) || 0;
  36864. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36865. var meshInd = mesh.getIndices();
  36866. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36867. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36868. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36869. var f = 0; // facet counter
  36870. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  36871. // compute size from number
  36872. if (number) {
  36873. number = (number > totalFacets) ? totalFacets : number;
  36874. size = Math.round(totalFacets / number);
  36875. delta = 0;
  36876. }
  36877. else {
  36878. size = (size > totalFacets) ? totalFacets : size;
  36879. }
  36880. var facetPos = []; // submesh positions
  36881. var facetInd = []; // submesh indices
  36882. var facetUV = []; // submesh UV
  36883. var facetCol = []; // submesh colors
  36884. var barycenter = BABYLON.Tmp.Vector3[0];
  36885. var rand;
  36886. var sizeO = size;
  36887. while (f < totalFacets) {
  36888. size = sizeO + Math.floor((1 + delta) * Math.random());
  36889. if (f > totalFacets - size) {
  36890. size = totalFacets - f;
  36891. }
  36892. // reset temp arrays
  36893. facetPos.length = 0;
  36894. facetInd.length = 0;
  36895. facetUV.length = 0;
  36896. facetCol.length = 0;
  36897. // iterate over "size" facets
  36898. var fi = 0;
  36899. for (var j = f * 3; j < (f + size) * 3; j++) {
  36900. facetInd.push(fi);
  36901. var i = meshInd[j];
  36902. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  36903. if (meshUV) {
  36904. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  36905. }
  36906. if (meshCol) {
  36907. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  36908. }
  36909. fi++;
  36910. }
  36911. // create a model shape for each single particle
  36912. var idx = this.nbParticles;
  36913. var shape = this._posToShape(facetPos);
  36914. var shapeUV = this._uvsToShapeUV(facetUV);
  36915. // compute the barycenter of the shape
  36916. var v;
  36917. for (v = 0; v < shape.length; v++) {
  36918. barycenter.addInPlace(shape[v]);
  36919. }
  36920. barycenter.scaleInPlace(1 / shape.length);
  36921. // shift the shape from its barycenter to the origin
  36922. for (v = 0; v < shape.length; v++) {
  36923. shape[v].subtractInPlace(barycenter);
  36924. }
  36925. var bInfo;
  36926. if (this._particlesIntersect) {
  36927. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  36928. }
  36929. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  36930. // add the particle in the SPS
  36931. var currentPos = this._positions.length;
  36932. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  36933. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  36934. // initialize the particle position
  36935. this.particles[this.nbParticles].position.addInPlace(barycenter);
  36936. this._index += shape.length;
  36937. idx++;
  36938. this.nbParticles++;
  36939. this._shapeCounter++;
  36940. f += size;
  36941. }
  36942. return this;
  36943. };
  36944. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  36945. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  36946. var index = 0;
  36947. var idx = 0;
  36948. for (var p = 0; p < this.particles.length; p++) {
  36949. this._particle = this.particles[p];
  36950. this._shape = this._particle._model._shape;
  36951. if (this._particle.rotationQuaternion) {
  36952. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  36953. }
  36954. else {
  36955. this._yaw = this._particle.rotation.y;
  36956. this._pitch = this._particle.rotation.x;
  36957. this._roll = this._particle.rotation.z;
  36958. this._quaternionRotationYPR();
  36959. }
  36960. this._quaternionToRotationMatrix();
  36961. this._rotMatrix.invertToRef(this._invertMatrix);
  36962. for (var pt = 0; pt < this._shape.length; pt++) {
  36963. idx = index + pt * 3;
  36964. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  36965. this._fixedNormal32[idx] = this._normal.x;
  36966. this._fixedNormal32[idx + 1] = this._normal.y;
  36967. this._fixedNormal32[idx + 2] = this._normal.z;
  36968. }
  36969. index = idx + 3;
  36970. }
  36971. };
  36972. //reset copy
  36973. SolidParticleSystem.prototype._resetCopy = function () {
  36974. this._copy.position.x = 0;
  36975. this._copy.position.y = 0;
  36976. this._copy.position.z = 0;
  36977. this._copy.rotation.x = 0;
  36978. this._copy.rotation.y = 0;
  36979. this._copy.rotation.z = 0;
  36980. this._copy.rotationQuaternion = null;
  36981. this._copy.scaling.x = 1;
  36982. this._copy.scaling.y = 1;
  36983. this._copy.scaling.z = 1;
  36984. this._copy.uvs.x = 0;
  36985. this._copy.uvs.y = 0;
  36986. this._copy.uvs.z = 1;
  36987. this._copy.uvs.w = 1;
  36988. this._copy.color = null;
  36989. };
  36990. // _meshBuilder : inserts the shape model in the global SPS mesh
  36991. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  36992. var i;
  36993. var u = 0;
  36994. var c = 0;
  36995. var n = 0;
  36996. this._resetCopy();
  36997. if (options && options.positionFunction) {
  36998. options.positionFunction(this._copy, idx, idxInShape);
  36999. this._mustUnrotateFixedNormals = true;
  37000. }
  37001. if (this._copy.rotationQuaternion) {
  37002. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  37003. }
  37004. else {
  37005. this._yaw = this._copy.rotation.y;
  37006. this._pitch = this._copy.rotation.x;
  37007. this._roll = this._copy.rotation.z;
  37008. this._quaternionRotationYPR();
  37009. }
  37010. this._quaternionToRotationMatrix();
  37011. for (i = 0; i < shape.length; i++) {
  37012. this._vertex.x = shape[i].x;
  37013. this._vertex.y = shape[i].y;
  37014. this._vertex.z = shape[i].z;
  37015. if (options && options.vertexFunction) {
  37016. options.vertexFunction(this._copy, this._vertex, i);
  37017. }
  37018. this._vertex.x *= this._copy.scaling.x;
  37019. this._vertex.y *= this._copy.scaling.y;
  37020. this._vertex.z *= this._copy.scaling.z;
  37021. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  37022. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  37023. if (meshUV) {
  37024. 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);
  37025. u += 2;
  37026. }
  37027. if (this._copy.color) {
  37028. this._color = this._copy.color;
  37029. }
  37030. else if (meshCol && meshCol[c] !== undefined) {
  37031. this._color.r = meshCol[c];
  37032. this._color.g = meshCol[c + 1];
  37033. this._color.b = meshCol[c + 2];
  37034. this._color.a = meshCol[c + 3];
  37035. }
  37036. else {
  37037. this._color.r = 1;
  37038. this._color.g = 1;
  37039. this._color.b = 1;
  37040. this._color.a = 1;
  37041. }
  37042. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  37043. c += 4;
  37044. if (!this.recomputeNormals && meshNor) {
  37045. this._normal.x = meshNor[n];
  37046. this._normal.y = meshNor[n + 1];
  37047. this._normal.z = meshNor[n + 2];
  37048. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  37049. normals.push(this._normal.x, this._normal.y, this._normal.z);
  37050. n += 3;
  37051. }
  37052. }
  37053. for (i = 0; i < meshInd.length; i++) {
  37054. indices.push(p + meshInd[i]);
  37055. }
  37056. if (this._pickable) {
  37057. var nbfaces = meshInd.length / 3;
  37058. for (i = 0; i < nbfaces; i++) {
  37059. this.pickedParticles.push({ idx: idx, faceId: i });
  37060. }
  37061. }
  37062. return this._copy;
  37063. };
  37064. // returns a shape array from positions array
  37065. SolidParticleSystem.prototype._posToShape = function (positions) {
  37066. var shape = [];
  37067. for (var i = 0; i < positions.length; i += 3) {
  37068. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  37069. }
  37070. return shape;
  37071. };
  37072. // returns a shapeUV array from a Vector4 uvs
  37073. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  37074. var shapeUV = [];
  37075. if (uvs) {
  37076. for (var i = 0; i < uvs.length; i++)
  37077. shapeUV.push(uvs[i]);
  37078. }
  37079. return shapeUV;
  37080. };
  37081. // adds a new particle object in the particles array
  37082. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  37083. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  37084. this.particles.push(sp);
  37085. return sp;
  37086. };
  37087. /**
  37088. * Adds some particles to the SPS from the model shape. Returns the shape id.
  37089. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  37090. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  37091. * `nb` (positive integer) the number of particles to be created from this model
  37092. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  37093. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  37094. */
  37095. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  37096. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37097. var meshInd = mesh.getIndices();
  37098. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37099. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37100. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37101. var bbInfo;
  37102. if (this._particlesIntersect) {
  37103. bbInfo = mesh.getBoundingInfo();
  37104. }
  37105. var shape = this._posToShape(meshPos);
  37106. var shapeUV = this._uvsToShapeUV(meshUV);
  37107. var posfunc = options ? options.positionFunction : null;
  37108. var vtxfunc = options ? options.vertexFunction : null;
  37109. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  37110. // particles
  37111. var sp;
  37112. var currentCopy;
  37113. var idx = this.nbParticles;
  37114. for (var i = 0; i < nb; i++) {
  37115. var currentPos = this._positions.length;
  37116. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  37117. if (this._updatable) {
  37118. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  37119. sp.position.copyFrom(currentCopy.position);
  37120. sp.rotation.copyFrom(currentCopy.rotation);
  37121. if (currentCopy.rotationQuaternion) {
  37122. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  37123. }
  37124. if (currentCopy.color) {
  37125. sp.color.copyFrom(currentCopy.color);
  37126. }
  37127. sp.scaling.copyFrom(currentCopy.scaling);
  37128. sp.uvs.copyFrom(currentCopy.uvs);
  37129. }
  37130. this._index += shape.length;
  37131. idx++;
  37132. }
  37133. this.nbParticles += nb;
  37134. this._shapeCounter++;
  37135. return this._shapeCounter - 1;
  37136. };
  37137. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  37138. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  37139. this._resetCopy();
  37140. if (particle._model._positionFunction) {
  37141. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  37142. }
  37143. if (this._copy.rotationQuaternion) {
  37144. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  37145. }
  37146. else {
  37147. this._yaw = this._copy.rotation.y;
  37148. this._pitch = this._copy.rotation.x;
  37149. this._roll = this._copy.rotation.z;
  37150. this._quaternionRotationYPR();
  37151. }
  37152. this._quaternionToRotationMatrix();
  37153. this._shape = particle._model._shape;
  37154. for (var pt = 0; pt < this._shape.length; pt++) {
  37155. this._vertex.x = this._shape[pt].x;
  37156. this._vertex.y = this._shape[pt].y;
  37157. this._vertex.z = this._shape[pt].z;
  37158. if (particle._model._vertexFunction) {
  37159. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  37160. }
  37161. this._vertex.x *= this._copy.scaling.x;
  37162. this._vertex.y *= this._copy.scaling.y;
  37163. this._vertex.z *= this._copy.scaling.z;
  37164. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  37165. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  37166. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  37167. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  37168. }
  37169. particle.position.x = 0.0;
  37170. particle.position.y = 0.0;
  37171. particle.position.z = 0.0;
  37172. particle.rotation.x = 0.0;
  37173. particle.rotation.y = 0.0;
  37174. particle.rotation.z = 0.0;
  37175. particle.rotationQuaternion = null;
  37176. particle.scaling.x = 1.0;
  37177. particle.scaling.y = 1.0;
  37178. particle.scaling.z = 1.0;
  37179. };
  37180. /**
  37181. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  37182. * Returns the SPS.
  37183. */
  37184. SolidParticleSystem.prototype.rebuildMesh = function () {
  37185. for (var p = 0; p < this.particles.length; p++) {
  37186. this._rebuildParticle(this.particles[p]);
  37187. }
  37188. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  37189. return this;
  37190. };
  37191. /**
  37192. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  37193. * This method calls `updateParticle()` for each particle of the SPS.
  37194. * For an animated SPS, it is usually called within the render loop.
  37195. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  37196. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  37197. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  37198. * Returns the SPS.
  37199. */
  37200. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  37201. if (start === void 0) { start = 0; }
  37202. if (end === void 0) { end = this.nbParticles - 1; }
  37203. if (update === void 0) { update = true; }
  37204. if (!this._updatable) {
  37205. return;
  37206. }
  37207. // custom beforeUpdate
  37208. this.beforeUpdateParticles(start, end, update);
  37209. this._cam_axisX.x = 1.0;
  37210. this._cam_axisX.y = 0.0;
  37211. this._cam_axisX.z = 0.0;
  37212. this._cam_axisY.x = 0.0;
  37213. this._cam_axisY.y = 1.0;
  37214. this._cam_axisY.z = 0.0;
  37215. this._cam_axisZ.x = 0.0;
  37216. this._cam_axisZ.y = 0.0;
  37217. this._cam_axisZ.z = 1.0;
  37218. // if the particles will always face the camera
  37219. if (this.billboard) {
  37220. this.mesh.computeWorldMatrix(true);
  37221. // compute the camera position and un-rotate it by the current mesh rotation
  37222. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  37223. this._quaternionToRotationMatrix();
  37224. this._rotMatrix.invertToRef(this._invertMatrix);
  37225. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  37226. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  37227. this._cam_axisZ.normalize();
  37228. // same for camera up vector extracted from the cam view matrix
  37229. var view = this._camera.getViewMatrix(true);
  37230. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  37231. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  37232. this._cam_axisY.normalize();
  37233. this._cam_axisX.normalize();
  37234. }
  37235. }
  37236. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  37237. var idx = 0; // current position index in the global array positions32
  37238. var index = 0; // position start index in the global array positions32 of the current particle
  37239. var colidx = 0; // current color index in the global array colors32
  37240. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  37241. var uvidx = 0; // current uv index in the global array uvs32
  37242. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  37243. var pt = 0; // current index in the particle model shape
  37244. if (this.mesh.isFacetDataEnabled) {
  37245. this._computeBoundingBox = true;
  37246. }
  37247. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  37248. if (this._computeBoundingBox) {
  37249. if (start == 0 && end == this.nbParticles - 1) {
  37250. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  37251. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  37252. }
  37253. else {
  37254. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  37255. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  37256. }
  37257. }
  37258. // particle loop
  37259. index = this.particles[start]._pos;
  37260. var vpos = (index / 3) | 0;
  37261. colorIndex = vpos * 4;
  37262. uvIndex = vpos * 2;
  37263. for (var p = start; p <= end; p++) {
  37264. this._particle = this.particles[p];
  37265. this._shape = this._particle._model._shape;
  37266. this._shapeUV = this._particle._model._shapeUV;
  37267. // call to custom user function to update the particle properties
  37268. this.updateParticle(this._particle);
  37269. if (this._particle.isVisible) {
  37270. // particle rotation matrix
  37271. if (this.billboard) {
  37272. this._particle.rotation.x = 0.0;
  37273. this._particle.rotation.y = 0.0;
  37274. }
  37275. if (this._computeParticleRotation || this.billboard) {
  37276. if (this._particle.rotationQuaternion) {
  37277. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  37278. }
  37279. else {
  37280. this._yaw = this._particle.rotation.y;
  37281. this._pitch = this._particle.rotation.x;
  37282. this._roll = this._particle.rotation.z;
  37283. this._quaternionRotationYPR();
  37284. }
  37285. this._quaternionToRotationMatrix();
  37286. }
  37287. // particle vertex loop
  37288. for (pt = 0; pt < this._shape.length; pt++) {
  37289. idx = index + pt * 3;
  37290. colidx = colorIndex + pt * 4;
  37291. uvidx = uvIndex + pt * 2;
  37292. this._vertex.x = this._shape[pt].x;
  37293. this._vertex.y = this._shape[pt].y;
  37294. this._vertex.z = this._shape[pt].z;
  37295. if (this._computeParticleVertex) {
  37296. this.updateParticleVertex(this._particle, this._vertex, pt);
  37297. }
  37298. // positions
  37299. this._vertex.x *= this._particle.scaling.x;
  37300. this._vertex.y *= this._particle.scaling.y;
  37301. this._vertex.z *= this._particle.scaling.z;
  37302. 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];
  37303. 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;
  37304. 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;
  37305. 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;
  37306. 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;
  37307. 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;
  37308. 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;
  37309. if (this._computeBoundingBox) {
  37310. if (this._positions32[idx] < this._minimum.x) {
  37311. this._minimum.x = this._positions32[idx];
  37312. }
  37313. if (this._positions32[idx] > this._maximum.x) {
  37314. this._maximum.x = this._positions32[idx];
  37315. }
  37316. if (this._positions32[idx + 1] < this._minimum.y) {
  37317. this._minimum.y = this._positions32[idx + 1];
  37318. }
  37319. if (this._positions32[idx + 1] > this._maximum.y) {
  37320. this._maximum.y = this._positions32[idx + 1];
  37321. }
  37322. if (this._positions32[idx + 2] < this._minimum.z) {
  37323. this._minimum.z = this._positions32[idx + 2];
  37324. }
  37325. if (this._positions32[idx + 2] > this._maximum.z) {
  37326. this._maximum.z = this._positions32[idx + 2];
  37327. }
  37328. }
  37329. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  37330. if (!this._computeParticleVertex) {
  37331. this._normal.x = this._fixedNormal32[idx];
  37332. this._normal.y = this._fixedNormal32[idx + 1];
  37333. this._normal.z = this._fixedNormal32[idx + 2];
  37334. 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]);
  37335. 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]);
  37336. 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]);
  37337. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  37338. 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;
  37339. 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;
  37340. }
  37341. if (this._computeParticleColor) {
  37342. this._colors32[colidx] = this._particle.color.r;
  37343. this._colors32[colidx + 1] = this._particle.color.g;
  37344. this._colors32[colidx + 2] = this._particle.color.b;
  37345. this._colors32[colidx + 3] = this._particle.color.a;
  37346. }
  37347. if (this._computeParticleTexture) {
  37348. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  37349. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  37350. }
  37351. }
  37352. }
  37353. else {
  37354. for (pt = 0; pt < this._shape.length; pt++) {
  37355. idx = index + pt * 3;
  37356. colidx = colorIndex + pt * 4;
  37357. uvidx = uvIndex + pt * 2;
  37358. this._positions32[idx] = this._camera.position.x;
  37359. this._positions32[idx + 1] = this._camera.position.y;
  37360. this._positions32[idx + 2] = this._camera.position.z;
  37361. this._normals32[idx] = 0.0;
  37362. this._normals32[idx + 1] = 0.0;
  37363. this._normals32[idx + 2] = 0.0;
  37364. if (this._computeParticleColor) {
  37365. this._colors32[colidx] = this._particle.color.r;
  37366. this._colors32[colidx + 1] = this._particle.color.g;
  37367. this._colors32[colidx + 2] = this._particle.color.b;
  37368. this._colors32[colidx + 3] = this._particle.color.a;
  37369. }
  37370. if (this._computeParticleTexture) {
  37371. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  37372. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  37373. }
  37374. }
  37375. }
  37376. // if the particle intersections must be computed : update the bbInfo
  37377. if (this._particlesIntersect) {
  37378. var bInfo = this._particle._boundingInfo;
  37379. var bBox = bInfo.boundingBox;
  37380. var bSphere = bInfo.boundingSphere;
  37381. if (!this._bSphereOnly) {
  37382. // place, scale and rotate the particle bbox within the SPS local system, then update it
  37383. for (var b = 0; b < bBox.vectors.length; b++) {
  37384. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  37385. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  37386. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  37387. 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];
  37388. 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;
  37389. 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;
  37390. 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;
  37391. bBox.vectors[b].x = 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;
  37392. bBox.vectors[b].y = 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;
  37393. bBox.vectors[b].z = 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;
  37394. }
  37395. bBox._update(this.mesh._worldMatrix);
  37396. }
  37397. // place and scale the particle bouding sphere in the SPS local system, then update it
  37398. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  37399. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  37400. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  37401. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  37402. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  37403. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  37404. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  37405. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  37406. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  37407. bSphere.radius = this._bSphereRadiusFactor * 0.5 * Math.sqrt((this._maxBbox.x - this._minBbox.x) * (this._maxBbox.x - this._minBbox.x) + (this._maxBbox.y - this._minBbox.y) * (this._maxBbox.y - this._minBbox.y) + (this._maxBbox.z - this._minBbox.z) * (this._maxBbox.z - this._minBbox.z));
  37408. bSphere._update(this.mesh._worldMatrix);
  37409. }
  37410. // increment indexes for the next particle
  37411. index = idx + 3;
  37412. colorIndex = colidx + 4;
  37413. uvIndex = uvidx + 2;
  37414. }
  37415. // if the VBO must be updated
  37416. if (update) {
  37417. if (this._computeParticleColor) {
  37418. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  37419. }
  37420. if (this._computeParticleTexture) {
  37421. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  37422. }
  37423. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  37424. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  37425. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  37426. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  37427. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  37428. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  37429. for (var i = 0; i < this._normals32.length; i++) {
  37430. this._fixedNormal32[i] = this._normals32[i];
  37431. }
  37432. }
  37433. if (!this.mesh.areNormalsFrozen) {
  37434. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  37435. }
  37436. }
  37437. }
  37438. if (this._computeBoundingBox) {
  37439. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  37440. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  37441. }
  37442. this.afterUpdateParticles(start, end, update);
  37443. return this;
  37444. };
  37445. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  37446. this._halfroll = this._roll * 0.5;
  37447. this._halfpitch = this._pitch * 0.5;
  37448. this._halfyaw = this._yaw * 0.5;
  37449. this._sinRoll = Math.sin(this._halfroll);
  37450. this._cosRoll = Math.cos(this._halfroll);
  37451. this._sinPitch = Math.sin(this._halfpitch);
  37452. this._cosPitch = Math.cos(this._halfpitch);
  37453. this._sinYaw = Math.sin(this._halfyaw);
  37454. this._cosYaw = Math.cos(this._halfyaw);
  37455. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  37456. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  37457. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  37458. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  37459. };
  37460. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  37461. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  37462. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  37463. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  37464. this._rotMatrix.m[3] = 0;
  37465. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  37466. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  37467. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  37468. this._rotMatrix.m[7] = 0;
  37469. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  37470. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  37471. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  37472. this._rotMatrix.m[11] = 0;
  37473. this._rotMatrix.m[12] = 0;
  37474. this._rotMatrix.m[13] = 0;
  37475. this._rotMatrix.m[14] = 0;
  37476. this._rotMatrix.m[15] = 1.0;
  37477. };
  37478. /**
  37479. * Disposes the SPS.
  37480. * Returns nothing.
  37481. */
  37482. SolidParticleSystem.prototype.dispose = function () {
  37483. this.mesh.dispose();
  37484. this.vars = null;
  37485. // drop references to internal big arrays for the GC
  37486. this._positions = null;
  37487. this._indices = null;
  37488. this._normals = null;
  37489. this._uvs = null;
  37490. this._colors = null;
  37491. this._positions32 = null;
  37492. this._normals32 = null;
  37493. this._fixedNormal32 = null;
  37494. this._uvs32 = null;
  37495. this._colors32 = null;
  37496. this.pickedParticles = null;
  37497. };
  37498. /**
  37499. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  37500. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  37501. * Returns the SPS.
  37502. */
  37503. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  37504. if (!this._isVisibilityBoxLocked) {
  37505. this.mesh.refreshBoundingInfo();
  37506. }
  37507. return this;
  37508. };
  37509. /**
  37510. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  37511. * @param size the size (float) of the visibility box
  37512. * note : this doesn't lock the SPS mesh bounding box.
  37513. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  37514. */
  37515. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  37516. var vis = size / 2;
  37517. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  37518. };
  37519. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  37520. // getter and setter
  37521. get: function () {
  37522. return this._alwaysVisible;
  37523. },
  37524. /**
  37525. * Sets the SPS as always visible or not
  37526. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  37527. */
  37528. set: function (val) {
  37529. this._alwaysVisible = val;
  37530. this.mesh.alwaysSelectAsActiveMesh = val;
  37531. },
  37532. enumerable: true,
  37533. configurable: true
  37534. });
  37535. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  37536. get: function () {
  37537. return this._isVisibilityBoxLocked;
  37538. },
  37539. /**
  37540. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  37541. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  37542. */
  37543. set: function (val) {
  37544. this._isVisibilityBoxLocked = val;
  37545. this.mesh.getBoundingInfo().isLocked = val;
  37546. },
  37547. enumerable: true,
  37548. configurable: true
  37549. });
  37550. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  37551. // getters
  37552. get: function () {
  37553. return this._computeParticleRotation;
  37554. },
  37555. // Optimizer setters
  37556. /**
  37557. * Tells to `setParticles()` to compute the particle rotations or not.
  37558. * Default value : true. The SPS is faster when it's set to false.
  37559. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  37560. */
  37561. set: function (val) {
  37562. this._computeParticleRotation = val;
  37563. },
  37564. enumerable: true,
  37565. configurable: true
  37566. });
  37567. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  37568. get: function () {
  37569. return this._computeParticleColor;
  37570. },
  37571. /**
  37572. * Tells to `setParticles()` to compute the particle colors or not.
  37573. * Default value : true. The SPS is faster when it's set to false.
  37574. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  37575. */
  37576. set: function (val) {
  37577. this._computeParticleColor = val;
  37578. },
  37579. enumerable: true,
  37580. configurable: true
  37581. });
  37582. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  37583. get: function () {
  37584. return this._computeParticleTexture;
  37585. },
  37586. /**
  37587. * Tells to `setParticles()` to compute the particle textures or not.
  37588. * Default value : true. The SPS is faster when it's set to false.
  37589. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  37590. */
  37591. set: function (val) {
  37592. this._computeParticleTexture = val;
  37593. },
  37594. enumerable: true,
  37595. configurable: true
  37596. });
  37597. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  37598. get: function () {
  37599. return this._computeParticleVertex;
  37600. },
  37601. /**
  37602. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  37603. * Default value : false. The SPS is faster when it's set to false.
  37604. * Note : the particle custom vertex positions aren't stored values.
  37605. */
  37606. set: function (val) {
  37607. this._computeParticleVertex = val;
  37608. },
  37609. enumerable: true,
  37610. configurable: true
  37611. });
  37612. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  37613. get: function () {
  37614. return this._computeBoundingBox;
  37615. },
  37616. /**
  37617. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  37618. */
  37619. set: function (val) {
  37620. this._computeBoundingBox = val;
  37621. },
  37622. enumerable: true,
  37623. configurable: true
  37624. });
  37625. // =======================================================================
  37626. // Particle behavior logic
  37627. // these following methods may be overwritten by the user to fit his needs
  37628. /**
  37629. * This function does nothing. It may be overwritten to set all the particle first values.
  37630. * The SPS doesn't call this function, you may have to call it by your own.
  37631. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  37632. */
  37633. SolidParticleSystem.prototype.initParticles = function () {
  37634. };
  37635. /**
  37636. * This function does nothing. It may be overwritten to recycle a particle.
  37637. * The SPS doesn't call this function, you may have to call it by your own.
  37638. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  37639. */
  37640. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  37641. return particle;
  37642. };
  37643. /**
  37644. * Updates a particle : this function should be overwritten by the user.
  37645. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  37646. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  37647. * ex : just set a particle position or velocity and recycle conditions
  37648. */
  37649. SolidParticleSystem.prototype.updateParticle = function (particle) {
  37650. return particle;
  37651. };
  37652. /**
  37653. * Updates a vertex of a particle : it can be overwritten by the user.
  37654. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  37655. * @param particle the current particle
  37656. * @param vertex the current index of the current particle
  37657. * @param pt the index of the current vertex in the particle shape
  37658. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  37659. * ex : just set a vertex particle position
  37660. */
  37661. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  37662. return vertex;
  37663. };
  37664. /**
  37665. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  37666. * This does nothing and may be overwritten by the user.
  37667. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37668. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37669. * @param update the boolean update value actually passed to setParticles()
  37670. */
  37671. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  37672. };
  37673. /**
  37674. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  37675. * This will be passed three parameters.
  37676. * This does nothing and may be overwritten by the user.
  37677. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37678. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37679. * @param update the boolean update value actually passed to setParticles()
  37680. */
  37681. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  37682. };
  37683. return SolidParticleSystem;
  37684. }());
  37685. BABYLON.SolidParticleSystem = SolidParticleSystem;
  37686. })(BABYLON || (BABYLON = {}));
  37687. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  37688. /// <reference path="babylon.mesh.ts" />
  37689. var BABYLON;
  37690. (function (BABYLON) {
  37691. var GroundMesh = (function (_super) {
  37692. __extends(GroundMesh, _super);
  37693. function GroundMesh(name, scene) {
  37694. var _this = _super.call(this, name, scene) || this;
  37695. _this.generateOctree = false;
  37696. _this._worldInverse = new BABYLON.Matrix();
  37697. return _this;
  37698. }
  37699. GroundMesh.prototype.getClassName = function () {
  37700. return "GroundMesh";
  37701. };
  37702. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  37703. get: function () {
  37704. return Math.min(this._subdivisionsX, this._subdivisionsY);
  37705. },
  37706. enumerable: true,
  37707. configurable: true
  37708. });
  37709. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  37710. get: function () {
  37711. return this._subdivisionsX;
  37712. },
  37713. enumerable: true,
  37714. configurable: true
  37715. });
  37716. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  37717. get: function () {
  37718. return this._subdivisionsY;
  37719. },
  37720. enumerable: true,
  37721. configurable: true
  37722. });
  37723. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  37724. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  37725. this._subdivisionsX = chunksCount;
  37726. this._subdivisionsY = chunksCount;
  37727. this.subdivide(chunksCount);
  37728. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  37729. };
  37730. /**
  37731. * Returns a height (y) value in the Worl system :
  37732. * the ground altitude at the coordinates (x, z) expressed in the World system.
  37733. * Returns the ground y position if (x, z) are outside the ground surface.
  37734. */
  37735. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  37736. var world = this.getWorldMatrix();
  37737. var invMat = BABYLON.Tmp.Matrix[5];
  37738. world.invertToRef(invMat);
  37739. var tmpVect = BABYLON.Tmp.Vector3[8];
  37740. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  37741. x = tmpVect.x;
  37742. z = tmpVect.z;
  37743. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  37744. return this.position.y;
  37745. }
  37746. if (!this._heightQuads || this._heightQuads.length == 0) {
  37747. this._initHeightQuads();
  37748. this._computeHeightQuads();
  37749. }
  37750. var facet = this._getFacetAt(x, z);
  37751. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  37752. // return y in the World system
  37753. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  37754. return tmpVect.y;
  37755. };
  37756. /**
  37757. * Returns a normalized vector (Vector3) orthogonal to the ground
  37758. * at the ground coordinates (x, z) expressed in the World system.
  37759. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  37760. */
  37761. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  37762. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  37763. this.getNormalAtCoordinatesToRef(x, z, normal);
  37764. return normal;
  37765. };
  37766. /**
  37767. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  37768. * at the ground coordinates (x, z) expressed in the World system.
  37769. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  37770. * Returns the GroundMesh.
  37771. */
  37772. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  37773. var world = this.getWorldMatrix();
  37774. var tmpMat = BABYLON.Tmp.Matrix[5];
  37775. world.invertToRef(tmpMat);
  37776. var tmpVect = BABYLON.Tmp.Vector3[8];
  37777. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  37778. x = tmpVect.x;
  37779. z = tmpVect.z;
  37780. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  37781. return this;
  37782. }
  37783. if (!this._heightQuads || this._heightQuads.length == 0) {
  37784. this._initHeightQuads();
  37785. this._computeHeightQuads();
  37786. }
  37787. var facet = this._getFacetAt(x, z);
  37788. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  37789. return this;
  37790. };
  37791. /**
  37792. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  37793. * if the ground has been updated.
  37794. * This can be used in the render loop.
  37795. * Returns the GroundMesh.
  37796. */
  37797. GroundMesh.prototype.updateCoordinateHeights = function () {
  37798. if (!this._heightQuads || this._heightQuads.length == 0) {
  37799. this._initHeightQuads();
  37800. }
  37801. this._computeHeightQuads();
  37802. return this;
  37803. };
  37804. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  37805. GroundMesh.prototype._getFacetAt = function (x, z) {
  37806. // retrieve col and row from x, z coordinates in the ground local system
  37807. var subdivisionsX = this._subdivisionsX;
  37808. var subdivisionsY = this._subdivisionsY;
  37809. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  37810. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  37811. var quad = this._heightQuads[row * this._subdivisionsX + col];
  37812. var facet;
  37813. if (z < quad.slope.x * x + quad.slope.y) {
  37814. facet = quad.facet1;
  37815. }
  37816. else {
  37817. facet = quad.facet2;
  37818. }
  37819. return facet;
  37820. };
  37821. // Creates and populates the heightMap array with "facet" elements :
  37822. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  37823. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  37824. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  37825. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  37826. // Returns the GroundMesh.
  37827. GroundMesh.prototype._initHeightQuads = function () {
  37828. var subdivisionsX = this._subdivisionsX;
  37829. var subdivisionsY = this._subdivisionsY;
  37830. this._heightQuads = new Array();
  37831. for (var row = 0; row < subdivisionsY; row++) {
  37832. for (var col = 0; col < subdivisionsX; col++) {
  37833. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0), facet2: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0) };
  37834. this._heightQuads[row * subdivisionsX + col] = quad;
  37835. }
  37836. }
  37837. return this;
  37838. };
  37839. // Compute each quad element values and update the the heightMap array :
  37840. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  37841. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  37842. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  37843. // Returns the GroundMesh.
  37844. GroundMesh.prototype._computeHeightQuads = function () {
  37845. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37846. var v1 = BABYLON.Tmp.Vector3[3];
  37847. var v2 = BABYLON.Tmp.Vector3[2];
  37848. var v3 = BABYLON.Tmp.Vector3[1];
  37849. var v4 = BABYLON.Tmp.Vector3[0];
  37850. var v1v2 = BABYLON.Tmp.Vector3[4];
  37851. var v1v3 = BABYLON.Tmp.Vector3[5];
  37852. var v1v4 = BABYLON.Tmp.Vector3[6];
  37853. var norm1 = BABYLON.Tmp.Vector3[7];
  37854. var norm2 = BABYLON.Tmp.Vector3[8];
  37855. var i = 0;
  37856. var j = 0;
  37857. var k = 0;
  37858. var cd = 0; // 2D slope coefficient : z = cd * x + h
  37859. var h = 0;
  37860. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  37861. var d2 = 0;
  37862. var subdivisionsX = this._subdivisionsX;
  37863. var subdivisionsY = this._subdivisionsY;
  37864. for (var row = 0; row < subdivisionsY; row++) {
  37865. for (var col = 0; col < subdivisionsX; col++) {
  37866. i = col * 3;
  37867. j = row * (subdivisionsX + 1) * 3;
  37868. k = (row + 1) * (subdivisionsX + 1) * 3;
  37869. v1.x = positions[j + i];
  37870. v1.y = positions[j + i + 1];
  37871. v1.z = positions[j + i + 2];
  37872. v2.x = positions[j + i + 3];
  37873. v2.y = positions[j + i + 4];
  37874. v2.z = positions[j + i + 5];
  37875. v3.x = positions[k + i];
  37876. v3.y = positions[k + i + 1];
  37877. v3.z = positions[k + i + 2];
  37878. v4.x = positions[k + i + 3];
  37879. v4.y = positions[k + i + 4];
  37880. v4.z = positions[k + i + 5];
  37881. // 2D slope V1V4
  37882. cd = (v4.z - v1.z) / (v4.x - v1.x);
  37883. h = v1.z - cd * v1.x; // v1 belongs to the slope
  37884. // facet equations :
  37885. // we compute each facet normal vector
  37886. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  37887. // we compute the value d by applying the equation to v1 which belongs to the plane
  37888. // then we store the facet equation in a Vector4
  37889. v2.subtractToRef(v1, v1v2);
  37890. v3.subtractToRef(v1, v1v3);
  37891. v4.subtractToRef(v1, v1v4);
  37892. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  37893. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  37894. norm1.normalize();
  37895. norm2.normalize();
  37896. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  37897. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  37898. var quad = this._heightQuads[row * subdivisionsX + col];
  37899. quad.slope.copyFromFloats(cd, h);
  37900. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  37901. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  37902. }
  37903. }
  37904. return this;
  37905. };
  37906. GroundMesh.prototype.serialize = function (serializationObject) {
  37907. _super.prototype.serialize.call(this, serializationObject);
  37908. serializationObject.subdivisionsX = this._subdivisionsX;
  37909. serializationObject.subdivisionsY = this._subdivisionsY;
  37910. serializationObject.minX = this._minX;
  37911. serializationObject.maxX = this._maxX;
  37912. serializationObject.minZ = this._minZ;
  37913. serializationObject.maxZ = this._maxZ;
  37914. serializationObject.width = this._width;
  37915. serializationObject.height = this._height;
  37916. };
  37917. GroundMesh.Parse = function (parsedMesh, scene) {
  37918. var result = new GroundMesh(parsedMesh.name, scene);
  37919. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  37920. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  37921. result._minX = parsedMesh.minX;
  37922. result._maxX = parsedMesh.maxX;
  37923. result._minZ = parsedMesh.minZ;
  37924. result._maxZ = parsedMesh.maxZ;
  37925. result._width = parsedMesh.width;
  37926. result._height = parsedMesh.height;
  37927. return result;
  37928. };
  37929. return GroundMesh;
  37930. }(BABYLON.Mesh));
  37931. BABYLON.GroundMesh = GroundMesh;
  37932. })(BABYLON || (BABYLON = {}));
  37933. //# sourceMappingURL=babylon.groundMesh.js.map
  37934. var BABYLON;
  37935. (function (BABYLON) {
  37936. /**
  37937. * Creates an instance based on a source mesh.
  37938. */
  37939. var InstancedMesh = (function (_super) {
  37940. __extends(InstancedMesh, _super);
  37941. function InstancedMesh(name, source) {
  37942. var _this = _super.call(this, name, source.getScene()) || this;
  37943. source.instances.push(_this);
  37944. _this._sourceMesh = source;
  37945. _this.position.copyFrom(source.position);
  37946. _this.rotation.copyFrom(source.rotation);
  37947. _this.scaling.copyFrom(source.scaling);
  37948. if (source.rotationQuaternion) {
  37949. _this.rotationQuaternion = source.rotationQuaternion.clone();
  37950. }
  37951. _this.infiniteDistance = source.infiniteDistance;
  37952. _this.setPivotMatrix(source.getPivotMatrix());
  37953. _this.refreshBoundingInfo();
  37954. _this._syncSubMeshes();
  37955. return _this;
  37956. }
  37957. /**
  37958. * Returns the string "InstancedMesh".
  37959. */
  37960. InstancedMesh.prototype.getClassName = function () {
  37961. return "InstancedMesh";
  37962. };
  37963. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  37964. // Methods
  37965. get: function () {
  37966. return this._sourceMesh.receiveShadows;
  37967. },
  37968. enumerable: true,
  37969. configurable: true
  37970. });
  37971. Object.defineProperty(InstancedMesh.prototype, "material", {
  37972. get: function () {
  37973. return this._sourceMesh.material;
  37974. },
  37975. enumerable: true,
  37976. configurable: true
  37977. });
  37978. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  37979. get: function () {
  37980. return this._sourceMesh.visibility;
  37981. },
  37982. enumerable: true,
  37983. configurable: true
  37984. });
  37985. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  37986. get: function () {
  37987. return this._sourceMesh.skeleton;
  37988. },
  37989. enumerable: true,
  37990. configurable: true
  37991. });
  37992. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  37993. get: function () {
  37994. return this._sourceMesh.renderingGroupId;
  37995. },
  37996. enumerable: true,
  37997. configurable: true
  37998. });
  37999. /**
  38000. * Returns the total number of vertices (integer).
  38001. */
  38002. InstancedMesh.prototype.getTotalVertices = function () {
  38003. return this._sourceMesh.getTotalVertices();
  38004. };
  38005. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  38006. get: function () {
  38007. return this._sourceMesh;
  38008. },
  38009. enumerable: true,
  38010. configurable: true
  38011. });
  38012. /**
  38013. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  38014. */
  38015. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  38016. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  38017. };
  38018. /**
  38019. * Sets the vertex data of the mesh geometry for the requested `kind`.
  38020. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  38021. * The `data` are either a numeric array either a Float32Array.
  38022. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  38023. * 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).
  38024. * Note that a new underlying VertexBuffer object is created each call.
  38025. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  38026. *
  38027. * Possible `kind` values :
  38028. * - BABYLON.VertexBuffer.PositionKind
  38029. * - BABYLON.VertexBuffer.UVKind
  38030. * - BABYLON.VertexBuffer.UV2Kind
  38031. * - BABYLON.VertexBuffer.UV3Kind
  38032. * - BABYLON.VertexBuffer.UV4Kind
  38033. * - BABYLON.VertexBuffer.UV5Kind
  38034. * - BABYLON.VertexBuffer.UV6Kind
  38035. * - BABYLON.VertexBuffer.ColorKind
  38036. * - BABYLON.VertexBuffer.MatricesIndicesKind
  38037. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  38038. * - BABYLON.VertexBuffer.MatricesWeightsKind
  38039. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  38040. *
  38041. * Returns the Mesh.
  38042. */
  38043. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38044. if (this.sourceMesh) {
  38045. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  38046. }
  38047. return this.sourceMesh;
  38048. };
  38049. /**
  38050. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  38051. * If the mesh has no geometry, it is simply returned as it is.
  38052. * The `data` are either a numeric array either a Float32Array.
  38053. * No new underlying VertexBuffer object is created.
  38054. * 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.
  38055. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  38056. *
  38057. * Possible `kind` values :
  38058. * - BABYLON.VertexBuffer.PositionKind
  38059. * - BABYLON.VertexBuffer.UVKind
  38060. * - BABYLON.VertexBuffer.UV2Kind
  38061. * - BABYLON.VertexBuffer.UV3Kind
  38062. * - BABYLON.VertexBuffer.UV4Kind
  38063. * - BABYLON.VertexBuffer.UV5Kind
  38064. * - BABYLON.VertexBuffer.UV6Kind
  38065. * - BABYLON.VertexBuffer.ColorKind
  38066. * - BABYLON.VertexBuffer.MatricesIndicesKind
  38067. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  38068. * - BABYLON.VertexBuffer.MatricesWeightsKind
  38069. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  38070. *
  38071. * Returns the Mesh.
  38072. */
  38073. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  38074. if (this.sourceMesh) {
  38075. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  38076. }
  38077. return this.sourceMesh;
  38078. };
  38079. /**
  38080. * Sets the mesh indices.
  38081. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  38082. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  38083. * This method creates a new index buffer each call.
  38084. * Returns the Mesh.
  38085. */
  38086. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  38087. if (this.sourceMesh) {
  38088. this.sourceMesh.setIndices(indices, totalVertices);
  38089. }
  38090. return this.sourceMesh;
  38091. };
  38092. /**
  38093. * Boolean : True if the mesh owns the requested kind of data.
  38094. */
  38095. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  38096. return this._sourceMesh.isVerticesDataPresent(kind);
  38097. };
  38098. /**
  38099. * Returns an array of indices (IndicesArray).
  38100. */
  38101. InstancedMesh.prototype.getIndices = function () {
  38102. return this._sourceMesh.getIndices();
  38103. };
  38104. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  38105. get: function () {
  38106. return this._sourceMesh._positions;
  38107. },
  38108. enumerable: true,
  38109. configurable: true
  38110. });
  38111. /**
  38112. * Sets a new updated BoundingInfo to the mesh.
  38113. * Returns the mesh.
  38114. */
  38115. InstancedMesh.prototype.refreshBoundingInfo = function () {
  38116. var meshBB = this._sourceMesh.getBoundingInfo();
  38117. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  38118. this._updateBoundingInfo();
  38119. return this;
  38120. };
  38121. InstancedMesh.prototype._preActivate = function () {
  38122. if (this._currentLOD) {
  38123. this._currentLOD._preActivate();
  38124. }
  38125. return this;
  38126. };
  38127. InstancedMesh.prototype._activate = function (renderId) {
  38128. if (this._currentLOD) {
  38129. this._currentLOD._registerInstanceForRenderId(this, renderId);
  38130. }
  38131. return this;
  38132. };
  38133. /**
  38134. * Returns the current associated LOD AbstractMesh.
  38135. */
  38136. InstancedMesh.prototype.getLOD = function (camera) {
  38137. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  38138. if (this._currentLOD === this.sourceMesh) {
  38139. return this;
  38140. }
  38141. return this._currentLOD;
  38142. };
  38143. InstancedMesh.prototype._syncSubMeshes = function () {
  38144. this.releaseSubMeshes();
  38145. if (this._sourceMesh.subMeshes) {
  38146. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  38147. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  38148. }
  38149. }
  38150. return this;
  38151. };
  38152. InstancedMesh.prototype._generatePointsArray = function () {
  38153. return this._sourceMesh._generatePointsArray();
  38154. };
  38155. /**
  38156. * Creates a new InstancedMesh from the current mesh.
  38157. * - name (string) : the cloned mesh name
  38158. * - newParent (optional Node) : the optional Node to parent the clone to.
  38159. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  38160. *
  38161. * Returns the clone.
  38162. */
  38163. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  38164. var result = this._sourceMesh.createInstance(name);
  38165. // Deep copy
  38166. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  38167. // Bounding info
  38168. this.refreshBoundingInfo();
  38169. // Parent
  38170. if (newParent) {
  38171. result.parent = newParent;
  38172. }
  38173. if (!doNotCloneChildren) {
  38174. // Children
  38175. for (var index = 0; index < this.getScene().meshes.length; index++) {
  38176. var mesh = this.getScene().meshes[index];
  38177. if (mesh.parent === this) {
  38178. mesh.clone(mesh.name, result);
  38179. }
  38180. }
  38181. }
  38182. result.computeWorldMatrix(true);
  38183. return result;
  38184. };
  38185. /**
  38186. * Disposes the InstancedMesh.
  38187. * Returns nothing.
  38188. */
  38189. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  38190. // Remove from mesh
  38191. var index = this._sourceMesh.instances.indexOf(this);
  38192. this._sourceMesh.instances.splice(index, 1);
  38193. _super.prototype.dispose.call(this, doNotRecurse);
  38194. };
  38195. return InstancedMesh;
  38196. }(BABYLON.AbstractMesh));
  38197. BABYLON.InstancedMesh = InstancedMesh;
  38198. })(BABYLON || (BABYLON = {}));
  38199. //# sourceMappingURL=babylon.instancedMesh.js.map
  38200. /// <reference path="babylon.mesh.ts" />
  38201. var BABYLON;
  38202. (function (BABYLON) {
  38203. var LinesMesh = (function (_super) {
  38204. __extends(LinesMesh, _super);
  38205. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  38206. if (parent === void 0) { parent = null; }
  38207. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  38208. _this.useVertexColor = useVertexColor;
  38209. _this.color = new BABYLON.Color3(1, 1, 1);
  38210. _this.alpha = 1;
  38211. if (source) {
  38212. _this.color = source.color.clone();
  38213. _this.alpha = source.alpha;
  38214. _this.useVertexColor = source.useVertexColor;
  38215. }
  38216. _this._intersectionThreshold = 0.1;
  38217. var options = {
  38218. attributes: [BABYLON.VertexBuffer.PositionKind],
  38219. uniforms: ["world", "viewProjection"],
  38220. needAlphaBlending: false,
  38221. };
  38222. if (!useVertexColor) {
  38223. options.uniforms.push("color");
  38224. options.needAlphaBlending = true;
  38225. }
  38226. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  38227. return _this;
  38228. }
  38229. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  38230. /**
  38231. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  38232. * This margin is expressed in world space coordinates, so its value may vary.
  38233. * Default value is 0.1
  38234. * @returns the intersection Threshold value.
  38235. */
  38236. get: function () {
  38237. return this._intersectionThreshold;
  38238. },
  38239. /**
  38240. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  38241. * This margin is expressed in world space coordinates, so its value may vary.
  38242. * @param value the new threshold to apply
  38243. */
  38244. set: function (value) {
  38245. if (this._intersectionThreshold === value) {
  38246. return;
  38247. }
  38248. this._intersectionThreshold = value;
  38249. if (this.geometry) {
  38250. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  38251. }
  38252. },
  38253. enumerable: true,
  38254. configurable: true
  38255. });
  38256. /**
  38257. * Returns the string "LineMesh"
  38258. */
  38259. LinesMesh.prototype.getClassName = function () {
  38260. return "LinesMesh";
  38261. };
  38262. Object.defineProperty(LinesMesh.prototype, "material", {
  38263. get: function () {
  38264. return this._colorShader;
  38265. },
  38266. enumerable: true,
  38267. configurable: true
  38268. });
  38269. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  38270. get: function () {
  38271. return false;
  38272. },
  38273. enumerable: true,
  38274. configurable: true
  38275. });
  38276. LinesMesh.prototype.createInstance = function (name) {
  38277. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  38278. return null;
  38279. };
  38280. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  38281. // VBOs
  38282. this._geometry._bind(this._colorShader.getEffect());
  38283. // Color
  38284. if (!this.useVertexColor) {
  38285. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  38286. }
  38287. return this;
  38288. };
  38289. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  38290. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  38291. return this;
  38292. }
  38293. var engine = this.getScene().getEngine();
  38294. // Draw order
  38295. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  38296. return this;
  38297. };
  38298. LinesMesh.prototype.dispose = function (doNotRecurse) {
  38299. this._colorShader.dispose();
  38300. _super.prototype.dispose.call(this, doNotRecurse);
  38301. };
  38302. /**
  38303. * Returns a new LineMesh object cloned from the current one.
  38304. */
  38305. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  38306. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  38307. };
  38308. return LinesMesh;
  38309. }(BABYLON.Mesh));
  38310. BABYLON.LinesMesh = LinesMesh;
  38311. })(BABYLON || (BABYLON = {}));
  38312. //# sourceMappingURL=babylon.linesMesh.js.map
  38313. var BABYLON;
  38314. (function (BABYLON) {
  38315. var ShaderMaterial = (function (_super) {
  38316. __extends(ShaderMaterial, _super);
  38317. function ShaderMaterial(name, scene, shaderPath, options) {
  38318. var _this = _super.call(this, name, scene) || this;
  38319. _this._textures = {};
  38320. _this._textureArrays = {};
  38321. _this._floats = {};
  38322. _this._floatsArrays = {};
  38323. _this._colors3 = {};
  38324. _this._colors4 = {};
  38325. _this._vectors2 = {};
  38326. _this._vectors3 = {};
  38327. _this._vectors4 = {};
  38328. _this._matrices = {};
  38329. _this._matrices3x3 = {};
  38330. _this._matrices2x2 = {};
  38331. _this._vectors3Arrays = {};
  38332. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  38333. _this._shaderPath = shaderPath;
  38334. options.needAlphaBlending = options.needAlphaBlending || false;
  38335. options.needAlphaTesting = options.needAlphaTesting || false;
  38336. options.attributes = options.attributes || ["position", "normal", "uv"];
  38337. options.uniforms = options.uniforms || ["worldViewProjection"];
  38338. options.uniformBuffers = options.uniformBuffers || [];
  38339. options.samplers = options.samplers || [];
  38340. options.defines = options.defines || [];
  38341. _this._options = options;
  38342. return _this;
  38343. }
  38344. ShaderMaterial.prototype.getClassName = function () {
  38345. return "ShaderMaterial";
  38346. };
  38347. ShaderMaterial.prototype.needAlphaBlending = function () {
  38348. return this._options.needAlphaBlending;
  38349. };
  38350. ShaderMaterial.prototype.needAlphaTesting = function () {
  38351. return this._options.needAlphaTesting;
  38352. };
  38353. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  38354. if (this._options.uniforms.indexOf(uniformName) === -1) {
  38355. this._options.uniforms.push(uniformName);
  38356. }
  38357. };
  38358. ShaderMaterial.prototype.setTexture = function (name, texture) {
  38359. if (this._options.samplers.indexOf(name) === -1) {
  38360. this._options.samplers.push(name);
  38361. }
  38362. this._textures[name] = texture;
  38363. return this;
  38364. };
  38365. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  38366. if (this._options.samplers.indexOf(name) === -1) {
  38367. this._options.samplers.push(name);
  38368. }
  38369. this._checkUniform(name);
  38370. this._textureArrays[name] = textures;
  38371. return this;
  38372. };
  38373. ShaderMaterial.prototype.setFloat = function (name, value) {
  38374. this._checkUniform(name);
  38375. this._floats[name] = value;
  38376. return this;
  38377. };
  38378. ShaderMaterial.prototype.setFloats = function (name, value) {
  38379. this._checkUniform(name);
  38380. this._floatsArrays[name] = value;
  38381. return this;
  38382. };
  38383. ShaderMaterial.prototype.setColor3 = function (name, value) {
  38384. this._checkUniform(name);
  38385. this._colors3[name] = value;
  38386. return this;
  38387. };
  38388. ShaderMaterial.prototype.setColor4 = function (name, value) {
  38389. this._checkUniform(name);
  38390. this._colors4[name] = value;
  38391. return this;
  38392. };
  38393. ShaderMaterial.prototype.setVector2 = function (name, value) {
  38394. this._checkUniform(name);
  38395. this._vectors2[name] = value;
  38396. return this;
  38397. };
  38398. ShaderMaterial.prototype.setVector3 = function (name, value) {
  38399. this._checkUniform(name);
  38400. this._vectors3[name] = value;
  38401. return this;
  38402. };
  38403. ShaderMaterial.prototype.setVector4 = function (name, value) {
  38404. this._checkUniform(name);
  38405. this._vectors4[name] = value;
  38406. return this;
  38407. };
  38408. ShaderMaterial.prototype.setMatrix = function (name, value) {
  38409. this._checkUniform(name);
  38410. this._matrices[name] = value;
  38411. return this;
  38412. };
  38413. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  38414. this._checkUniform(name);
  38415. this._matrices3x3[name] = value;
  38416. return this;
  38417. };
  38418. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  38419. this._checkUniform(name);
  38420. this._matrices2x2[name] = value;
  38421. return this;
  38422. };
  38423. ShaderMaterial.prototype.setArray3 = function (name, value) {
  38424. this._checkUniform(name);
  38425. this._vectors3Arrays[name] = value;
  38426. return this;
  38427. };
  38428. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  38429. if (!mesh) {
  38430. return true;
  38431. }
  38432. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  38433. return false;
  38434. }
  38435. return false;
  38436. };
  38437. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  38438. var scene = this.getScene();
  38439. var engine = scene.getEngine();
  38440. if (!this.checkReadyOnEveryCall) {
  38441. if (this._renderId === scene.getRenderId()) {
  38442. if (this._checkCache(scene, mesh, useInstances)) {
  38443. return true;
  38444. }
  38445. }
  38446. }
  38447. // Instances
  38448. var defines = [];
  38449. var attribs = [];
  38450. var fallbacks = new BABYLON.EffectFallbacks();
  38451. if (useInstances) {
  38452. defines.push("#define INSTANCES");
  38453. }
  38454. for (var index = 0; index < this._options.defines.length; index++) {
  38455. defines.push(this._options.defines[index]);
  38456. }
  38457. for (var index = 0; index < this._options.attributes.length; index++) {
  38458. attribs.push(this._options.attributes[index]);
  38459. }
  38460. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38461. attribs.push(BABYLON.VertexBuffer.ColorKind);
  38462. defines.push("#define VERTEXCOLOR");
  38463. }
  38464. // Bones
  38465. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  38466. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38467. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38468. if (mesh.numBoneInfluencers > 4) {
  38469. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38470. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38471. }
  38472. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  38473. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  38474. fallbacks.addCPUSkinningFallback(0, mesh);
  38475. }
  38476. else {
  38477. defines.push("#define NUM_BONE_INFLUENCERS 0");
  38478. }
  38479. // Textures
  38480. for (var name in this._textures) {
  38481. if (!this._textures[name].isReady()) {
  38482. return false;
  38483. }
  38484. }
  38485. // Alpha test
  38486. if (engine.getAlphaTesting()) {
  38487. defines.push("#define ALPHATEST");
  38488. }
  38489. var previousEffect = this._effect;
  38490. var join = defines.join("\n");
  38491. this._effect = engine.createEffect(this._shaderPath, {
  38492. attributes: attribs,
  38493. uniformsNames: this._options.uniforms,
  38494. uniformBuffersNames: this._options.uniformBuffers,
  38495. samplers: this._options.samplers,
  38496. defines: join,
  38497. fallbacks: fallbacks,
  38498. onCompiled: this.onCompiled,
  38499. onError: this.onError
  38500. }, engine);
  38501. if (!this._effect.isReady()) {
  38502. return false;
  38503. }
  38504. if (previousEffect !== this._effect) {
  38505. scene.resetCachedMaterial();
  38506. }
  38507. this._renderId = scene.getRenderId();
  38508. return true;
  38509. };
  38510. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38511. var scene = this.getScene();
  38512. if (this._options.uniforms.indexOf("world") !== -1) {
  38513. this._effect.setMatrix("world", world);
  38514. }
  38515. if (this._options.uniforms.indexOf("worldView") !== -1) {
  38516. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  38517. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  38518. }
  38519. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  38520. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  38521. }
  38522. };
  38523. ShaderMaterial.prototype.bind = function (world, mesh) {
  38524. // Std values
  38525. this.bindOnlyWorldMatrix(world);
  38526. if (this.getScene().getCachedMaterial() !== this) {
  38527. if (this._options.uniforms.indexOf("view") !== -1) {
  38528. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  38529. }
  38530. if (this._options.uniforms.indexOf("projection") !== -1) {
  38531. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  38532. }
  38533. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  38534. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  38535. }
  38536. // Bones
  38537. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  38538. var name;
  38539. // Texture
  38540. for (name in this._textures) {
  38541. this._effect.setTexture(name, this._textures[name]);
  38542. }
  38543. // Texture arrays
  38544. for (name in this._textureArrays) {
  38545. this._effect.setTextureArray(name, this._textureArrays[name]);
  38546. }
  38547. // Float
  38548. for (name in this._floats) {
  38549. this._effect.setFloat(name, this._floats[name]);
  38550. }
  38551. // Float s
  38552. for (name in this._floatsArrays) {
  38553. this._effect.setArray(name, this._floatsArrays[name]);
  38554. }
  38555. // Color3
  38556. for (name in this._colors3) {
  38557. this._effect.setColor3(name, this._colors3[name]);
  38558. }
  38559. // Color4
  38560. for (name in this._colors4) {
  38561. var color = this._colors4[name];
  38562. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  38563. }
  38564. // Vector2
  38565. for (name in this._vectors2) {
  38566. this._effect.setVector2(name, this._vectors2[name]);
  38567. }
  38568. // Vector3
  38569. for (name in this._vectors3) {
  38570. this._effect.setVector3(name, this._vectors3[name]);
  38571. }
  38572. // Vector4
  38573. for (name in this._vectors4) {
  38574. this._effect.setVector4(name, this._vectors4[name]);
  38575. }
  38576. // Matrix
  38577. for (name in this._matrices) {
  38578. this._effect.setMatrix(name, this._matrices[name]);
  38579. }
  38580. // Matrix 3x3
  38581. for (name in this._matrices3x3) {
  38582. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  38583. }
  38584. // Matrix 2x2
  38585. for (name in this._matrices2x2) {
  38586. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  38587. }
  38588. // Vector3Array
  38589. for (name in this._vectors3Arrays) {
  38590. this._effect.setArray3(name, this._vectors3Arrays[name]);
  38591. }
  38592. }
  38593. this._afterBind(mesh);
  38594. };
  38595. ShaderMaterial.prototype.clone = function (name) {
  38596. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  38597. return newShaderMaterial;
  38598. };
  38599. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  38600. if (forceDisposeTextures) {
  38601. var name;
  38602. for (name in this._textures) {
  38603. this._textures[name].dispose();
  38604. }
  38605. for (name in this._textureArrays) {
  38606. var array = this._textureArrays[name];
  38607. for (var index = 0; index < array.length; index++) {
  38608. array[index].dispose();
  38609. }
  38610. }
  38611. }
  38612. this._textures = {};
  38613. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  38614. };
  38615. ShaderMaterial.prototype.serialize = function () {
  38616. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38617. serializationObject.customType = "BABYLON.ShaderMaterial";
  38618. serializationObject.options = this._options;
  38619. serializationObject.shaderPath = this._shaderPath;
  38620. var name;
  38621. // Texture
  38622. serializationObject.textures = {};
  38623. for (name in this._textures) {
  38624. serializationObject.textures[name] = this._textures[name].serialize();
  38625. }
  38626. // Texture arrays
  38627. serializationObject.textureArrays = {};
  38628. for (name in this._textureArrays) {
  38629. serializationObject.textureArrays[name] = [];
  38630. var array = this._textureArrays[name];
  38631. for (var index = 0; index < array.length; index++) {
  38632. serializationObject.textureArrays[name].push(array[index].serialize());
  38633. }
  38634. }
  38635. // Float
  38636. serializationObject.floats = {};
  38637. for (name in this._floats) {
  38638. serializationObject.floats[name] = this._floats[name];
  38639. }
  38640. // Float s
  38641. serializationObject.floatArrays = {};
  38642. for (name in this._floatsArrays) {
  38643. serializationObject.floatArrays[name] = this._floatsArrays[name];
  38644. }
  38645. // Color3
  38646. serializationObject.colors3 = {};
  38647. for (name in this._colors3) {
  38648. serializationObject.colors3[name] = this._colors3[name].asArray();
  38649. }
  38650. // Color4
  38651. serializationObject.colors4 = {};
  38652. for (name in this._colors4) {
  38653. serializationObject.colors4[name] = this._colors4[name].asArray();
  38654. }
  38655. // Vector2
  38656. serializationObject.vectors2 = {};
  38657. for (name in this._vectors2) {
  38658. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  38659. }
  38660. // Vector3
  38661. serializationObject.vectors3 = {};
  38662. for (name in this._vectors3) {
  38663. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  38664. }
  38665. // Vector4
  38666. serializationObject.vectors4 = {};
  38667. for (name in this._vectors4) {
  38668. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  38669. }
  38670. // Matrix
  38671. serializationObject.matrices = {};
  38672. for (name in this._matrices) {
  38673. serializationObject.matrices[name] = this._matrices[name].asArray();
  38674. }
  38675. // Matrix 3x3
  38676. serializationObject.matrices3x3 = {};
  38677. for (name in this._matrices3x3) {
  38678. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  38679. }
  38680. // Matrix 2x2
  38681. serializationObject.matrices2x2 = {};
  38682. for (name in this._matrices2x2) {
  38683. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  38684. }
  38685. // Vector3Array
  38686. serializationObject.vectors3Arrays = {};
  38687. for (name in this._vectors3Arrays) {
  38688. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  38689. }
  38690. return serializationObject;
  38691. };
  38692. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  38693. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  38694. var name;
  38695. // Texture
  38696. for (name in source.textures) {
  38697. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  38698. }
  38699. // Texture arrays
  38700. for (name in source.textureArrays) {
  38701. var array = source.textureArrays[name];
  38702. var textureArray = new Array();
  38703. for (var index = 0; index < array.length; index++) {
  38704. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  38705. }
  38706. material.setTextureArray(name, textureArray);
  38707. }
  38708. // Float
  38709. for (name in source.floats) {
  38710. material.setFloat(name, source.floats[name]);
  38711. }
  38712. // Float s
  38713. for (name in source.floatsArrays) {
  38714. material.setFloats(name, source.floatsArrays[name]);
  38715. }
  38716. // Color3
  38717. for (name in source.colors3) {
  38718. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  38719. }
  38720. // Color4
  38721. for (name in source.colors4) {
  38722. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  38723. }
  38724. // Vector2
  38725. for (name in source.vectors2) {
  38726. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  38727. }
  38728. // Vector3
  38729. for (name in source.vectors3) {
  38730. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  38731. }
  38732. // Vector4
  38733. for (name in source.vectors4) {
  38734. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  38735. }
  38736. // Matrix
  38737. for (name in source.matrices) {
  38738. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  38739. }
  38740. // Matrix 3x3
  38741. for (name in source.matrices3x3) {
  38742. material.setMatrix3x3(name, source.matrices3x3[name]);
  38743. }
  38744. // Matrix 2x2
  38745. for (name in source.matrices2x2) {
  38746. material.setMatrix2x2(name, source.matrices2x2[name]);
  38747. }
  38748. // Vector3Array
  38749. for (name in source.vectors3Arrays) {
  38750. material.setArray3(name, source.vectors3Arrays[name]);
  38751. }
  38752. return material;
  38753. };
  38754. return ShaderMaterial;
  38755. }(BABYLON.Material));
  38756. BABYLON.ShaderMaterial = ShaderMaterial;
  38757. })(BABYLON || (BABYLON = {}));
  38758. //# sourceMappingURL=babylon.shaderMaterial.js.map
  38759. var BABYLON;
  38760. (function (BABYLON) {
  38761. var MeshBuilder = (function () {
  38762. function MeshBuilder() {
  38763. }
  38764. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  38765. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  38766. return BABYLON.Mesh.DOUBLESIDE;
  38767. }
  38768. if (orientation === undefined || orientation === null) {
  38769. return BABYLON.Mesh.FRONTSIDE;
  38770. }
  38771. return orientation;
  38772. };
  38773. /**
  38774. * Creates a box mesh.
  38775. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  38776. * The parameter `size` sets the size (float) of each box side (default 1).
  38777. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  38778. * 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).
  38779. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  38780. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38781. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38782. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38783. */
  38784. MeshBuilder.CreateBox = function (name, options, scene) {
  38785. var box = new BABYLON.Mesh(name, scene);
  38786. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38787. box.sideOrientation = options.sideOrientation;
  38788. var vertexData = BABYLON.VertexData.CreateBox(options);
  38789. vertexData.applyToMesh(box, options.updatable);
  38790. return box;
  38791. };
  38792. /**
  38793. * Creates a sphere mesh.
  38794. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  38795. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  38796. * 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`).
  38797. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  38798. * 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
  38799. * 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).
  38800. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38801. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38802. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38803. */
  38804. MeshBuilder.CreateSphere = function (name, options, scene) {
  38805. var sphere = new BABYLON.Mesh(name, scene);
  38806. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38807. sphere.sideOrientation = options.sideOrientation;
  38808. var vertexData = BABYLON.VertexData.CreateSphere(options);
  38809. vertexData.applyToMesh(sphere, options.updatable);
  38810. return sphere;
  38811. };
  38812. /**
  38813. * Creates a plane polygonal mesh. By default, this is a disc.
  38814. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  38815. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  38816. * 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.
  38817. * 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
  38818. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38819. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38820. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38821. */
  38822. MeshBuilder.CreateDisc = function (name, options, scene) {
  38823. var disc = new BABYLON.Mesh(name, scene);
  38824. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38825. disc.sideOrientation = options.sideOrientation;
  38826. var vertexData = BABYLON.VertexData.CreateDisc(options);
  38827. vertexData.applyToMesh(disc, options.updatable);
  38828. return disc;
  38829. };
  38830. /**
  38831. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  38832. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  38833. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  38834. * 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`).
  38835. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  38836. * 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.
  38837. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38838. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38839. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38840. */
  38841. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  38842. var sphere = new BABYLON.Mesh(name, scene);
  38843. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38844. sphere.sideOrientation = options.sideOrientation;
  38845. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  38846. vertexData.applyToMesh(sphere, options.updatable);
  38847. return sphere;
  38848. };
  38849. ;
  38850. /**
  38851. * Creates a ribbon mesh.
  38852. * 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.
  38853. *
  38854. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  38855. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  38856. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  38857. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  38858. * 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.
  38859. * 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.
  38860. * 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
  38861. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38862. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38863. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  38864. * The parameter `uvs` is an optional flat array of `Vector2` to update/set each ribbon vertex with its own custom UV values instead of the computed ones.
  38865. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  38866. * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that
  38867. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  38868. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  38869. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38870. */
  38871. MeshBuilder.CreateRibbon = function (name, options, scene) {
  38872. var pathArray = options.pathArray;
  38873. var closeArray = options.closeArray;
  38874. var closePath = options.closePath;
  38875. var offset = options.offset;
  38876. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38877. var instance = options.instance;
  38878. var updatable = options.updatable;
  38879. if (instance) {
  38880. // positionFunction : ribbon case
  38881. // only pathArray and sideOrientation parameters are taken into account for positions update
  38882. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  38883. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  38884. var positionFunction = function (positions) {
  38885. var minlg = pathArray[0].length;
  38886. var i = 0;
  38887. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  38888. for (var si = 1; si <= ns; si++) {
  38889. for (var p = 0; p < pathArray.length; p++) {
  38890. var path = pathArray[p];
  38891. var l = path.length;
  38892. minlg = (minlg < l) ? minlg : l;
  38893. var j = 0;
  38894. while (j < minlg) {
  38895. positions[i] = path[j].x;
  38896. positions[i + 1] = path[j].y;
  38897. positions[i + 2] = path[j].z;
  38898. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  38899. BABYLON.Tmp.Vector3[0].x = path[j].x;
  38900. }
  38901. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  38902. BABYLON.Tmp.Vector3[1].x = path[j].x;
  38903. }
  38904. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  38905. BABYLON.Tmp.Vector3[0].y = path[j].y;
  38906. }
  38907. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  38908. BABYLON.Tmp.Vector3[1].y = path[j].y;
  38909. }
  38910. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  38911. BABYLON.Tmp.Vector3[0].z = path[j].z;
  38912. }
  38913. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  38914. BABYLON.Tmp.Vector3[1].z = path[j].z;
  38915. }
  38916. j++;
  38917. i += 3;
  38918. }
  38919. if (instance._closePath) {
  38920. positions[i] = path[0].x;
  38921. positions[i + 1] = path[0].y;
  38922. positions[i + 2] = path[0].z;
  38923. i += 3;
  38924. }
  38925. }
  38926. }
  38927. };
  38928. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38929. positionFunction(positions);
  38930. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  38931. instance._boundingInfo.update(instance._worldMatrix);
  38932. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  38933. if (options.colors) {
  38934. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  38935. for (var c = 0; c < options.colors.length; c++) {
  38936. colors[c * 4] = options.colors[c].r;
  38937. colors[c * 4 + 1] = options.colors[c].g;
  38938. colors[c * 4 + 2] = options.colors[c].b;
  38939. colors[c * 4 + 3] = options.colors[c].a;
  38940. }
  38941. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  38942. }
  38943. if (options.uvs) {
  38944. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38945. for (var i = 0; i < options.uvs.length; i++) {
  38946. uvs[i * 2] = options.uvs[i].x;
  38947. uvs[i * 2 + 1] = options.uvs[i].y;
  38948. }
  38949. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  38950. }
  38951. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  38952. var indices = instance.getIndices();
  38953. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38954. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  38955. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  38956. if (instance._closePath) {
  38957. var indexFirst = 0;
  38958. var indexLast = 0;
  38959. for (var p = 0; p < pathArray.length; p++) {
  38960. indexFirst = instance._idx[p] * 3;
  38961. if (p + 1 < pathArray.length) {
  38962. indexLast = (instance._idx[p + 1] - 1) * 3;
  38963. }
  38964. else {
  38965. indexLast = normals.length - 3;
  38966. }
  38967. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  38968. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  38969. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  38970. normals[indexLast] = normals[indexFirst];
  38971. normals[indexLast + 1] = normals[indexFirst + 1];
  38972. normals[indexLast + 2] = normals[indexFirst + 2];
  38973. }
  38974. }
  38975. if (!(instance.areNormalsFrozen)) {
  38976. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  38977. }
  38978. }
  38979. return instance;
  38980. }
  38981. else {
  38982. var ribbon = new BABYLON.Mesh(name, scene);
  38983. ribbon.sideOrientation = sideOrientation;
  38984. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  38985. if (closePath) {
  38986. ribbon._idx = vertexData._idx;
  38987. }
  38988. ribbon._closePath = closePath;
  38989. ribbon._closeArray = closeArray;
  38990. vertexData.applyToMesh(ribbon, updatable);
  38991. return ribbon;
  38992. }
  38993. };
  38994. /**
  38995. * Creates a cylinder or a cone mesh.
  38996. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  38997. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  38998. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  38999. * 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.
  39000. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  39001. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  39002. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  39003. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  39004. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  39005. * 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).
  39006. * 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
  39007. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  39008. * 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
  39009. * 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.
  39010. * If `enclose` is false, a ring surface is one element.
  39011. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  39012. * 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
  39013. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39014. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39015. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39016. */
  39017. MeshBuilder.CreateCylinder = function (name, options, scene) {
  39018. var cylinder = new BABYLON.Mesh(name, scene);
  39019. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39020. cylinder.sideOrientation = options.sideOrientation;
  39021. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  39022. vertexData.applyToMesh(cylinder, options.updatable);
  39023. return cylinder;
  39024. };
  39025. /**
  39026. * Creates a torus mesh.
  39027. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  39028. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  39029. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  39030. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  39031. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39032. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39033. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39034. */
  39035. MeshBuilder.CreateTorus = function (name, options, scene) {
  39036. var torus = new BABYLON.Mesh(name, scene);
  39037. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39038. torus.sideOrientation = options.sideOrientation;
  39039. var vertexData = BABYLON.VertexData.CreateTorus(options);
  39040. vertexData.applyToMesh(torus, options.updatable);
  39041. return torus;
  39042. };
  39043. /**
  39044. * Creates a torus knot mesh.
  39045. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  39046. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  39047. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  39048. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  39049. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  39050. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39051. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39052. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39053. */
  39054. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  39055. var torusKnot = new BABYLON.Mesh(name, scene);
  39056. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39057. torusKnot.sideOrientation = options.sideOrientation;
  39058. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  39059. vertexData.applyToMesh(torusKnot, options.updatable);
  39060. return torusKnot;
  39061. };
  39062. /**
  39063. * Creates a line system mesh.
  39064. * A line system is a pool of many lines gathered in a single mesh.
  39065. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  39066. * 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.
  39067. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  39068. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  39069. * 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
  39070. * 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
  39071. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  39072. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39073. */
  39074. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  39075. var instance = options.instance;
  39076. var lines = options.lines;
  39077. if (instance) {
  39078. var positionFunction = function (positions) {
  39079. var i = 0;
  39080. for (var l = 0; l < lines.length; l++) {
  39081. var points = lines[l];
  39082. for (var p = 0; p < points.length; p++) {
  39083. positions[i] = points[p].x;
  39084. positions[i + 1] = points[p].y;
  39085. positions[i + 2] = points[p].z;
  39086. i += 3;
  39087. }
  39088. }
  39089. };
  39090. instance.updateMeshPositions(positionFunction, false);
  39091. return instance;
  39092. }
  39093. // line system creation
  39094. var lineSystem = new BABYLON.LinesMesh(name, scene);
  39095. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  39096. vertexData.applyToMesh(lineSystem, options.updatable);
  39097. return lineSystem;
  39098. };
  39099. /**
  39100. * Creates a line mesh.
  39101. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  39102. * 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.
  39103. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  39104. * The parameter `points` is an array successive Vector3.
  39105. * 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
  39106. * When updating an instance, remember that only point positions can change, not the number of points.
  39107. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39108. */
  39109. MeshBuilder.CreateLines = function (name, options, scene) {
  39110. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  39111. return lines;
  39112. };
  39113. /**
  39114. * Creates a dashed line mesh.
  39115. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  39116. * 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.
  39117. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  39118. * The parameter `points` is an array successive Vector3.
  39119. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  39120. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  39121. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  39122. * 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
  39123. * When updating an instance, remember that only point positions can change, not the number of points.
  39124. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39125. */
  39126. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  39127. var points = options.points;
  39128. var instance = options.instance;
  39129. var gapSize = options.gapSize;
  39130. var dashNb = options.dashNb;
  39131. var dashSize = options.dashSize;
  39132. if (instance) {
  39133. var positionFunction = function (positions) {
  39134. var curvect = BABYLON.Vector3.Zero();
  39135. var nbSeg = positions.length / 6;
  39136. var lg = 0;
  39137. var nb = 0;
  39138. var shft = 0;
  39139. var dashshft = 0;
  39140. var curshft = 0;
  39141. var p = 0;
  39142. var i = 0;
  39143. var j = 0;
  39144. for (i = 0; i < points.length - 1; i++) {
  39145. points[i + 1].subtractToRef(points[i], curvect);
  39146. lg += curvect.length();
  39147. }
  39148. shft = lg / nbSeg;
  39149. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  39150. for (i = 0; i < points.length - 1; i++) {
  39151. points[i + 1].subtractToRef(points[i], curvect);
  39152. nb = Math.floor(curvect.length() / shft);
  39153. curvect.normalize();
  39154. j = 0;
  39155. while (j < nb && p < positions.length) {
  39156. curshft = shft * j;
  39157. positions[p] = points[i].x + curshft * curvect.x;
  39158. positions[p + 1] = points[i].y + curshft * curvect.y;
  39159. positions[p + 2] = points[i].z + curshft * curvect.z;
  39160. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  39161. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  39162. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  39163. p += 6;
  39164. j++;
  39165. }
  39166. }
  39167. while (p < positions.length) {
  39168. positions[p] = points[i].x;
  39169. positions[p + 1] = points[i].y;
  39170. positions[p + 2] = points[i].z;
  39171. p += 3;
  39172. }
  39173. };
  39174. instance.updateMeshPositions(positionFunction, false);
  39175. return instance;
  39176. }
  39177. // dashed lines creation
  39178. var dashedLines = new BABYLON.LinesMesh(name, scene);
  39179. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  39180. vertexData.applyToMesh(dashedLines, options.updatable);
  39181. dashedLines.dashSize = dashSize;
  39182. dashedLines.gapSize = gapSize;
  39183. return dashedLines;
  39184. };
  39185. /**
  39186. * Creates an extruded shape mesh.
  39187. * 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.
  39188. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  39189. *
  39190. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  39191. * 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
  39192. * extruded along the Z axis.
  39193. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  39194. * 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.
  39195. * The parameter `scale` (float, default 1) is the value to scale the shape.
  39196. * 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
  39197. * 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
  39198. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  39199. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39200. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39201. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39202. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39203. */
  39204. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  39205. var path = options.path;
  39206. var shape = options.shape;
  39207. var scale = options.scale || 1;
  39208. var rotation = options.rotation || 0;
  39209. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  39210. var updatable = options.updatable;
  39211. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39212. var instance = options.instance;
  39213. var invertUV = options.invertUV || false;
  39214. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  39215. };
  39216. /**
  39217. * Creates an custom extruded shape mesh.
  39218. * 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.
  39219. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  39220. *
  39221. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  39222. * 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
  39223. * extruded along the Z axis.
  39224. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  39225. * 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
  39226. * and the distance of this point from the begining of the path :
  39227. * ```javascript
  39228. * var rotationFunction = function(i, distance) {
  39229. * // do things
  39230. * return rotationValue; }
  39231. * ```
  39232. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  39233. * 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
  39234. * and the distance of this point from the begining of the path :
  39235. * ```javascript
  39236. * var scaleFunction = function(i, distance) {
  39237. * // do things
  39238. * return scaleValue;}
  39239. * ```
  39240. * It must returns a float value that will be the scale value applied to the shape on each path point.
  39241. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  39242. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  39243. * 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
  39244. * 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
  39245. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  39246. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39247. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39248. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39249. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39250. */
  39251. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  39252. var path = options.path;
  39253. var shape = options.shape;
  39254. var scaleFunction = options.scaleFunction || (function () { return 1; });
  39255. var rotationFunction = options.rotationFunction || (function () { return 0; });
  39256. var ribbonCloseArray = options.ribbonCloseArray || false;
  39257. var ribbonClosePath = options.ribbonClosePath || false;
  39258. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  39259. var updatable = options.updatable;
  39260. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39261. var instance = options.instance;
  39262. var invertUV = options.invertUV || false;
  39263. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  39264. };
  39265. /**
  39266. * Creates lathe mesh.
  39267. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  39268. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  39269. *
  39270. * 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
  39271. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  39272. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  39273. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  39274. * 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.
  39275. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  39276. * 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
  39277. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39278. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39279. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39280. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39281. */
  39282. MeshBuilder.CreateLathe = function (name, options, scene) {
  39283. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  39284. var closed = (options.closed === undefined) ? true : options.closed;
  39285. var shape = options.shape;
  39286. var radius = options.radius || 1;
  39287. var tessellation = options.tessellation || 64;
  39288. var updatable = options.updatable;
  39289. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39290. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  39291. var pi2 = Math.PI * 2;
  39292. var paths = new Array();
  39293. var invertUV = options.invertUV || false;
  39294. var i = 0;
  39295. var p = 0;
  39296. var step = pi2 / tessellation * arc;
  39297. var rotated;
  39298. var path = new Array();
  39299. ;
  39300. for (i = 0; i <= tessellation; i++) {
  39301. var path = [];
  39302. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  39303. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  39304. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  39305. }
  39306. for (p = 0; p < shape.length; p++) {
  39307. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  39308. path.push(rotated);
  39309. }
  39310. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  39311. 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));
  39312. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  39313. }
  39314. paths.push(path);
  39315. }
  39316. // lathe ribbon
  39317. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  39318. return lathe;
  39319. };
  39320. /**
  39321. * Creates a plane mesh.
  39322. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  39323. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  39324. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  39325. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  39326. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39327. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39328. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39329. */
  39330. MeshBuilder.CreatePlane = function (name, options, scene) {
  39331. var plane = new BABYLON.Mesh(name, scene);
  39332. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39333. plane.sideOrientation = options.sideOrientation;
  39334. var vertexData = BABYLON.VertexData.CreatePlane(options);
  39335. vertexData.applyToMesh(plane, options.updatable);
  39336. if (options.sourcePlane) {
  39337. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  39338. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  39339. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  39340. plane.rotate(vectorProduct, product);
  39341. }
  39342. return plane;
  39343. };
  39344. /**
  39345. * Creates a ground mesh.
  39346. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  39347. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  39348. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  39349. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39350. */
  39351. MeshBuilder.CreateGround = function (name, options, scene) {
  39352. var ground = new BABYLON.GroundMesh(name, scene);
  39353. ground._setReady(false);
  39354. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  39355. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  39356. ground._width = options.width || 1;
  39357. ground._height = options.height || 1;
  39358. ground._maxX = ground._width / 2;
  39359. ground._maxZ = ground._height / 2;
  39360. ground._minX = -ground._maxX;
  39361. ground._minZ = -ground._maxZ;
  39362. var vertexData = BABYLON.VertexData.CreateGround(options);
  39363. vertexData.applyToMesh(ground, options.updatable);
  39364. ground._setReady(true);
  39365. return ground;
  39366. };
  39367. /**
  39368. * Creates a tiled ground mesh.
  39369. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  39370. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  39371. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  39372. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  39373. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  39374. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  39375. * numbers of subdivisions on the ground width and height of each tile.
  39376. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39377. */
  39378. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  39379. var tiledGround = new BABYLON.Mesh(name, scene);
  39380. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  39381. vertexData.applyToMesh(tiledGround, options.updatable);
  39382. return tiledGround;
  39383. };
  39384. /**
  39385. * Creates a ground mesh from a height map.
  39386. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  39387. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  39388. * The parameter `url` sets the URL of the height map image resource.
  39389. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  39390. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  39391. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  39392. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  39393. * The parameter `colorFilter` (optional Color3, default (0.3, 0.59, 0.11) ) is the filter to apply to the image pixel colors to compute the height.
  39394. * 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).
  39395. * This function is passed the newly built mesh :
  39396. * ```javascript
  39397. * function(mesh) { // do things
  39398. * return; }
  39399. * ```
  39400. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39401. */
  39402. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  39403. var width = options.width || 10.0;
  39404. var height = options.height || 10.0;
  39405. var subdivisions = options.subdivisions || 1 | 0;
  39406. var minHeight = options.minHeight || 0.0;
  39407. var maxHeight = options.maxHeight || 10.0;
  39408. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  39409. var updatable = options.updatable;
  39410. var onReady = options.onReady;
  39411. var ground = new BABYLON.GroundMesh(name, scene);
  39412. ground._subdivisionsX = subdivisions;
  39413. ground._subdivisionsY = subdivisions;
  39414. ground._width = width;
  39415. ground._height = height;
  39416. ground._maxX = ground._width / 2.0;
  39417. ground._maxZ = ground._height / 2.0;
  39418. ground._minX = -ground._maxX;
  39419. ground._minZ = -ground._maxZ;
  39420. ground._setReady(false);
  39421. var onload = function (img) {
  39422. // Getting height map data
  39423. var canvas = document.createElement("canvas");
  39424. var context = canvas.getContext("2d");
  39425. var bufferWidth = img.width;
  39426. var bufferHeight = img.height;
  39427. canvas.width = bufferWidth;
  39428. canvas.height = bufferHeight;
  39429. context.drawImage(img, 0, 0);
  39430. // Create VertexData from map data
  39431. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  39432. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  39433. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  39434. width: width, height: height,
  39435. subdivisions: subdivisions,
  39436. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  39437. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  39438. });
  39439. vertexData.applyToMesh(ground, updatable);
  39440. ground._setReady(true);
  39441. //execute ready callback, if set
  39442. if (onReady) {
  39443. onReady(ground);
  39444. }
  39445. };
  39446. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  39447. return ground;
  39448. };
  39449. /**
  39450. * Creates a tube mesh.
  39451. * 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.
  39452. *
  39453. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  39454. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  39455. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  39456. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  39457. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  39458. * 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.
  39459. * It must return a radius value (positive float) :
  39460. * ```javascript
  39461. * var radiusFunction = function(i, distance) {
  39462. * // do things
  39463. * return radius; }
  39464. * ```
  39465. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  39466. * 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
  39467. * 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
  39468. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39469. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39470. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39471. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39472. */
  39473. MeshBuilder.CreateTube = function (name, options, scene) {
  39474. var path = options.path;
  39475. var radius = options.radius || 1.0;
  39476. var tessellation = options.tessellation || 64 | 0;
  39477. var radiusFunction = options.radiusFunction;
  39478. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  39479. var invertUV = options.invertUV || false;
  39480. var updatable = options.updatable;
  39481. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39482. var instance = options.instance;
  39483. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  39484. // tube geometry
  39485. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  39486. var tangents = path3D.getTangents();
  39487. var normals = path3D.getNormals();
  39488. var distances = path3D.getDistances();
  39489. var pi2 = Math.PI * 2;
  39490. var step = pi2 / tessellation * arc;
  39491. var returnRadius = function () { return radius; };
  39492. var radiusFunctionFinal = radiusFunction || returnRadius;
  39493. var circlePath;
  39494. var rad;
  39495. var normal;
  39496. var rotated;
  39497. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  39498. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  39499. for (var i = 0; i < path.length; i++) {
  39500. rad = radiusFunctionFinal(i, distances[i]); // current radius
  39501. circlePath = Array(); // current circle array
  39502. normal = normals[i]; // current normal
  39503. for (var t = 0; t < tessellation; t++) {
  39504. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  39505. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  39506. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  39507. rotated.scaleInPlace(rad).addInPlace(path[i]);
  39508. circlePath[t] = rotated;
  39509. }
  39510. circlePaths[index] = circlePath;
  39511. index++;
  39512. }
  39513. // cap
  39514. var capPath = function (nbPoints, pathIndex) {
  39515. var pointCap = Array();
  39516. for (var i = 0; i < nbPoints; i++) {
  39517. pointCap.push(path[pathIndex]);
  39518. }
  39519. return pointCap;
  39520. };
  39521. switch (cap) {
  39522. case BABYLON.Mesh.NO_CAP:
  39523. break;
  39524. case BABYLON.Mesh.CAP_START:
  39525. circlePaths[0] = capPath(tessellation, 0);
  39526. circlePaths[1] = circlePaths[2].slice(0);
  39527. break;
  39528. case BABYLON.Mesh.CAP_END:
  39529. circlePaths[index] = circlePaths[index - 1].slice(0);
  39530. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  39531. break;
  39532. case BABYLON.Mesh.CAP_ALL:
  39533. circlePaths[0] = capPath(tessellation, 0);
  39534. circlePaths[1] = circlePaths[2].slice(0);
  39535. circlePaths[index] = circlePaths[index - 1].slice(0);
  39536. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  39537. break;
  39538. default:
  39539. break;
  39540. }
  39541. return circlePaths;
  39542. };
  39543. var path3D;
  39544. var pathArray;
  39545. if (instance) {
  39546. var arc = options.arc || instance.arc;
  39547. path3D = (instance.path3D).update(path);
  39548. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  39549. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  39550. instance.path3D = path3D;
  39551. instance.pathArray = pathArray;
  39552. instance.arc = arc;
  39553. return instance;
  39554. }
  39555. // tube creation
  39556. path3D = new BABYLON.Path3D(path);
  39557. var newPathArray = new Array();
  39558. cap = (cap < 0 || cap > 3) ? 0 : cap;
  39559. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  39560. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  39561. tube.pathArray = pathArray;
  39562. tube.path3D = path3D;
  39563. tube.tessellation = tessellation;
  39564. tube.cap = cap;
  39565. tube.arc = options.arc;
  39566. return tube;
  39567. };
  39568. /**
  39569. * Creates a polyhedron mesh.
  39570. *
  39571. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  39572. * 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
  39573. * to choose the wanted type.
  39574. * The parameter `size` (positive float, default 1) sets the polygon size.
  39575. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  39576. * 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`.
  39577. * 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
  39578. * 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)`).
  39579. * 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
  39580. * 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.
  39581. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39582. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39583. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39584. */
  39585. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  39586. var polyhedron = new BABYLON.Mesh(name, scene);
  39587. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39588. polyhedron.sideOrientation = options.sideOrientation;
  39589. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  39590. vertexData.applyToMesh(polyhedron, options.updatable);
  39591. return polyhedron;
  39592. };
  39593. /**
  39594. * Creates a decal mesh.
  39595. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  39596. * 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.
  39597. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  39598. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  39599. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  39600. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  39601. */
  39602. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  39603. var indices = sourceMesh.getIndices();
  39604. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39605. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39606. var position = options.position || BABYLON.Vector3.Zero();
  39607. var normal = options.normal || BABYLON.Vector3.Up();
  39608. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  39609. var angle = options.angle || 0;
  39610. // Getting correct rotation
  39611. if (!normal) {
  39612. var target = new BABYLON.Vector3(0, 0, 1);
  39613. var camera = sourceMesh.getScene().activeCamera;
  39614. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  39615. normal = camera.globalPosition.subtract(cameraWorldTarget);
  39616. }
  39617. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  39618. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  39619. var pitch = Math.atan2(normal.y, len);
  39620. // Matrix
  39621. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  39622. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  39623. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  39624. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  39625. var vertexData = new BABYLON.VertexData();
  39626. vertexData.indices = [];
  39627. vertexData.positions = [];
  39628. vertexData.normals = [];
  39629. vertexData.uvs = [];
  39630. var currentVertexDataIndex = 0;
  39631. var extractDecalVector3 = function (indexId) {
  39632. var vertexId = indices[indexId];
  39633. var result = new BABYLON.PositionNormalVertex();
  39634. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  39635. // Send vector to decal local world
  39636. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  39637. // Get normal
  39638. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  39639. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  39640. return result;
  39641. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  39642. var clip = function (vertices, axis) {
  39643. if (vertices.length === 0) {
  39644. return vertices;
  39645. }
  39646. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  39647. var clipVertices = function (v0, v1) {
  39648. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  39649. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  39650. };
  39651. var result = new Array();
  39652. for (var index = 0; index < vertices.length; index += 3) {
  39653. var v1Out;
  39654. var v2Out;
  39655. var v3Out;
  39656. var total = 0;
  39657. var nV1, nV2, nV3, nV4;
  39658. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  39659. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  39660. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  39661. v1Out = d1 > 0;
  39662. v2Out = d2 > 0;
  39663. v3Out = d3 > 0;
  39664. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  39665. switch (total) {
  39666. case 0:
  39667. result.push(vertices[index]);
  39668. result.push(vertices[index + 1]);
  39669. result.push(vertices[index + 2]);
  39670. break;
  39671. case 1:
  39672. if (v1Out) {
  39673. nV1 = vertices[index + 1];
  39674. nV2 = vertices[index + 2];
  39675. nV3 = clipVertices(vertices[index], nV1);
  39676. nV4 = clipVertices(vertices[index], nV2);
  39677. }
  39678. if (v2Out) {
  39679. nV1 = vertices[index];
  39680. nV2 = vertices[index + 2];
  39681. nV3 = clipVertices(vertices[index + 1], nV1);
  39682. nV4 = clipVertices(vertices[index + 1], nV2);
  39683. result.push(nV3);
  39684. result.push(nV2.clone());
  39685. result.push(nV1.clone());
  39686. result.push(nV2.clone());
  39687. result.push(nV3.clone());
  39688. result.push(nV4);
  39689. break;
  39690. }
  39691. if (v3Out) {
  39692. nV1 = vertices[index];
  39693. nV2 = vertices[index + 1];
  39694. nV3 = clipVertices(vertices[index + 2], nV1);
  39695. nV4 = clipVertices(vertices[index + 2], nV2);
  39696. }
  39697. result.push(nV1.clone());
  39698. result.push(nV2.clone());
  39699. result.push(nV3);
  39700. result.push(nV4);
  39701. result.push(nV3.clone());
  39702. result.push(nV2.clone());
  39703. break;
  39704. case 2:
  39705. if (!v1Out) {
  39706. nV1 = vertices[index].clone();
  39707. nV2 = clipVertices(nV1, vertices[index + 1]);
  39708. nV3 = clipVertices(nV1, vertices[index + 2]);
  39709. result.push(nV1);
  39710. result.push(nV2);
  39711. result.push(nV3);
  39712. }
  39713. if (!v2Out) {
  39714. nV1 = vertices[index + 1].clone();
  39715. nV2 = clipVertices(nV1, vertices[index + 2]);
  39716. nV3 = clipVertices(nV1, vertices[index]);
  39717. result.push(nV1);
  39718. result.push(nV2);
  39719. result.push(nV3);
  39720. }
  39721. if (!v3Out) {
  39722. nV1 = vertices[index + 2].clone();
  39723. nV2 = clipVertices(nV1, vertices[index]);
  39724. nV3 = clipVertices(nV1, vertices[index + 1]);
  39725. result.push(nV1);
  39726. result.push(nV2);
  39727. result.push(nV3);
  39728. }
  39729. break;
  39730. case 3:
  39731. break;
  39732. }
  39733. }
  39734. return result;
  39735. };
  39736. for (var index = 0; index < indices.length; index += 3) {
  39737. var faceVertices = new Array();
  39738. faceVertices.push(extractDecalVector3(index));
  39739. faceVertices.push(extractDecalVector3(index + 1));
  39740. faceVertices.push(extractDecalVector3(index + 2));
  39741. // Clip
  39742. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  39743. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  39744. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  39745. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  39746. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  39747. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  39748. if (faceVertices.length === 0) {
  39749. continue;
  39750. }
  39751. // Add UVs and get back to world
  39752. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  39753. var vertex = faceVertices[vIndex];
  39754. //TODO check for Int32Array | Uint32Array | Uint16Array
  39755. vertexData.indices.push(currentVertexDataIndex);
  39756. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  39757. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  39758. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  39759. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  39760. currentVertexDataIndex++;
  39761. }
  39762. }
  39763. // Return mesh
  39764. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  39765. vertexData.applyToMesh(decal);
  39766. decal.position = position.clone();
  39767. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  39768. return decal;
  39769. };
  39770. // Privates
  39771. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  39772. // extrusion geometry
  39773. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  39774. var tangents = path3D.getTangents();
  39775. var normals = path3D.getNormals();
  39776. var binormals = path3D.getBinormals();
  39777. var distances = path3D.getDistances();
  39778. var angle = 0;
  39779. var returnScale = function () { return scale; };
  39780. var returnRotation = function () { return rotation; };
  39781. var rotate = custom ? rotateFunction : returnRotation;
  39782. var scl = custom ? scaleFunction : returnScale;
  39783. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  39784. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  39785. for (var i = 0; i < curve.length; i++) {
  39786. var shapePath = new Array();
  39787. var angleStep = rotate(i, distances[i]);
  39788. var scaleRatio = scl(i, distances[i]);
  39789. for (var p = 0; p < shape.length; p++) {
  39790. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  39791. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  39792. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  39793. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  39794. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  39795. shapePath[p] = rotated;
  39796. }
  39797. shapePaths[index] = shapePath;
  39798. angle += angleStep;
  39799. index++;
  39800. }
  39801. // cap
  39802. var capPath = function (shapePath) {
  39803. var pointCap = Array();
  39804. var barycenter = BABYLON.Vector3.Zero();
  39805. var i;
  39806. for (i = 0; i < shapePath.length; i++) {
  39807. barycenter.addInPlace(shapePath[i]);
  39808. }
  39809. barycenter.scaleInPlace(1.0 / shapePath.length);
  39810. for (i = 0; i < shapePath.length; i++) {
  39811. pointCap.push(barycenter);
  39812. }
  39813. return pointCap;
  39814. };
  39815. switch (cap) {
  39816. case BABYLON.Mesh.NO_CAP:
  39817. break;
  39818. case BABYLON.Mesh.CAP_START:
  39819. shapePaths[0] = capPath(shapePaths[2]);
  39820. shapePaths[1] = shapePaths[2];
  39821. break;
  39822. case BABYLON.Mesh.CAP_END:
  39823. shapePaths[index] = shapePaths[index - 1];
  39824. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  39825. break;
  39826. case BABYLON.Mesh.CAP_ALL:
  39827. shapePaths[0] = capPath(shapePaths[2]);
  39828. shapePaths[1] = shapePaths[2];
  39829. shapePaths[index] = shapePaths[index - 1];
  39830. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  39831. break;
  39832. default:
  39833. break;
  39834. }
  39835. return shapePaths;
  39836. };
  39837. var path3D;
  39838. var pathArray;
  39839. if (instance) {
  39840. path3D = (instance.path3D).update(curve);
  39841. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  39842. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  39843. return instance;
  39844. }
  39845. // extruded shape creation
  39846. path3D = new BABYLON.Path3D(curve);
  39847. var newShapePaths = new Array();
  39848. cap = (cap < 0 || cap > 3) ? 0 : cap;
  39849. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  39850. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  39851. extrudedGeneric.pathArray = pathArray;
  39852. extrudedGeneric.path3D = path3D;
  39853. extrudedGeneric.cap = cap;
  39854. return extrudedGeneric;
  39855. };
  39856. return MeshBuilder;
  39857. }());
  39858. BABYLON.MeshBuilder = MeshBuilder;
  39859. })(BABYLON || (BABYLON = {}));
  39860. //# sourceMappingURL=babylon.meshBuilder.js.map
  39861. var BABYLON;
  39862. (function (BABYLON) {
  39863. var AudioEngine = (function () {
  39864. function AudioEngine() {
  39865. this._audioContext = null;
  39866. this._audioContextInitialized = false;
  39867. this.canUseWebAudio = false;
  39868. this.WarnedWebAudioUnsupported = false;
  39869. this.unlocked = false;
  39870. this.isMP3supported = false;
  39871. this.isOGGsupported = false;
  39872. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  39873. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  39874. this.canUseWebAudio = true;
  39875. }
  39876. var audioElem = document.createElement('audio');
  39877. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  39878. this.isMP3supported = true;
  39879. }
  39880. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  39881. this.isOGGsupported = true;
  39882. }
  39883. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  39884. this._unlockiOSaudio();
  39885. }
  39886. else {
  39887. this.unlocked = true;
  39888. }
  39889. }
  39890. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  39891. get: function () {
  39892. if (!this._audioContextInitialized) {
  39893. this._initializeAudioContext();
  39894. }
  39895. return this._audioContext;
  39896. },
  39897. enumerable: true,
  39898. configurable: true
  39899. });
  39900. AudioEngine.prototype._unlockiOSaudio = function () {
  39901. var _this = this;
  39902. var unlockaudio = function () {
  39903. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  39904. var source = _this.audioContext.createBufferSource();
  39905. source.buffer = buffer;
  39906. source.connect(_this.audioContext.destination);
  39907. source.start(0);
  39908. setTimeout(function () {
  39909. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  39910. _this.unlocked = true;
  39911. window.removeEventListener('touchend', unlockaudio, false);
  39912. if (_this.onAudioUnlocked) {
  39913. _this.onAudioUnlocked();
  39914. }
  39915. }
  39916. }, 0);
  39917. };
  39918. window.addEventListener('touchend', unlockaudio, false);
  39919. };
  39920. AudioEngine.prototype._initializeAudioContext = function () {
  39921. try {
  39922. if (this.canUseWebAudio) {
  39923. this._audioContext = new AudioContext();
  39924. // create a global volume gain node
  39925. this.masterGain = this._audioContext.createGain();
  39926. this.masterGain.gain.value = 1;
  39927. this.masterGain.connect(this._audioContext.destination);
  39928. this._audioContextInitialized = true;
  39929. }
  39930. }
  39931. catch (e) {
  39932. this.canUseWebAudio = false;
  39933. BABYLON.Tools.Error("Web Audio: " + e.message);
  39934. }
  39935. };
  39936. AudioEngine.prototype.dispose = function () {
  39937. if (this.canUseWebAudio && this._audioContextInitialized) {
  39938. if (this._connectedAnalyser) {
  39939. this._connectedAnalyser.stopDebugCanvas();
  39940. this._connectedAnalyser.dispose();
  39941. this.masterGain.disconnect();
  39942. this.masterGain.connect(this._audioContext.destination);
  39943. this._connectedAnalyser = null;
  39944. }
  39945. this.masterGain.gain.value = 1;
  39946. }
  39947. this.WarnedWebAudioUnsupported = false;
  39948. };
  39949. AudioEngine.prototype.getGlobalVolume = function () {
  39950. if (this.canUseWebAudio && this._audioContextInitialized) {
  39951. return this.masterGain.gain.value;
  39952. }
  39953. else {
  39954. return -1;
  39955. }
  39956. };
  39957. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  39958. if (this.canUseWebAudio && this._audioContextInitialized) {
  39959. this.masterGain.gain.value = newVolume;
  39960. }
  39961. };
  39962. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  39963. if (this._connectedAnalyser) {
  39964. this._connectedAnalyser.stopDebugCanvas();
  39965. }
  39966. if (this.canUseWebAudio && this._audioContextInitialized) {
  39967. this._connectedAnalyser = analyser;
  39968. this.masterGain.disconnect();
  39969. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  39970. }
  39971. };
  39972. return AudioEngine;
  39973. }());
  39974. BABYLON.AudioEngine = AudioEngine;
  39975. })(BABYLON || (BABYLON = {}));
  39976. //# sourceMappingURL=babylon.audioEngine.js.map
  39977. var BABYLON;
  39978. (function (BABYLON) {
  39979. var Sound = (function () {
  39980. /**
  39981. * Create a sound and attach it to a scene
  39982. * @param name Name of your sound
  39983. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  39984. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  39985. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  39986. */
  39987. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  39988. var _this = this;
  39989. this.autoplay = false;
  39990. this.loop = false;
  39991. this.useCustomAttenuation = false;
  39992. this.spatialSound = false;
  39993. this.refDistance = 1;
  39994. this.rolloffFactor = 1;
  39995. this.maxDistance = 100;
  39996. this.distanceModel = "linear";
  39997. this._panningModel = "equalpower";
  39998. this._playbackRate = 1;
  39999. this._streaming = false;
  40000. this._startTime = 0;
  40001. this._startOffset = 0;
  40002. this._position = BABYLON.Vector3.Zero();
  40003. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  40004. this._volume = 1;
  40005. this._isLoaded = false;
  40006. this._isReadyToPlay = false;
  40007. this.isPlaying = false;
  40008. this.isPaused = false;
  40009. this._isDirectional = false;
  40010. // Used if you'd like to create a directional sound.
  40011. // If not set, the sound will be omnidirectional
  40012. this._coneInnerAngle = 360;
  40013. this._coneOuterAngle = 360;
  40014. this._coneOuterGain = 0;
  40015. this._isOutputConnected = false;
  40016. this._urlType = "Unknown";
  40017. this.name = name;
  40018. this._scene = scene;
  40019. this._readyToPlayCallback = readyToPlayCallback;
  40020. // Default custom attenuation function is a linear attenuation
  40021. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  40022. if (currentDistance < maxDistance) {
  40023. return currentVolume * (1 - currentDistance / maxDistance);
  40024. }
  40025. else {
  40026. return 0;
  40027. }
  40028. };
  40029. if (options) {
  40030. this.autoplay = options.autoplay || false;
  40031. this.loop = options.loop || false;
  40032. // if volume === 0, we need another way to check this option
  40033. if (options.volume !== undefined) {
  40034. this._volume = options.volume;
  40035. }
  40036. this.spatialSound = options.spatialSound || false;
  40037. this.maxDistance = options.maxDistance || 100;
  40038. this.useCustomAttenuation = options.useCustomAttenuation || false;
  40039. this.rolloffFactor = options.rolloffFactor || 1;
  40040. this.refDistance = options.refDistance || 1;
  40041. this.distanceModel = options.distanceModel || "linear";
  40042. this._playbackRate = options.playbackRate || 1;
  40043. this._streaming = options.streaming || false;
  40044. }
  40045. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40046. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  40047. this._soundGain.gain.value = this._volume;
  40048. this._inputAudioNode = this._soundGain;
  40049. this._ouputAudioNode = this._soundGain;
  40050. if (this.spatialSound) {
  40051. this._createSpatialParameters();
  40052. }
  40053. this._scene.mainSoundTrack.AddSound(this);
  40054. var validParameter = true;
  40055. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  40056. if (urlOrArrayBuffer) {
  40057. if (typeof (urlOrArrayBuffer) === "string")
  40058. this._urlType = "String";
  40059. if (Array.isArray(urlOrArrayBuffer))
  40060. this._urlType = "Array";
  40061. if (urlOrArrayBuffer instanceof ArrayBuffer)
  40062. this._urlType = "ArrayBuffer";
  40063. var urls = [];
  40064. var codecSupportedFound = false;
  40065. switch (this._urlType) {
  40066. case "ArrayBuffer":
  40067. if (urlOrArrayBuffer.byteLength > 0) {
  40068. codecSupportedFound = true;
  40069. this._soundLoaded(urlOrArrayBuffer);
  40070. }
  40071. break;
  40072. case "String":
  40073. urls.push(urlOrArrayBuffer);
  40074. case "Array":
  40075. if (urls.length === 0)
  40076. urls = urlOrArrayBuffer;
  40077. // If we found a supported format, we load it immediately and stop the loop
  40078. for (var i = 0; i < urls.length; i++) {
  40079. var url = urls[i];
  40080. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  40081. codecSupportedFound = true;
  40082. }
  40083. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  40084. codecSupportedFound = true;
  40085. }
  40086. if (url.indexOf(".wav", url.length - 4) !== -1) {
  40087. codecSupportedFound = true;
  40088. }
  40089. if (codecSupportedFound) {
  40090. // Loading sound using XHR2
  40091. if (!this._streaming) {
  40092. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  40093. }
  40094. else {
  40095. this._htmlAudioElement = new Audio(url);
  40096. this._htmlAudioElement.controls = false;
  40097. this._htmlAudioElement.loop = this.loop;
  40098. this._htmlAudioElement.crossOrigin = "anonymous";
  40099. this._htmlAudioElement.preload = "auto";
  40100. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  40101. _this._isReadyToPlay = true;
  40102. if (_this.autoplay) {
  40103. _this.play();
  40104. }
  40105. if (_this._readyToPlayCallback) {
  40106. _this._readyToPlayCallback();
  40107. }
  40108. });
  40109. document.body.appendChild(this._htmlAudioElement);
  40110. }
  40111. break;
  40112. }
  40113. }
  40114. break;
  40115. default:
  40116. validParameter = false;
  40117. break;
  40118. }
  40119. if (!validParameter) {
  40120. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  40121. }
  40122. else {
  40123. if (!codecSupportedFound) {
  40124. this._isReadyToPlay = true;
  40125. // Simulating a ready to play event to avoid breaking code path
  40126. if (this._readyToPlayCallback) {
  40127. window.setTimeout(function () {
  40128. _this._readyToPlayCallback();
  40129. }, 1000);
  40130. }
  40131. }
  40132. }
  40133. }
  40134. }
  40135. else {
  40136. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  40137. this._scene.mainSoundTrack.AddSound(this);
  40138. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  40139. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  40140. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  40141. }
  40142. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  40143. if (this._readyToPlayCallback) {
  40144. window.setTimeout(function () {
  40145. _this._readyToPlayCallback();
  40146. }, 1000);
  40147. }
  40148. }
  40149. }
  40150. Sound.prototype.dispose = function () {
  40151. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  40152. if (this.isPlaying) {
  40153. this.stop();
  40154. }
  40155. this._isReadyToPlay = false;
  40156. if (this.soundTrackId === -1) {
  40157. this._scene.mainSoundTrack.RemoveSound(this);
  40158. }
  40159. else {
  40160. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  40161. }
  40162. if (this._soundGain) {
  40163. this._soundGain.disconnect();
  40164. this._soundGain = null;
  40165. }
  40166. if (this._soundPanner) {
  40167. this._soundPanner.disconnect();
  40168. this._soundPanner = null;
  40169. }
  40170. if (this._soundSource) {
  40171. this._soundSource.disconnect();
  40172. this._soundSource = null;
  40173. }
  40174. this._audioBuffer = null;
  40175. if (this._htmlAudioElement) {
  40176. this._htmlAudioElement.pause();
  40177. this._htmlAudioElement.src = "";
  40178. document.body.removeChild(this._htmlAudioElement);
  40179. }
  40180. if (this._connectedMesh) {
  40181. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  40182. this._connectedMesh = null;
  40183. }
  40184. }
  40185. };
  40186. Sound.prototype.isReady = function () {
  40187. return this._isReadyToPlay;
  40188. };
  40189. Sound.prototype._soundLoaded = function (audioData) {
  40190. var _this = this;
  40191. this._isLoaded = true;
  40192. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  40193. _this._audioBuffer = buffer;
  40194. _this._isReadyToPlay = true;
  40195. if (_this.autoplay) {
  40196. _this.play();
  40197. }
  40198. if (_this._readyToPlayCallback) {
  40199. _this._readyToPlayCallback();
  40200. }
  40201. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  40202. };
  40203. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  40204. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40205. this._audioBuffer = audioBuffer;
  40206. this._isReadyToPlay = true;
  40207. }
  40208. };
  40209. Sound.prototype.updateOptions = function (options) {
  40210. if (options) {
  40211. this.loop = options.loop || this.loop;
  40212. this.maxDistance = options.maxDistance || this.maxDistance;
  40213. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  40214. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  40215. this.refDistance = options.refDistance || this.refDistance;
  40216. this.distanceModel = options.distanceModel || this.distanceModel;
  40217. this._playbackRate = options.playbackRate || this._playbackRate;
  40218. this._updateSpatialParameters();
  40219. if (this.isPlaying) {
  40220. if (this._streaming) {
  40221. this._htmlAudioElement.playbackRate = this._playbackRate;
  40222. }
  40223. else {
  40224. this._soundSource.playbackRate.value = this._playbackRate;
  40225. }
  40226. }
  40227. }
  40228. };
  40229. Sound.prototype._createSpatialParameters = function () {
  40230. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40231. if (this._scene.headphone) {
  40232. this._panningModel = "HRTF";
  40233. }
  40234. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  40235. this._updateSpatialParameters();
  40236. this._soundPanner.connect(this._ouputAudioNode);
  40237. this._inputAudioNode = this._soundPanner;
  40238. }
  40239. };
  40240. Sound.prototype._updateSpatialParameters = function () {
  40241. if (this.spatialSound) {
  40242. if (this.useCustomAttenuation) {
  40243. // Tricks to disable in a way embedded Web Audio attenuation
  40244. this._soundPanner.distanceModel = "linear";
  40245. this._soundPanner.maxDistance = Number.MAX_VALUE;
  40246. this._soundPanner.refDistance = 1;
  40247. this._soundPanner.rolloffFactor = 1;
  40248. this._soundPanner.panningModel = this._panningModel;
  40249. }
  40250. else {
  40251. this._soundPanner.distanceModel = this.distanceModel;
  40252. this._soundPanner.maxDistance = this.maxDistance;
  40253. this._soundPanner.refDistance = this.refDistance;
  40254. this._soundPanner.rolloffFactor = this.rolloffFactor;
  40255. this._soundPanner.panningModel = this._panningModel;
  40256. }
  40257. }
  40258. };
  40259. Sound.prototype.switchPanningModelToHRTF = function () {
  40260. this._panningModel = "HRTF";
  40261. this._switchPanningModel();
  40262. };
  40263. Sound.prototype.switchPanningModelToEqualPower = function () {
  40264. this._panningModel = "equalpower";
  40265. this._switchPanningModel();
  40266. };
  40267. Sound.prototype._switchPanningModel = function () {
  40268. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  40269. this._soundPanner.panningModel = this._panningModel;
  40270. }
  40271. };
  40272. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  40273. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40274. if (this._isOutputConnected) {
  40275. this._ouputAudioNode.disconnect();
  40276. }
  40277. this._ouputAudioNode.connect(soundTrackAudioNode);
  40278. this._isOutputConnected = true;
  40279. }
  40280. };
  40281. /**
  40282. * Transform this sound into a directional source
  40283. * @param coneInnerAngle Size of the inner cone in degree
  40284. * @param coneOuterAngle Size of the outer cone in degree
  40285. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  40286. */
  40287. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  40288. if (coneOuterAngle < coneInnerAngle) {
  40289. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  40290. return;
  40291. }
  40292. this._coneInnerAngle = coneInnerAngle;
  40293. this._coneOuterAngle = coneOuterAngle;
  40294. this._coneOuterGain = coneOuterGain;
  40295. this._isDirectional = true;
  40296. if (this.isPlaying && this.loop) {
  40297. this.stop();
  40298. this.play();
  40299. }
  40300. };
  40301. Sound.prototype.setPosition = function (newPosition) {
  40302. this._position = newPosition;
  40303. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  40304. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  40305. }
  40306. };
  40307. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  40308. this._localDirection = newLocalDirection;
  40309. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  40310. this._updateDirection();
  40311. }
  40312. };
  40313. Sound.prototype._updateDirection = function () {
  40314. var mat = this._connectedMesh.getWorldMatrix();
  40315. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  40316. direction.normalize();
  40317. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  40318. };
  40319. Sound.prototype.updateDistanceFromListener = function () {
  40320. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  40321. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  40322. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  40323. }
  40324. };
  40325. Sound.prototype.setAttenuationFunction = function (callback) {
  40326. this._customAttenuationFunction = callback;
  40327. };
  40328. /**
  40329. * Play the sound
  40330. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  40331. * @param offset (optional) Start the sound setting it at a specific time
  40332. */
  40333. Sound.prototype.play = function (time, offset) {
  40334. var _this = this;
  40335. if (this._isReadyToPlay && this._scene.audioEnabled) {
  40336. try {
  40337. if (this._startOffset < 0) {
  40338. time = -this._startOffset;
  40339. this._startOffset = 0;
  40340. }
  40341. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  40342. if (!this._soundSource || !this._streamingSource) {
  40343. if (this.spatialSound) {
  40344. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  40345. if (this._isDirectional) {
  40346. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  40347. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  40348. this._soundPanner.coneOuterGain = this._coneOuterGain;
  40349. if (this._connectedMesh) {
  40350. this._updateDirection();
  40351. }
  40352. else {
  40353. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  40354. }
  40355. }
  40356. }
  40357. }
  40358. if (this._streaming) {
  40359. if (!this._streamingSource) {
  40360. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  40361. this._htmlAudioElement.onended = function () { _this._onended(); };
  40362. this._htmlAudioElement.playbackRate = this._playbackRate;
  40363. }
  40364. this._streamingSource.disconnect();
  40365. this._streamingSource.connect(this._inputAudioNode);
  40366. this._htmlAudioElement.play();
  40367. }
  40368. else {
  40369. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  40370. this._soundSource.buffer = this._audioBuffer;
  40371. this._soundSource.connect(this._inputAudioNode);
  40372. this._soundSource.loop = this.loop;
  40373. this._soundSource.playbackRate.value = this._playbackRate;
  40374. this._soundSource.onended = function () { _this._onended(); };
  40375. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  40376. }
  40377. this._startTime = startTime;
  40378. this.isPlaying = true;
  40379. this.isPaused = false;
  40380. }
  40381. catch (ex) {
  40382. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  40383. }
  40384. }
  40385. };
  40386. Sound.prototype._onended = function () {
  40387. this.isPlaying = false;
  40388. if (this.onended) {
  40389. this.onended();
  40390. }
  40391. };
  40392. /**
  40393. * Stop the sound
  40394. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  40395. */
  40396. Sound.prototype.stop = function (time) {
  40397. if (this.isPlaying) {
  40398. if (this._streaming) {
  40399. this._htmlAudioElement.pause();
  40400. // Test needed for Firefox or it will generate an Invalid State Error
  40401. if (this._htmlAudioElement.currentTime > 0) {
  40402. this._htmlAudioElement.currentTime = 0;
  40403. }
  40404. }
  40405. else {
  40406. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  40407. this._soundSource.stop(stopTime);
  40408. this._soundSource.onended = null;
  40409. if (!this.isPaused) {
  40410. this._startOffset = 0;
  40411. }
  40412. }
  40413. this.isPlaying = false;
  40414. }
  40415. };
  40416. Sound.prototype.pause = function () {
  40417. if (this.isPlaying) {
  40418. this.isPaused = true;
  40419. if (this._streaming) {
  40420. this._htmlAudioElement.pause();
  40421. }
  40422. else {
  40423. this.stop(0);
  40424. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  40425. }
  40426. }
  40427. };
  40428. Sound.prototype.setVolume = function (newVolume, time) {
  40429. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40430. if (time) {
  40431. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  40432. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  40433. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  40434. }
  40435. else {
  40436. this._soundGain.gain.value = newVolume;
  40437. }
  40438. }
  40439. this._volume = newVolume;
  40440. };
  40441. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  40442. this._playbackRate = newPlaybackRate;
  40443. if (this.isPlaying) {
  40444. if (this._streaming) {
  40445. this._htmlAudioElement.playbackRate = this._playbackRate;
  40446. }
  40447. else {
  40448. this._soundSource.playbackRate.value = this._playbackRate;
  40449. }
  40450. }
  40451. };
  40452. Sound.prototype.getVolume = function () {
  40453. return this._volume;
  40454. };
  40455. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  40456. var _this = this;
  40457. if (this._connectedMesh) {
  40458. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  40459. this._registerFunc = null;
  40460. }
  40461. this._connectedMesh = meshToConnectTo;
  40462. if (!this.spatialSound) {
  40463. this.spatialSound = true;
  40464. this._createSpatialParameters();
  40465. if (this.isPlaying && this.loop) {
  40466. this.stop();
  40467. this.play();
  40468. }
  40469. }
  40470. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  40471. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  40472. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  40473. };
  40474. Sound.prototype.detachFromMesh = function () {
  40475. if (this._connectedMesh) {
  40476. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  40477. this._registerFunc = null;
  40478. this._connectedMesh = null;
  40479. }
  40480. };
  40481. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  40482. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  40483. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  40484. this._updateDirection();
  40485. }
  40486. };
  40487. Sound.prototype.clone = function () {
  40488. var _this = this;
  40489. if (!this._streaming) {
  40490. var setBufferAndRun = function () {
  40491. if (_this._isReadyToPlay) {
  40492. clonedSound._audioBuffer = _this.getAudioBuffer();
  40493. clonedSound._isReadyToPlay = true;
  40494. if (clonedSound.autoplay) {
  40495. clonedSound.play();
  40496. }
  40497. }
  40498. else {
  40499. window.setTimeout(setBufferAndRun, 300);
  40500. }
  40501. };
  40502. var currentOptions = {
  40503. autoplay: this.autoplay, loop: this.loop,
  40504. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  40505. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  40506. refDistance: this.refDistance, distanceModel: this.distanceModel
  40507. };
  40508. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  40509. if (this.useCustomAttenuation) {
  40510. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  40511. }
  40512. clonedSound.setPosition(this._position);
  40513. clonedSound.setPlaybackRate(this._playbackRate);
  40514. setBufferAndRun();
  40515. return clonedSound;
  40516. }
  40517. else {
  40518. return null;
  40519. }
  40520. };
  40521. Sound.prototype.getAudioBuffer = function () {
  40522. return this._audioBuffer;
  40523. };
  40524. Sound.prototype.serialize = function () {
  40525. var serializationObject = {
  40526. name: this.name,
  40527. url: this.name,
  40528. autoplay: this.autoplay,
  40529. loop: this.loop,
  40530. volume: this._volume,
  40531. spatialSound: this.spatialSound,
  40532. maxDistance: this.maxDistance,
  40533. rolloffFactor: this.rolloffFactor,
  40534. refDistance: this.refDistance,
  40535. distanceModel: this.distanceModel,
  40536. playbackRate: this._playbackRate,
  40537. panningModel: this._panningModel,
  40538. soundTrackId: this.soundTrackId
  40539. };
  40540. if (this.spatialSound) {
  40541. if (this._connectedMesh)
  40542. serializationObject.connectedMeshId = this._connectedMesh.id;
  40543. serializationObject.position = this._position.asArray();
  40544. serializationObject.refDistance = this.refDistance;
  40545. serializationObject.distanceModel = this.distanceModel;
  40546. serializationObject.isDirectional = this._isDirectional;
  40547. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  40548. serializationObject.coneInnerAngle = this._coneInnerAngle;
  40549. serializationObject.coneOuterAngle = this._coneOuterAngle;
  40550. serializationObject.coneOuterGain = this._coneOuterGain;
  40551. }
  40552. return serializationObject;
  40553. };
  40554. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  40555. var soundName = parsedSound.name;
  40556. var soundUrl;
  40557. if (parsedSound.url) {
  40558. soundUrl = rootUrl + parsedSound.url;
  40559. }
  40560. else {
  40561. soundUrl = rootUrl + soundName;
  40562. }
  40563. var options = {
  40564. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  40565. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  40566. rolloffFactor: parsedSound.rolloffFactor,
  40567. refDistance: parsedSound.refDistance,
  40568. distanceModel: parsedSound.distanceModel,
  40569. playbackRate: parsedSound.playbackRate
  40570. };
  40571. var newSound;
  40572. if (!sourceSound) {
  40573. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  40574. scene._addPendingData(newSound);
  40575. }
  40576. else {
  40577. var setBufferAndRun = function () {
  40578. if (sourceSound._isReadyToPlay) {
  40579. newSound._audioBuffer = sourceSound.getAudioBuffer();
  40580. newSound._isReadyToPlay = true;
  40581. if (newSound.autoplay) {
  40582. newSound.play();
  40583. }
  40584. }
  40585. else {
  40586. window.setTimeout(setBufferAndRun, 300);
  40587. }
  40588. };
  40589. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  40590. setBufferAndRun();
  40591. }
  40592. if (parsedSound.position) {
  40593. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  40594. newSound.setPosition(soundPosition);
  40595. }
  40596. if (parsedSound.isDirectional) {
  40597. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  40598. if (parsedSound.localDirectionToMesh) {
  40599. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  40600. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  40601. }
  40602. }
  40603. if (parsedSound.connectedMeshId) {
  40604. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  40605. if (connectedMesh) {
  40606. newSound.attachToMesh(connectedMesh);
  40607. }
  40608. }
  40609. return newSound;
  40610. };
  40611. return Sound;
  40612. }());
  40613. BABYLON.Sound = Sound;
  40614. })(BABYLON || (BABYLON = {}));
  40615. //# sourceMappingURL=babylon.sound.js.map
  40616. var BABYLON;
  40617. (function (BABYLON) {
  40618. var SoundTrack = (function () {
  40619. function SoundTrack(scene, options) {
  40620. this.id = -1;
  40621. this._isMainTrack = false;
  40622. this._isInitialized = false;
  40623. this._scene = scene;
  40624. this.soundCollection = new Array();
  40625. this._options = options;
  40626. if (!this._isMainTrack) {
  40627. this._scene.soundTracks.push(this);
  40628. this.id = this._scene.soundTracks.length - 1;
  40629. }
  40630. }
  40631. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  40632. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40633. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  40634. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  40635. if (this._options) {
  40636. if (this._options.volume) {
  40637. this._outputAudioNode.gain.value = this._options.volume;
  40638. }
  40639. if (this._options.mainTrack) {
  40640. this._isMainTrack = this._options.mainTrack;
  40641. }
  40642. }
  40643. this._isInitialized = true;
  40644. }
  40645. };
  40646. SoundTrack.prototype.dispose = function () {
  40647. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40648. if (this._connectedAnalyser) {
  40649. this._connectedAnalyser.stopDebugCanvas();
  40650. }
  40651. while (this.soundCollection.length) {
  40652. this.soundCollection[0].dispose();
  40653. }
  40654. if (this._outputAudioNode) {
  40655. this._outputAudioNode.disconnect();
  40656. }
  40657. this._outputAudioNode = null;
  40658. }
  40659. };
  40660. SoundTrack.prototype.AddSound = function (sound) {
  40661. if (!this._isInitialized) {
  40662. this._initializeSoundTrackAudioGraph();
  40663. }
  40664. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40665. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  40666. }
  40667. if (sound.soundTrackId) {
  40668. if (sound.soundTrackId === -1) {
  40669. this._scene.mainSoundTrack.RemoveSound(sound);
  40670. }
  40671. else {
  40672. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  40673. }
  40674. }
  40675. this.soundCollection.push(sound);
  40676. sound.soundTrackId = this.id;
  40677. };
  40678. SoundTrack.prototype.RemoveSound = function (sound) {
  40679. var index = this.soundCollection.indexOf(sound);
  40680. if (index !== -1) {
  40681. this.soundCollection.splice(index, 1);
  40682. }
  40683. };
  40684. SoundTrack.prototype.setVolume = function (newVolume) {
  40685. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40686. this._outputAudioNode.gain.value = newVolume;
  40687. }
  40688. };
  40689. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  40690. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40691. for (var i = 0; i < this.soundCollection.length; i++) {
  40692. this.soundCollection[i].switchPanningModelToHRTF();
  40693. }
  40694. }
  40695. };
  40696. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  40697. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40698. for (var i = 0; i < this.soundCollection.length; i++) {
  40699. this.soundCollection[i].switchPanningModelToEqualPower();
  40700. }
  40701. }
  40702. };
  40703. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  40704. if (this._connectedAnalyser) {
  40705. this._connectedAnalyser.stopDebugCanvas();
  40706. }
  40707. this._connectedAnalyser = analyser;
  40708. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40709. this._outputAudioNode.disconnect();
  40710. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  40711. }
  40712. };
  40713. return SoundTrack;
  40714. }());
  40715. BABYLON.SoundTrack = SoundTrack;
  40716. })(BABYLON || (BABYLON = {}));
  40717. //# sourceMappingURL=babylon.soundtrack.js.map
  40718. var BABYLON;
  40719. (function (BABYLON) {
  40720. var Analyser = (function () {
  40721. function Analyser(scene) {
  40722. this.SMOOTHING = 0.75;
  40723. this.FFT_SIZE = 512;
  40724. this.BARGRAPHAMPLITUDE = 256;
  40725. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  40726. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  40727. this._scene = scene;
  40728. this._audioEngine = BABYLON.Engine.audioEngine;
  40729. if (this._audioEngine.canUseWebAudio) {
  40730. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  40731. this._webAudioAnalyser.minDecibels = -140;
  40732. this._webAudioAnalyser.maxDecibels = 0;
  40733. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  40734. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  40735. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  40736. }
  40737. }
  40738. Analyser.prototype.getFrequencyBinCount = function () {
  40739. if (this._audioEngine.canUseWebAudio) {
  40740. return this._webAudioAnalyser.frequencyBinCount;
  40741. }
  40742. else {
  40743. return 0;
  40744. }
  40745. };
  40746. Analyser.prototype.getByteFrequencyData = function () {
  40747. if (this._audioEngine.canUseWebAudio) {
  40748. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  40749. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  40750. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  40751. }
  40752. return this._byteFreqs;
  40753. };
  40754. Analyser.prototype.getByteTimeDomainData = function () {
  40755. if (this._audioEngine.canUseWebAudio) {
  40756. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  40757. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  40758. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  40759. }
  40760. return this._byteTime;
  40761. };
  40762. Analyser.prototype.getFloatFrequencyData = function () {
  40763. if (this._audioEngine.canUseWebAudio) {
  40764. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  40765. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  40766. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  40767. }
  40768. return this._floatFreqs;
  40769. };
  40770. Analyser.prototype.drawDebugCanvas = function () {
  40771. var _this = this;
  40772. if (this._audioEngine.canUseWebAudio) {
  40773. if (!this._debugCanvas) {
  40774. this._debugCanvas = document.createElement("canvas");
  40775. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  40776. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  40777. this._debugCanvas.style.position = "absolute";
  40778. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  40779. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  40780. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  40781. document.body.appendChild(this._debugCanvas);
  40782. this._registerFunc = function () {
  40783. _this.drawDebugCanvas();
  40784. };
  40785. this._scene.registerBeforeRender(this._registerFunc);
  40786. }
  40787. if (this._registerFunc) {
  40788. var workingArray = this.getByteFrequencyData();
  40789. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  40790. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  40791. // Draw the frequency domain chart.
  40792. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  40793. var value = workingArray[i];
  40794. var percent = value / this.BARGRAPHAMPLITUDE;
  40795. var height = this.DEBUGCANVASSIZE.height * percent;
  40796. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  40797. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  40798. var hue = i / this.getFrequencyBinCount() * 360;
  40799. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  40800. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  40801. }
  40802. }
  40803. }
  40804. };
  40805. Analyser.prototype.stopDebugCanvas = function () {
  40806. if (this._debugCanvas) {
  40807. this._scene.unregisterBeforeRender(this._registerFunc);
  40808. this._registerFunc = null;
  40809. document.body.removeChild(this._debugCanvas);
  40810. this._debugCanvas = null;
  40811. this._debugCanvasContext = null;
  40812. }
  40813. };
  40814. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  40815. if (this._audioEngine.canUseWebAudio) {
  40816. inputAudioNode.connect(this._webAudioAnalyser);
  40817. this._webAudioAnalyser.connect(outputAudioNode);
  40818. }
  40819. };
  40820. Analyser.prototype.dispose = function () {
  40821. if (this._audioEngine.canUseWebAudio) {
  40822. this._webAudioAnalyser.disconnect();
  40823. }
  40824. };
  40825. return Analyser;
  40826. }());
  40827. BABYLON.Analyser = Analyser;
  40828. })(BABYLON || (BABYLON = {}));
  40829. //# sourceMappingURL=babylon.analyser.js.map
  40830. var BABYLON;
  40831. (function (BABYLON) {
  40832. var CubeTexture = (function (_super) {
  40833. __extends(CubeTexture, _super);
  40834. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  40835. if (onLoad === void 0) { onLoad = null; }
  40836. if (onError === void 0) { onError = null; }
  40837. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  40838. var _this = _super.call(this, scene) || this;
  40839. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  40840. _this.name = rootUrl;
  40841. _this.url = rootUrl;
  40842. _this._noMipmap = noMipmap;
  40843. _this.hasAlpha = false;
  40844. _this._format = format;
  40845. if (!rootUrl && !files) {
  40846. return _this;
  40847. }
  40848. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  40849. if (!files) {
  40850. if (!extensions) {
  40851. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  40852. }
  40853. files = [];
  40854. for (var index = 0; index < extensions.length; index++) {
  40855. files.push(rootUrl + extensions[index]);
  40856. }
  40857. _this._extensions = extensions;
  40858. }
  40859. _this._files = files;
  40860. if (!_this._texture) {
  40861. if (!scene.useDelayedTextureLoading) {
  40862. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  40863. }
  40864. else {
  40865. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40866. }
  40867. }
  40868. else if (onLoad) {
  40869. if (_this._texture.isReady) {
  40870. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  40871. }
  40872. else {
  40873. _this._texture.onLoadedCallbacks.push(onLoad);
  40874. }
  40875. }
  40876. _this.isCube = true;
  40877. _this._textureMatrix = BABYLON.Matrix.Identity();
  40878. return _this;
  40879. }
  40880. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  40881. return new CubeTexture("", scene, null, noMipmap, files);
  40882. };
  40883. // Methods
  40884. CubeTexture.prototype.delayLoad = function () {
  40885. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  40886. return;
  40887. }
  40888. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40889. this._texture = this._getFromCache(this.url, this._noMipmap);
  40890. if (!this._texture) {
  40891. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  40892. }
  40893. };
  40894. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  40895. return this._textureMatrix;
  40896. };
  40897. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  40898. var texture = BABYLON.SerializationHelper.Parse(function () {
  40899. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  40900. }, parsedTexture, scene);
  40901. // Animations
  40902. if (parsedTexture.animations) {
  40903. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  40904. var parsedAnimation = parsedTexture.animations[animationIndex];
  40905. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  40906. }
  40907. }
  40908. return texture;
  40909. };
  40910. CubeTexture.prototype.clone = function () {
  40911. var _this = this;
  40912. return BABYLON.SerializationHelper.Clone(function () {
  40913. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  40914. }, this);
  40915. };
  40916. return CubeTexture;
  40917. }(BABYLON.BaseTexture));
  40918. BABYLON.CubeTexture = CubeTexture;
  40919. })(BABYLON || (BABYLON = {}));
  40920. //# sourceMappingURL=babylon.cubeTexture.js.map
  40921. var BABYLON;
  40922. (function (BABYLON) {
  40923. var RenderTargetTexture = (function (_super) {
  40924. __extends(RenderTargetTexture, _super);
  40925. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  40926. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  40927. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40928. if (isCube === void 0) { isCube = false; }
  40929. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40930. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  40931. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  40932. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  40933. _this.isCube = isCube;
  40934. /**
  40935. * Use this list to define the list of mesh you want to render.
  40936. */
  40937. _this.renderList = new Array();
  40938. _this.renderParticles = true;
  40939. _this.renderSprites = false;
  40940. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  40941. // Events
  40942. /**
  40943. * An event triggered when the texture is unbind.
  40944. * @type {BABYLON.Observable}
  40945. */
  40946. _this.onAfterUnbindObservable = new BABYLON.Observable();
  40947. /**
  40948. * An event triggered before rendering the texture
  40949. * @type {BABYLON.Observable}
  40950. */
  40951. _this.onBeforeRenderObservable = new BABYLON.Observable();
  40952. /**
  40953. * An event triggered after rendering the texture
  40954. * @type {BABYLON.Observable}
  40955. */
  40956. _this.onAfterRenderObservable = new BABYLON.Observable();
  40957. /**
  40958. * An event triggered after the texture clear
  40959. * @type {BABYLON.Observable}
  40960. */
  40961. _this.onClearObservable = new BABYLON.Observable();
  40962. _this._currentRefreshId = -1;
  40963. _this._refreshRate = 1;
  40964. _this._samples = 1;
  40965. _this.name = name;
  40966. _this.isRenderTarget = true;
  40967. _this._size = size;
  40968. _this._generateMipMaps = generateMipMaps;
  40969. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  40970. _this._renderTargetOptions = {
  40971. generateMipMaps: generateMipMaps,
  40972. type: type,
  40973. samplingMode: samplingMode,
  40974. generateDepthBuffer: generateDepthBuffer,
  40975. generateStencilBuffer: generateStencilBuffer
  40976. };
  40977. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  40978. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40979. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40980. }
  40981. if (isCube) {
  40982. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  40983. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  40984. _this._textureMatrix = BABYLON.Matrix.Identity();
  40985. }
  40986. else {
  40987. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  40988. }
  40989. // Rendering groups
  40990. _this._renderingManager = new BABYLON.RenderingManager(scene);
  40991. return _this;
  40992. }
  40993. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  40994. get: function () {
  40995. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  40996. },
  40997. enumerable: true,
  40998. configurable: true
  40999. });
  41000. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  41001. get: function () {
  41002. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  41003. },
  41004. enumerable: true,
  41005. configurable: true
  41006. });
  41007. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  41008. get: function () {
  41009. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  41010. },
  41011. enumerable: true,
  41012. configurable: true
  41013. });
  41014. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  41015. set: function (callback) {
  41016. if (this._onAfterUnbindObserver) {
  41017. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  41018. }
  41019. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  41020. },
  41021. enumerable: true,
  41022. configurable: true
  41023. });
  41024. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  41025. set: function (callback) {
  41026. if (this._onBeforeRenderObserver) {
  41027. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  41028. }
  41029. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  41030. },
  41031. enumerable: true,
  41032. configurable: true
  41033. });
  41034. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  41035. set: function (callback) {
  41036. if (this._onAfterRenderObserver) {
  41037. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  41038. }
  41039. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  41040. },
  41041. enumerable: true,
  41042. configurable: true
  41043. });
  41044. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  41045. set: function (callback) {
  41046. if (this._onClearObserver) {
  41047. this.onClearObservable.remove(this._onClearObserver);
  41048. }
  41049. this._onClearObserver = this.onClearObservable.add(callback);
  41050. },
  41051. enumerable: true,
  41052. configurable: true
  41053. });
  41054. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  41055. get: function () {
  41056. return this._samples;
  41057. },
  41058. set: function (value) {
  41059. if (this._samples === value) {
  41060. return;
  41061. }
  41062. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  41063. },
  41064. enumerable: true,
  41065. configurable: true
  41066. });
  41067. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  41068. this._currentRefreshId = -1;
  41069. };
  41070. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  41071. get: function () {
  41072. return this._refreshRate;
  41073. },
  41074. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  41075. set: function (value) {
  41076. this._refreshRate = value;
  41077. this.resetRefreshCounter();
  41078. },
  41079. enumerable: true,
  41080. configurable: true
  41081. });
  41082. RenderTargetTexture.prototype._shouldRender = function () {
  41083. if (this._currentRefreshId === -1) {
  41084. this._currentRefreshId = 1;
  41085. return true;
  41086. }
  41087. if (this.refreshRate === this._currentRefreshId) {
  41088. this._currentRefreshId = 1;
  41089. return true;
  41090. }
  41091. this._currentRefreshId++;
  41092. return false;
  41093. };
  41094. RenderTargetTexture.prototype.isReady = function () {
  41095. if (!this.getScene().renderTargetsEnabled) {
  41096. return false;
  41097. }
  41098. return _super.prototype.isReady.call(this);
  41099. };
  41100. RenderTargetTexture.prototype.getRenderSize = function () {
  41101. return this._size;
  41102. };
  41103. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  41104. get: function () {
  41105. return true;
  41106. },
  41107. enumerable: true,
  41108. configurable: true
  41109. });
  41110. RenderTargetTexture.prototype.scale = function (ratio) {
  41111. var newSize = this._size * ratio;
  41112. this.resize(newSize);
  41113. };
  41114. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  41115. if (this.isCube) {
  41116. return this._textureMatrix;
  41117. }
  41118. return _super.prototype.getReflectionTextureMatrix.call(this);
  41119. };
  41120. RenderTargetTexture.prototype.resize = function (size) {
  41121. this.releaseInternalTexture();
  41122. if (this.isCube) {
  41123. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  41124. }
  41125. else {
  41126. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  41127. }
  41128. };
  41129. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  41130. var scene = this.getScene();
  41131. var engine = scene.getEngine();
  41132. if (this.useCameraPostProcesses !== undefined) {
  41133. useCameraPostProcess = this.useCameraPostProcesses;
  41134. }
  41135. if (this._waitingRenderList) {
  41136. this.renderList = [];
  41137. for (var index = 0; index < this._waitingRenderList.length; index++) {
  41138. var id = this._waitingRenderList[index];
  41139. this.renderList.push(scene.getMeshByID(id));
  41140. }
  41141. delete this._waitingRenderList;
  41142. }
  41143. // Is predicate defined?
  41144. if (this.renderListPredicate) {
  41145. this.renderList.splice(0); // Clear previous renderList
  41146. var sceneMeshes = this.getScene().meshes;
  41147. for (var index = 0; index < sceneMeshes.length; index++) {
  41148. var mesh = sceneMeshes[index];
  41149. if (this.renderListPredicate(mesh)) {
  41150. this.renderList.push(mesh);
  41151. }
  41152. }
  41153. }
  41154. if (this.renderList && this.renderList.length === 0) {
  41155. return;
  41156. }
  41157. // Set custom projection.
  41158. // Needs to be before binding to prevent changing the aspect ratio.
  41159. if (this.activeCamera) {
  41160. engine.setViewport(this.activeCamera.viewport);
  41161. if (this.activeCamera !== scene.activeCamera) {
  41162. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  41163. }
  41164. }
  41165. else {
  41166. engine.setViewport(scene.activeCamera.viewport);
  41167. }
  41168. // Prepare renderingManager
  41169. this._renderingManager.reset();
  41170. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  41171. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  41172. var sceneRenderId = scene.getRenderId();
  41173. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  41174. var mesh = currentRenderList[meshIndex];
  41175. if (mesh) {
  41176. if (!mesh.isReady()) {
  41177. // Reset _currentRefreshId
  41178. this.resetRefreshCounter();
  41179. continue;
  41180. }
  41181. mesh._preActivateForIntermediateRendering(sceneRenderId);
  41182. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  41183. mesh._activate(sceneRenderId);
  41184. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  41185. var subMesh = mesh.subMeshes[subIndex];
  41186. scene._activeIndices.addCount(subMesh.indexCount, false);
  41187. this._renderingManager.dispatch(subMesh);
  41188. }
  41189. }
  41190. }
  41191. }
  41192. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  41193. var particleSystem = scene.particleSystems[particleIndex];
  41194. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  41195. continue;
  41196. }
  41197. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  41198. this._renderingManager.dispatchParticles(particleSystem);
  41199. }
  41200. }
  41201. if (this.isCube) {
  41202. for (var face = 0; face < 6; face++) {
  41203. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  41204. scene.incrementRenderId();
  41205. scene.resetCachedMaterial();
  41206. }
  41207. }
  41208. else {
  41209. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  41210. }
  41211. this.onAfterUnbindObservable.notifyObservers(this);
  41212. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  41213. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  41214. }
  41215. engine.setViewport(scene.activeCamera.viewport);
  41216. scene.resetCachedMaterial();
  41217. };
  41218. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  41219. var _this = this;
  41220. var scene = this.getScene();
  41221. var engine = scene.getEngine();
  41222. // Bind
  41223. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  41224. if (this.isCube) {
  41225. engine.bindFramebuffer(this._texture, faceIndex);
  41226. }
  41227. else {
  41228. engine.bindFramebuffer(this._texture);
  41229. }
  41230. }
  41231. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  41232. // Clear
  41233. if (this.onClearObservable.hasObservers()) {
  41234. this.onClearObservable.notifyObservers(engine);
  41235. }
  41236. else {
  41237. engine.clear(scene.clearColor, true, true, true);
  41238. }
  41239. if (!this._doNotChangeAspectRatio) {
  41240. scene.updateTransformMatrix(true);
  41241. }
  41242. // Render
  41243. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  41244. if (useCameraPostProcess) {
  41245. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  41246. }
  41247. if (!this._doNotChangeAspectRatio) {
  41248. scene.updateTransformMatrix(true);
  41249. }
  41250. // Dump ?
  41251. if (dumpForDebug) {
  41252. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  41253. }
  41254. // Unbind
  41255. if (!this.isCube || faceIndex === 5) {
  41256. if (this.isCube) {
  41257. if (faceIndex === 5) {
  41258. engine.generateMipMapsForCubemap(this._texture);
  41259. }
  41260. }
  41261. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  41262. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  41263. });
  41264. }
  41265. else {
  41266. this.onAfterRenderObservable.notifyObservers(faceIndex);
  41267. }
  41268. };
  41269. /**
  41270. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  41271. * This allowed control for front to back rendering or reversly depending of the special needs.
  41272. *
  41273. * @param renderingGroupId The rendering group id corresponding to its index
  41274. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  41275. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  41276. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  41277. */
  41278. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  41279. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  41280. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  41281. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  41282. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  41283. };
  41284. /**
  41285. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  41286. *
  41287. * @param renderingGroupId The rendering group id corresponding to its index
  41288. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  41289. */
  41290. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  41291. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  41292. };
  41293. RenderTargetTexture.prototype.clone = function () {
  41294. var textureSize = this.getSize();
  41295. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  41296. // Base texture
  41297. newTexture.hasAlpha = this.hasAlpha;
  41298. newTexture.level = this.level;
  41299. // RenderTarget Texture
  41300. newTexture.coordinatesMode = this.coordinatesMode;
  41301. newTexture.renderList = this.renderList.slice(0);
  41302. return newTexture;
  41303. };
  41304. RenderTargetTexture.prototype.serialize = function () {
  41305. if (!this.name) {
  41306. return null;
  41307. }
  41308. var serializationObject = _super.prototype.serialize.call(this);
  41309. serializationObject.renderTargetSize = this.getRenderSize();
  41310. serializationObject.renderList = [];
  41311. for (var index = 0; index < this.renderList.length; index++) {
  41312. serializationObject.renderList.push(this.renderList[index].id);
  41313. }
  41314. return serializationObject;
  41315. };
  41316. return RenderTargetTexture;
  41317. }(BABYLON.Texture));
  41318. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  41319. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  41320. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  41321. BABYLON.RenderTargetTexture = RenderTargetTexture;
  41322. })(BABYLON || (BABYLON = {}));
  41323. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  41324. /// <reference path="babylon.renderTargetTexture.ts" />
  41325. var BABYLON;
  41326. (function (BABYLON) {
  41327. var MirrorTexture = (function (_super) {
  41328. __extends(MirrorTexture, _super);
  41329. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  41330. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41331. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  41332. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  41333. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  41334. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  41335. _this._transformMatrix = BABYLON.Matrix.Zero();
  41336. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  41337. _this.onBeforeRenderObservable.add(function () {
  41338. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  41339. _this._savedViewMatrix = scene.getViewMatrix();
  41340. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  41341. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  41342. scene.clipPlane = _this.mirrorPlane;
  41343. scene.getEngine().cullBackFaces = false;
  41344. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  41345. });
  41346. _this.onAfterRenderObservable.add(function () {
  41347. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  41348. scene.getEngine().cullBackFaces = true;
  41349. scene._mirroredCameraPosition = null;
  41350. delete scene.clipPlane;
  41351. });
  41352. return _this;
  41353. }
  41354. MirrorTexture.prototype.clone = function () {
  41355. var textureSize = this.getSize();
  41356. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  41357. // Base texture
  41358. newTexture.hasAlpha = this.hasAlpha;
  41359. newTexture.level = this.level;
  41360. // Mirror Texture
  41361. newTexture.mirrorPlane = this.mirrorPlane.clone();
  41362. newTexture.renderList = this.renderList.slice(0);
  41363. return newTexture;
  41364. };
  41365. MirrorTexture.prototype.serialize = function () {
  41366. if (!this.name) {
  41367. return null;
  41368. }
  41369. var serializationObject = _super.prototype.serialize.call(this);
  41370. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  41371. return serializationObject;
  41372. };
  41373. return MirrorTexture;
  41374. }(BABYLON.RenderTargetTexture));
  41375. BABYLON.MirrorTexture = MirrorTexture;
  41376. })(BABYLON || (BABYLON = {}));
  41377. //# sourceMappingURL=babylon.mirrorTexture.js.map
  41378. /// <reference path="babylon.renderTargetTexture.ts" />
  41379. var BABYLON;
  41380. (function (BABYLON) {
  41381. /**
  41382. * Creates a refraction texture used by refraction channel of the standard material.
  41383. * @param name the texture name
  41384. * @param size size of the underlying texture
  41385. * @param scene root scene
  41386. */
  41387. var RefractionTexture = (function (_super) {
  41388. __extends(RefractionTexture, _super);
  41389. function RefractionTexture(name, size, scene, generateMipMaps) {
  41390. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  41391. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  41392. _this.depth = 2.0;
  41393. _this.onBeforeRenderObservable.add(function () {
  41394. scene.clipPlane = _this.refractionPlane;
  41395. });
  41396. _this.onAfterRenderObservable.add(function () {
  41397. delete scene.clipPlane;
  41398. });
  41399. return _this;
  41400. }
  41401. RefractionTexture.prototype.clone = function () {
  41402. var textureSize = this.getSize();
  41403. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  41404. // Base texture
  41405. newTexture.hasAlpha = this.hasAlpha;
  41406. newTexture.level = this.level;
  41407. // Refraction Texture
  41408. newTexture.refractionPlane = this.refractionPlane.clone();
  41409. newTexture.renderList = this.renderList.slice(0);
  41410. newTexture.depth = this.depth;
  41411. return newTexture;
  41412. };
  41413. RefractionTexture.prototype.serialize = function () {
  41414. if (!this.name) {
  41415. return null;
  41416. }
  41417. var serializationObject = _super.prototype.serialize.call(this);
  41418. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  41419. serializationObject.depth = this.depth;
  41420. return serializationObject;
  41421. };
  41422. return RefractionTexture;
  41423. }(BABYLON.RenderTargetTexture));
  41424. BABYLON.RefractionTexture = RefractionTexture;
  41425. })(BABYLON || (BABYLON = {}));
  41426. //# sourceMappingURL=babylon.refractionTexture.js.map
  41427. /// <reference path="babylon.texture.ts" />
  41428. var BABYLON;
  41429. (function (BABYLON) {
  41430. var DynamicTexture = (function (_super) {
  41431. __extends(DynamicTexture, _super);
  41432. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  41433. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41434. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  41435. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  41436. _this.name = name;
  41437. var engine = _this.getScene().getEngine();
  41438. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41439. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41440. _this._generateMipMaps = generateMipMaps;
  41441. if (options.getContext) {
  41442. _this._canvas = options;
  41443. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  41444. }
  41445. else {
  41446. _this._canvas = document.createElement("canvas");
  41447. if (options.width) {
  41448. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  41449. }
  41450. else {
  41451. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  41452. }
  41453. }
  41454. var textureSize = _this.getSize();
  41455. _this._canvas.width = textureSize.width;
  41456. _this._canvas.height = textureSize.height;
  41457. _this._context = _this._canvas.getContext("2d");
  41458. return _this;
  41459. }
  41460. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  41461. get: function () {
  41462. return true;
  41463. },
  41464. enumerable: true,
  41465. configurable: true
  41466. });
  41467. DynamicTexture.prototype._recreate = function (textureSize) {
  41468. this._canvas.width = textureSize.width;
  41469. this._canvas.height = textureSize.height;
  41470. this.releaseInternalTexture();
  41471. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  41472. };
  41473. DynamicTexture.prototype.scale = function (ratio) {
  41474. var textureSize = this.getSize();
  41475. textureSize.width *= ratio;
  41476. textureSize.height *= ratio;
  41477. this._recreate(textureSize);
  41478. };
  41479. DynamicTexture.prototype.scaleTo = function (width, height) {
  41480. var textureSize = this.getSize();
  41481. textureSize.width = width;
  41482. textureSize.height = height;
  41483. this._recreate(textureSize);
  41484. };
  41485. DynamicTexture.prototype.getContext = function () {
  41486. return this._context;
  41487. };
  41488. DynamicTexture.prototype.clear = function () {
  41489. var size = this.getSize();
  41490. this._context.fillRect(0, 0, size.width, size.height);
  41491. };
  41492. DynamicTexture.prototype.update = function (invertY) {
  41493. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  41494. };
  41495. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  41496. if (update === void 0) { update = true; }
  41497. var size = this.getSize();
  41498. if (clearColor) {
  41499. this._context.fillStyle = clearColor;
  41500. this._context.fillRect(0, 0, size.width, size.height);
  41501. }
  41502. this._context.font = font;
  41503. if (x === null || x === undefined) {
  41504. var textSize = this._context.measureText(text);
  41505. x = (size.width - textSize.width) / 2;
  41506. }
  41507. if (y === null || y === undefined) {
  41508. var fontSize = parseInt((font.replace(/\D/g, '')));
  41509. ;
  41510. y = (size.height / 2) + (fontSize / 3.65);
  41511. }
  41512. this._context.fillStyle = color;
  41513. this._context.fillText(text, x, y);
  41514. if (update) {
  41515. this.update(invertY);
  41516. }
  41517. };
  41518. DynamicTexture.prototype.clone = function () {
  41519. var textureSize = this.getSize();
  41520. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  41521. // Base texture
  41522. newTexture.hasAlpha = this.hasAlpha;
  41523. newTexture.level = this.level;
  41524. // Dynamic Texture
  41525. newTexture.wrapU = this.wrapU;
  41526. newTexture.wrapV = this.wrapV;
  41527. return newTexture;
  41528. };
  41529. return DynamicTexture;
  41530. }(BABYLON.Texture));
  41531. BABYLON.DynamicTexture = DynamicTexture;
  41532. })(BABYLON || (BABYLON = {}));
  41533. //# sourceMappingURL=babylon.dynamicTexture.js.map
  41534. var BABYLON;
  41535. (function (BABYLON) {
  41536. var VideoTexture = (function (_super) {
  41537. __extends(VideoTexture, _super);
  41538. /**
  41539. * Creates a video texture.
  41540. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  41541. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  41542. * @param {BABYLON.Scene} scene is obviously the current scene.
  41543. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  41544. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  41545. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  41546. */
  41547. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  41548. if (generateMipMaps === void 0) { generateMipMaps = false; }
  41549. if (invertY === void 0) { invertY = false; }
  41550. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41551. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  41552. _this._autoLaunch = true;
  41553. var urls;
  41554. _this.name = name;
  41555. if (urlsOrVideo instanceof HTMLVideoElement) {
  41556. _this.video = urlsOrVideo;
  41557. }
  41558. else {
  41559. urls = urlsOrVideo;
  41560. _this.video = document.createElement("video");
  41561. _this.video.autoplay = false;
  41562. _this.video.loop = true;
  41563. }
  41564. _this._generateMipMaps = generateMipMaps;
  41565. _this._samplingMode = samplingMode;
  41566. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  41567. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  41568. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  41569. }
  41570. else {
  41571. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41572. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41573. _this._generateMipMaps = false;
  41574. }
  41575. if (urls) {
  41576. _this.video.addEventListener("canplay", function () {
  41577. _this._createTexture();
  41578. });
  41579. urls.forEach(function (url) {
  41580. var source = document.createElement("source");
  41581. source.src = url;
  41582. _this.video.appendChild(source);
  41583. });
  41584. }
  41585. else {
  41586. _this._createTexture();
  41587. }
  41588. _this._lastUpdate = BABYLON.Tools.Now;
  41589. return _this;
  41590. }
  41591. VideoTexture.prototype._createTexture = function () {
  41592. var _this = this;
  41593. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  41594. if (this._autoLaunch) {
  41595. this._autoLaunch = false;
  41596. this.video.play();
  41597. }
  41598. this.video.addEventListener("playing", function () {
  41599. _this._texture.isReady = true;
  41600. });
  41601. };
  41602. VideoTexture.prototype.update = function () {
  41603. var now = BABYLON.Tools.Now;
  41604. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  41605. return false;
  41606. }
  41607. this._lastUpdate = now;
  41608. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  41609. return true;
  41610. };
  41611. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  41612. var video = document.createElement("video");
  41613. var constraintsDeviceId;
  41614. if (constraints && constraints.deviceId) {
  41615. constraintsDeviceId = {
  41616. exact: constraints.deviceId
  41617. };
  41618. }
  41619. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  41620. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  41621. if (navigator.getUserMedia) {
  41622. navigator.getUserMedia({
  41623. video: {
  41624. deviceId: constraintsDeviceId,
  41625. width: {
  41626. min: (constraints && constraints.minWidth) || 256,
  41627. max: (constraints && constraints.maxWidth) || 640
  41628. },
  41629. height: {
  41630. min: (constraints && constraints.minHeight) || 256,
  41631. max: (constraints && constraints.maxHeight) || 480
  41632. }
  41633. }
  41634. }, function (stream) {
  41635. if (video.mozSrcObject !== undefined) {
  41636. video.mozSrcObject = stream;
  41637. }
  41638. else {
  41639. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  41640. }
  41641. video.play();
  41642. if (onReady) {
  41643. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  41644. }
  41645. }, function (e) {
  41646. BABYLON.Tools.Error(e.name);
  41647. });
  41648. }
  41649. };
  41650. return VideoTexture;
  41651. }(BABYLON.Texture));
  41652. BABYLON.VideoTexture = VideoTexture;
  41653. })(BABYLON || (BABYLON = {}));
  41654. //# sourceMappingURL=babylon.videoTexture.js.map
  41655. var BABYLON;
  41656. (function (BABYLON) {
  41657. var RawTexture = (function (_super) {
  41658. __extends(RawTexture, _super);
  41659. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  41660. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41661. if (invertY === void 0) { invertY = false; }
  41662. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41663. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  41664. _this.format = format;
  41665. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  41666. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41667. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41668. return _this;
  41669. }
  41670. RawTexture.prototype.update = function (data) {
  41671. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  41672. };
  41673. // Statics
  41674. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  41675. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41676. if (invertY === void 0) { invertY = false; }
  41677. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41678. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  41679. };
  41680. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  41681. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41682. if (invertY === void 0) { invertY = false; }
  41683. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41684. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  41685. };
  41686. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  41687. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41688. if (invertY === void 0) { invertY = false; }
  41689. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41690. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  41691. };
  41692. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  41693. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41694. if (invertY === void 0) { invertY = false; }
  41695. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41696. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  41697. };
  41698. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  41699. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41700. if (invertY === void 0) { invertY = false; }
  41701. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41702. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  41703. };
  41704. return RawTexture;
  41705. }(BABYLON.Texture));
  41706. BABYLON.RawTexture = RawTexture;
  41707. })(BABYLON || (BABYLON = {}));
  41708. //# sourceMappingURL=babylon.rawTexture.js.map
  41709. var BABYLON;
  41710. (function (BABYLON) {
  41711. var PostProcess = (function () {
  41712. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  41713. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  41714. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41715. this.name = name;
  41716. this.width = -1;
  41717. this.height = -1;
  41718. /*
  41719. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  41720. Can only be used on a single postprocess or on the last one of a chain.
  41721. */
  41722. this.enablePixelPerfectMode = false;
  41723. this.samples = 1;
  41724. this._reusable = false;
  41725. this._textures = new BABYLON.SmartArray(2);
  41726. this._currentRenderTextureInd = 0;
  41727. this._scaleRatio = new BABYLON.Vector2(1, 1);
  41728. // Events
  41729. /**
  41730. * An event triggered when the postprocess is activated.
  41731. * @type {BABYLON.Observable}
  41732. */
  41733. this.onActivateObservable = new BABYLON.Observable();
  41734. /**
  41735. * An event triggered when the postprocess changes its size.
  41736. * @type {BABYLON.Observable}
  41737. */
  41738. this.onSizeChangedObservable = new BABYLON.Observable();
  41739. /**
  41740. * An event triggered when the postprocess applies its effect.
  41741. * @type {BABYLON.Observable}
  41742. */
  41743. this.onApplyObservable = new BABYLON.Observable();
  41744. /**
  41745. * An event triggered before rendering the postprocess
  41746. * @type {BABYLON.Observable}
  41747. */
  41748. this.onBeforeRenderObservable = new BABYLON.Observable();
  41749. /**
  41750. * An event triggered after rendering the postprocess
  41751. * @type {BABYLON.Observable}
  41752. */
  41753. this.onAfterRenderObservable = new BABYLON.Observable();
  41754. if (camera != null) {
  41755. this._camera = camera;
  41756. this._scene = camera.getScene();
  41757. camera.attachPostProcess(this);
  41758. this._engine = this._scene.getEngine();
  41759. }
  41760. else {
  41761. this._engine = engine;
  41762. }
  41763. this._options = options;
  41764. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  41765. this._reusable = reusable || false;
  41766. this._textureType = textureType;
  41767. this._samplers = samplers || [];
  41768. this._samplers.push("textureSampler");
  41769. this._fragmentUrl = fragmentUrl;
  41770. this._parameters = parameters || [];
  41771. this._parameters.push("scale");
  41772. this.updateEffect(defines);
  41773. }
  41774. Object.defineProperty(PostProcess.prototype, "onActivate", {
  41775. set: function (callback) {
  41776. if (this._onActivateObserver) {
  41777. this.onActivateObservable.remove(this._onActivateObserver);
  41778. }
  41779. this._onActivateObserver = this.onActivateObservable.add(callback);
  41780. },
  41781. enumerable: true,
  41782. configurable: true
  41783. });
  41784. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  41785. set: function (callback) {
  41786. if (this._onSizeChangedObserver) {
  41787. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  41788. }
  41789. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  41790. },
  41791. enumerable: true,
  41792. configurable: true
  41793. });
  41794. Object.defineProperty(PostProcess.prototype, "onApply", {
  41795. set: function (callback) {
  41796. if (this._onApplyObserver) {
  41797. this.onApplyObservable.remove(this._onApplyObserver);
  41798. }
  41799. this._onApplyObserver = this.onApplyObservable.add(callback);
  41800. },
  41801. enumerable: true,
  41802. configurable: true
  41803. });
  41804. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  41805. set: function (callback) {
  41806. if (this._onBeforeRenderObserver) {
  41807. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  41808. }
  41809. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  41810. },
  41811. enumerable: true,
  41812. configurable: true
  41813. });
  41814. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  41815. set: function (callback) {
  41816. if (this._onAfterRenderObserver) {
  41817. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  41818. }
  41819. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  41820. },
  41821. enumerable: true,
  41822. configurable: true
  41823. });
  41824. PostProcess.prototype.updateEffect = function (defines) {
  41825. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  41826. };
  41827. PostProcess.prototype.isReusable = function () {
  41828. return this._reusable;
  41829. };
  41830. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  41831. PostProcess.prototype.markTextureDirty = function () {
  41832. this.width = -1;
  41833. };
  41834. PostProcess.prototype.activate = function (camera, sourceTexture) {
  41835. var _this = this;
  41836. camera = camera || this._camera;
  41837. var scene = camera.getScene();
  41838. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  41839. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  41840. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  41841. var desiredWidth = this._options.width || requiredWidth;
  41842. var desiredHeight = this._options.height || requiredHeight;
  41843. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  41844. if (!this._options.width) {
  41845. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  41846. }
  41847. if (!this._options.height) {
  41848. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  41849. }
  41850. }
  41851. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  41852. if (this._textures.length > 0) {
  41853. for (var i = 0; i < this._textures.length; i++) {
  41854. this._engine._releaseTexture(this._textures.data[i]);
  41855. }
  41856. this._textures.reset();
  41857. }
  41858. this.width = desiredWidth;
  41859. this.height = desiredHeight;
  41860. var textureSize = { width: this.width, height: this.height };
  41861. var textureOptions = {
  41862. generateMipMaps: false,
  41863. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  41864. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  41865. samplingMode: this.renderTargetSamplingMode,
  41866. type: this._textureType
  41867. };
  41868. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  41869. if (this._reusable) {
  41870. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  41871. }
  41872. this.onSizeChangedObservable.notifyObservers(this);
  41873. }
  41874. this._textures.forEach(function (texture) {
  41875. if (texture.samples !== _this.samples) {
  41876. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  41877. }
  41878. });
  41879. if (this.enablePixelPerfectMode) {
  41880. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  41881. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  41882. }
  41883. else {
  41884. this._scaleRatio.copyFromFloats(1, 1);
  41885. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  41886. }
  41887. this.onActivateObservable.notifyObservers(camera);
  41888. // Clear
  41889. if (this.clearColor) {
  41890. this._engine.clear(this.clearColor, true, true, true);
  41891. }
  41892. else {
  41893. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  41894. }
  41895. if (this._reusable) {
  41896. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  41897. }
  41898. };
  41899. Object.defineProperty(PostProcess.prototype, "isSupported", {
  41900. get: function () {
  41901. return this._effect.isSupported;
  41902. },
  41903. enumerable: true,
  41904. configurable: true
  41905. });
  41906. PostProcess.prototype.apply = function () {
  41907. // Check
  41908. if (!this._effect.isReady())
  41909. return null;
  41910. // States
  41911. this._engine.enableEffect(this._effect);
  41912. this._engine.setState(false);
  41913. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  41914. this._engine.setDepthBuffer(false);
  41915. this._engine.setDepthWrite(false);
  41916. // Texture
  41917. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  41918. // Parameters
  41919. this._effect.setVector2("scale", this._scaleRatio);
  41920. this.onApplyObservable.notifyObservers(this._effect);
  41921. return this._effect;
  41922. };
  41923. PostProcess.prototype.dispose = function (camera) {
  41924. camera = camera || this._camera;
  41925. if (this._textures.length > 0) {
  41926. for (var i = 0; i < this._textures.length; i++) {
  41927. this._engine._releaseTexture(this._textures.data[i]);
  41928. }
  41929. }
  41930. this._textures.dispose();
  41931. if (!camera) {
  41932. return;
  41933. }
  41934. camera.detachPostProcess(this);
  41935. var index = camera._postProcesses.indexOf(this);
  41936. if (index === 0 && camera._postProcesses.length > 0) {
  41937. this._camera._postProcesses[0].markTextureDirty();
  41938. }
  41939. this.onActivateObservable.clear();
  41940. this.onAfterRenderObservable.clear();
  41941. this.onApplyObservable.clear();
  41942. this.onBeforeRenderObservable.clear();
  41943. this.onSizeChangedObservable.clear();
  41944. };
  41945. return PostProcess;
  41946. }());
  41947. BABYLON.PostProcess = PostProcess;
  41948. })(BABYLON || (BABYLON = {}));
  41949. //# sourceMappingURL=babylon.postProcess.js.map
  41950. var BABYLON;
  41951. (function (BABYLON) {
  41952. var PassPostProcess = (function (_super) {
  41953. __extends(PassPostProcess, _super);
  41954. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41955. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41956. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  41957. }
  41958. return PassPostProcess;
  41959. }(BABYLON.PostProcess));
  41960. BABYLON.PassPostProcess = PassPostProcess;
  41961. })(BABYLON || (BABYLON = {}));
  41962. //# sourceMappingURL=babylon.passPostProcess.js.map
  41963. var BABYLON;
  41964. (function (BABYLON) {
  41965. var ShadowGenerator = (function () {
  41966. /**
  41967. * Creates a ShadowGenerator object.
  41968. * A ShadowGenerator is the required tool to use the shadows.
  41969. * Each light casting shadows needs to use its own ShadowGenerator.
  41970. * Required parameters :
  41971. * - `mapSize` (integer), the size of the texture what stores the shadows. Example : 1024.
  41972. * - `light` : the light object generating the shadows.
  41973. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  41974. */
  41975. function ShadowGenerator(mapSize, light) {
  41976. var _this = this;
  41977. // Members
  41978. this._filter = ShadowGenerator.FILTER_NONE;
  41979. this.blurScale = 2;
  41980. this._blurBoxOffset = 0;
  41981. this._bias = 0.00005;
  41982. this._lightDirection = BABYLON.Vector3.Zero();
  41983. this.forceBackFacesOnly = false;
  41984. this._darkness = 0;
  41985. this._transparencyShadow = false;
  41986. this._viewMatrix = BABYLON.Matrix.Zero();
  41987. this._projectionMatrix = BABYLON.Matrix.Zero();
  41988. this._transformMatrix = BABYLON.Matrix.Zero();
  41989. this._worldViewProjection = BABYLON.Matrix.Zero();
  41990. this._currentFaceIndex = 0;
  41991. this._currentFaceIndexCache = 0;
  41992. this._useFullFloat = true;
  41993. this._light = light;
  41994. this._scene = light.getScene();
  41995. this._mapSize = mapSize;
  41996. light._shadowGenerator = this;
  41997. light._markMeshesAsLightDirty();
  41998. // Texture type fallback from float to int if not supported.
  41999. var textureType;
  42000. var caps = this._scene.getEngine().getCaps();
  42001. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  42002. this._useFullFloat = true;
  42003. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  42004. }
  42005. else {
  42006. this._useFullFloat = false;
  42007. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  42008. }
  42009. // Render target
  42010. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  42011. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42012. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42013. this._shadowMap.anisotropicFilteringLevel = 1;
  42014. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  42015. this._shadowMap.renderParticles = false;
  42016. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  42017. _this._currentFaceIndex = faceIndex;
  42018. });
  42019. this._shadowMap.onAfterUnbindObservable.add(function () {
  42020. if (!_this.useBlurExponentialShadowMap) {
  42021. return;
  42022. }
  42023. if (!_this._shadowMap2) {
  42024. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  42025. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42026. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42027. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  42028. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine(), false, textureType);
  42029. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  42030. effect.setTexture("textureSampler", _this._shadowMap);
  42031. });
  42032. _this.blurBoxOffset = 1;
  42033. }
  42034. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  42035. });
  42036. // Custom render function
  42037. var renderSubMesh = function (subMesh) {
  42038. var mesh = subMesh.getRenderingMesh();
  42039. var scene = _this._scene;
  42040. var engine = scene.getEngine();
  42041. // Culling
  42042. engine.setState(subMesh.getMaterial().backFaceCulling);
  42043. // Managing instances
  42044. var batch = mesh._getInstancesRenderList(subMesh._id);
  42045. if (batch.mustReturn) {
  42046. return;
  42047. }
  42048. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  42049. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  42050. engine.enableEffect(_this._effect);
  42051. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  42052. var material = subMesh.getMaterial();
  42053. _this._effect.setFloat2("biasAndScale", _this.bias, _this.depthScale);
  42054. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  42055. _this._effect.setVector3("lightPosition", _this.getLight().position);
  42056. if (_this.getLight().needCube()) {
  42057. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  42058. }
  42059. // Alpha test
  42060. if (material && material.needAlphaTesting()) {
  42061. var alphaTexture = material.getAlphaTestTexture();
  42062. _this._effect.setTexture("diffuseSampler", alphaTexture);
  42063. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  42064. }
  42065. // Bones
  42066. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  42067. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  42068. }
  42069. if (_this.forceBackFacesOnly) {
  42070. engine.setState(true, 0, false, true);
  42071. }
  42072. // Draw
  42073. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  42074. if (_this.forceBackFacesOnly) {
  42075. engine.setState(true, 0, false, false);
  42076. }
  42077. }
  42078. else {
  42079. // Need to reset refresh rate of the shadowMap
  42080. _this._shadowMap.resetRefreshCounter();
  42081. }
  42082. };
  42083. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  42084. var index;
  42085. for (index = 0; index < opaqueSubMeshes.length; index++) {
  42086. renderSubMesh(opaqueSubMeshes.data[index]);
  42087. }
  42088. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  42089. renderSubMesh(alphaTestSubMeshes.data[index]);
  42090. }
  42091. if (_this._transparencyShadow) {
  42092. for (index = 0; index < transparentSubMeshes.length; index++) {
  42093. renderSubMesh(transparentSubMeshes.data[index]);
  42094. }
  42095. }
  42096. };
  42097. this._shadowMap.onClearObservable.add(function (engine) {
  42098. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  42099. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  42100. }
  42101. else {
  42102. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  42103. }
  42104. });
  42105. }
  42106. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  42107. // Static
  42108. get: function () {
  42109. return ShadowGenerator._FILTER_NONE;
  42110. },
  42111. enumerable: true,
  42112. configurable: true
  42113. });
  42114. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  42115. get: function () {
  42116. return ShadowGenerator._FILTER_POISSONSAMPLING;
  42117. },
  42118. enumerable: true,
  42119. configurable: true
  42120. });
  42121. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  42122. get: function () {
  42123. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  42124. },
  42125. enumerable: true,
  42126. configurable: true
  42127. });
  42128. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  42129. get: function () {
  42130. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  42131. },
  42132. enumerable: true,
  42133. configurable: true
  42134. });
  42135. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  42136. get: function () {
  42137. return this._bias;
  42138. },
  42139. set: function (bias) {
  42140. this._bias = bias;
  42141. },
  42142. enumerable: true,
  42143. configurable: true
  42144. });
  42145. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  42146. get: function () {
  42147. return this._blurBoxOffset;
  42148. },
  42149. set: function (value) {
  42150. var _this = this;
  42151. if (this._blurBoxOffset === value) {
  42152. return;
  42153. }
  42154. this._blurBoxOffset = value;
  42155. if (this._boxBlurPostprocess) {
  42156. this._boxBlurPostprocess.dispose();
  42157. }
  42158. var textureType;
  42159. var caps = this._scene.getEngine().getCaps();
  42160. if (this._useFullFloat) {
  42161. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  42162. }
  42163. else {
  42164. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  42165. }
  42166. 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, textureType);
  42167. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  42168. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  42169. });
  42170. },
  42171. enumerable: true,
  42172. configurable: true
  42173. });
  42174. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  42175. get: function () {
  42176. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  42177. },
  42178. set: function (value) {
  42179. this._depthScale = value;
  42180. },
  42181. enumerable: true,
  42182. configurable: true
  42183. });
  42184. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  42185. get: function () {
  42186. return this._filter;
  42187. },
  42188. set: function (value) {
  42189. if (this._filter === value) {
  42190. return;
  42191. }
  42192. this._filter = value;
  42193. if (this.usePoissonSampling || this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  42194. this._shadowMap.anisotropicFilteringLevel = 16;
  42195. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  42196. }
  42197. else {
  42198. this._shadowMap.anisotropicFilteringLevel = 1;
  42199. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  42200. }
  42201. this._light._markMeshesAsLightDirty();
  42202. },
  42203. enumerable: true,
  42204. configurable: true
  42205. });
  42206. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  42207. get: function () {
  42208. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  42209. return this.useExponentialShadowMap;
  42210. },
  42211. set: function (value) {
  42212. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  42213. this.useExponentialShadowMap = value;
  42214. },
  42215. enumerable: true,
  42216. configurable: true
  42217. });
  42218. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  42219. get: function () {
  42220. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  42221. },
  42222. set: function (value) {
  42223. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  42224. },
  42225. enumerable: true,
  42226. configurable: true
  42227. });
  42228. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  42229. get: function () {
  42230. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  42231. },
  42232. set: function (value) {
  42233. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  42234. },
  42235. enumerable: true,
  42236. configurable: true
  42237. });
  42238. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  42239. get: function () {
  42240. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  42241. return this.useBlurExponentialShadowMap;
  42242. },
  42243. set: function (value) {
  42244. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  42245. this.useBlurExponentialShadowMap = value;
  42246. },
  42247. enumerable: true,
  42248. configurable: true
  42249. });
  42250. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  42251. get: function () {
  42252. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  42253. },
  42254. set: function (value) {
  42255. if (this._light.needCube() && value) {
  42256. this.useExponentialShadowMap = true; // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  42257. }
  42258. else {
  42259. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  42260. }
  42261. },
  42262. enumerable: true,
  42263. configurable: true
  42264. });
  42265. /**
  42266. * Boolean : true when the ShadowGenerator is finally computed.
  42267. */
  42268. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  42269. var defines = [];
  42270. if (this._useFullFloat) {
  42271. defines.push("#define FULLFLOAT");
  42272. }
  42273. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  42274. defines.push("#define ESM");
  42275. }
  42276. if (this.getLight().needCube()) {
  42277. defines.push("#define CUBEMAP");
  42278. }
  42279. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42280. var mesh = subMesh.getMesh();
  42281. var material = subMesh.getMaterial();
  42282. // Alpha test
  42283. if (material && material.needAlphaTesting()) {
  42284. defines.push("#define ALPHATEST");
  42285. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42286. attribs.push(BABYLON.VertexBuffer.UVKind);
  42287. defines.push("#define UV1");
  42288. }
  42289. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  42290. var alphaTexture = material.getAlphaTestTexture();
  42291. if (alphaTexture.coordinatesIndex === 1) {
  42292. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42293. defines.push("#define UV2");
  42294. }
  42295. }
  42296. }
  42297. // Bones
  42298. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  42299. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42300. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42301. if (mesh.numBoneInfluencers > 4) {
  42302. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42303. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42304. }
  42305. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  42306. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  42307. }
  42308. else {
  42309. defines.push("#define NUM_BONE_INFLUENCERS 0");
  42310. }
  42311. // Instances
  42312. if (useInstances) {
  42313. defines.push("#define INSTANCES");
  42314. attribs.push("world0");
  42315. attribs.push("world1");
  42316. attribs.push("world2");
  42317. attribs.push("world3");
  42318. }
  42319. // Get correct effect
  42320. var join = defines.join("\n");
  42321. if (this._cachedDefines !== join) {
  42322. this._cachedDefines = join;
  42323. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  42324. }
  42325. return this._effect.isReady();
  42326. };
  42327. /**
  42328. * Returns a RenderTargetTexture object : the shadow map texture.
  42329. */
  42330. ShadowGenerator.prototype.getShadowMap = function () {
  42331. return this._shadowMap;
  42332. };
  42333. /**
  42334. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  42335. */
  42336. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  42337. if (this._shadowMap2) {
  42338. return this._shadowMap2;
  42339. }
  42340. return this._shadowMap;
  42341. };
  42342. /**
  42343. * Returns the associated light object.
  42344. */
  42345. ShadowGenerator.prototype.getLight = function () {
  42346. return this._light;
  42347. };
  42348. // Methods
  42349. /**
  42350. * Returns a Matrix object : the updated transformation matrix.
  42351. */
  42352. ShadowGenerator.prototype.getTransformMatrix = function () {
  42353. var scene = this._scene;
  42354. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  42355. return this._transformMatrix;
  42356. }
  42357. this._currentRenderID = scene.getRenderId();
  42358. this._currentFaceIndexCache = this._currentFaceIndex;
  42359. var lightPosition = this._light.position;
  42360. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  42361. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  42362. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  42363. }
  42364. if (this._light.computeTransformedPosition()) {
  42365. lightPosition = this._light.transformedPosition;
  42366. }
  42367. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  42368. this._cachedPosition = lightPosition.clone();
  42369. this._cachedDirection = this._lightDirection.clone();
  42370. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  42371. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  42372. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  42373. }
  42374. return this._transformMatrix;
  42375. };
  42376. /**
  42377. * Returns the darkness value (float).
  42378. */
  42379. ShadowGenerator.prototype.getDarkness = function () {
  42380. return this._darkness;
  42381. };
  42382. /**
  42383. * Sets the ShadowGenerator darkness value (float <= 1.0).
  42384. * Returns the ShadowGenerator.
  42385. */
  42386. ShadowGenerator.prototype.setDarkness = function (darkness) {
  42387. if (darkness >= 1.0)
  42388. this._darkness = 1.0;
  42389. else if (darkness <= 0.0)
  42390. this._darkness = 0.0;
  42391. else
  42392. this._darkness = darkness;
  42393. return this;
  42394. };
  42395. /**
  42396. * Sets the ability to have transparent shadow (boolean).
  42397. * Returns the ShadowGenerator.
  42398. */
  42399. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  42400. this._transparencyShadow = hasShadow;
  42401. return this;
  42402. };
  42403. ShadowGenerator.prototype._packHalf = function (depth) {
  42404. var scale = depth * 255.0;
  42405. var fract = scale - Math.floor(scale);
  42406. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  42407. };
  42408. /**
  42409. * Disposes the ShadowGenerator.
  42410. * Returns nothing.
  42411. */
  42412. ShadowGenerator.prototype.dispose = function () {
  42413. this._shadowMap.dispose();
  42414. if (this._shadowMap2) {
  42415. this._shadowMap2.dispose();
  42416. }
  42417. if (this._downSamplePostprocess) {
  42418. this._downSamplePostprocess.dispose();
  42419. }
  42420. if (this._boxBlurPostprocess) {
  42421. this._boxBlurPostprocess.dispose();
  42422. }
  42423. this._light._shadowGenerator = null;
  42424. this._light._markMeshesAsLightDirty();
  42425. };
  42426. /**
  42427. * Serializes the ShadowGenerator and returns a serializationObject.
  42428. */
  42429. ShadowGenerator.prototype.serialize = function () {
  42430. var serializationObject = {};
  42431. serializationObject.lightId = this._light.id;
  42432. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  42433. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  42434. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  42435. serializationObject.usePoissonSampling = this.usePoissonSampling;
  42436. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  42437. serializationObject.depthScale = this.depthScale;
  42438. serializationObject.darkness = this.getDarkness();
  42439. serializationObject.renderList = [];
  42440. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  42441. var mesh = this.getShadowMap().renderList[meshIndex];
  42442. serializationObject.renderList.push(mesh.id);
  42443. }
  42444. return serializationObject;
  42445. };
  42446. /**
  42447. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  42448. */
  42449. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  42450. //casting to point light, as light is missing the position attr and typescript complains.
  42451. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  42452. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  42453. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  42454. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  42455. meshes.forEach(function (mesh) {
  42456. shadowGenerator.getShadowMap().renderList.push(mesh);
  42457. });
  42458. }
  42459. if (parsedShadowGenerator.usePoissonSampling) {
  42460. shadowGenerator.usePoissonSampling = true;
  42461. }
  42462. else if (parsedShadowGenerator.useExponentialShadowMap) {
  42463. shadowGenerator.useExponentialShadowMap = true;
  42464. }
  42465. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  42466. shadowGenerator.useBlurExponentialShadowMap = true;
  42467. }
  42468. else if (parsedShadowGenerator.useVarianceShadowMap) {
  42469. shadowGenerator.useExponentialShadowMap = true;
  42470. }
  42471. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  42472. shadowGenerator.useBlurExponentialShadowMap = true;
  42473. }
  42474. if (parsedShadowGenerator.depthScale) {
  42475. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  42476. }
  42477. if (parsedShadowGenerator.blurScale) {
  42478. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  42479. }
  42480. if (parsedShadowGenerator.blurBoxOffset) {
  42481. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  42482. }
  42483. if (parsedShadowGenerator.bias !== undefined) {
  42484. shadowGenerator.bias = parsedShadowGenerator.bias;
  42485. }
  42486. if (parsedShadowGenerator.darkness) {
  42487. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  42488. }
  42489. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  42490. return shadowGenerator;
  42491. };
  42492. return ShadowGenerator;
  42493. }());
  42494. ShadowGenerator._FILTER_NONE = 0;
  42495. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  42496. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  42497. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  42498. BABYLON.ShadowGenerator = ShadowGenerator;
  42499. })(BABYLON || (BABYLON = {}));
  42500. //# sourceMappingURL=babylon.shadowGenerator.js.map
  42501. var BABYLON;
  42502. (function (BABYLON) {
  42503. var DefaultLoadingScreen = (function () {
  42504. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  42505. if (_loadingText === void 0) { _loadingText = ""; }
  42506. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  42507. var _this = this;
  42508. this._renderingCanvas = _renderingCanvas;
  42509. this._loadingText = _loadingText;
  42510. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  42511. // Resize
  42512. this._resizeLoadingUI = function () {
  42513. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  42514. _this._loadingDiv.style.position = "absolute";
  42515. _this._loadingDiv.style.left = canvasRect.left + "px";
  42516. _this._loadingDiv.style.top = canvasRect.top + "px";
  42517. _this._loadingDiv.style.width = canvasRect.width + "px";
  42518. _this._loadingDiv.style.height = canvasRect.height + "px";
  42519. };
  42520. }
  42521. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  42522. var _this = this;
  42523. if (this._loadingDiv) {
  42524. // Do not add a loading screen if there is already one
  42525. return;
  42526. }
  42527. this._loadingDiv = document.createElement("div");
  42528. this._loadingDiv.id = "babylonjsLoadingDiv";
  42529. this._loadingDiv.style.opacity = "0";
  42530. this._loadingDiv.style.transition = "opacity 1.5s ease";
  42531. // Loading text
  42532. this._loadingTextDiv = document.createElement("div");
  42533. this._loadingTextDiv.style.position = "absolute";
  42534. this._loadingTextDiv.style.left = "0";
  42535. this._loadingTextDiv.style.top = "50%";
  42536. this._loadingTextDiv.style.marginTop = "80px";
  42537. this._loadingTextDiv.style.width = "100%";
  42538. this._loadingTextDiv.style.height = "20px";
  42539. this._loadingTextDiv.style.fontFamily = "Arial";
  42540. this._loadingTextDiv.style.fontSize = "14px";
  42541. this._loadingTextDiv.style.color = "white";
  42542. this._loadingTextDiv.style.textAlign = "center";
  42543. this._loadingTextDiv.innerHTML = "Loading";
  42544. this._loadingDiv.appendChild(this._loadingTextDiv);
  42545. //set the predefined text
  42546. this._loadingTextDiv.innerHTML = this._loadingText;
  42547. // Loading img
  42548. var imgBack = new Image();
  42549. 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==";
  42550. imgBack.style.position = "absolute";
  42551. imgBack.style.left = "50%";
  42552. imgBack.style.top = "50%";
  42553. imgBack.style.marginLeft = "-50px";
  42554. imgBack.style.marginTop = "-50px";
  42555. imgBack.style.transition = "transform 1.0s ease";
  42556. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  42557. var deg = 360;
  42558. var onTransitionEnd = function () {
  42559. deg += 360;
  42560. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  42561. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  42562. };
  42563. imgBack.addEventListener("transitionend", onTransitionEnd);
  42564. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  42565. this._loadingDiv.appendChild(imgBack);
  42566. // front image
  42567. var imgFront = new Image();
  42568. 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=";
  42569. imgFront.style.position = "absolute";
  42570. imgFront.style.left = "50%";
  42571. imgFront.style.top = "50%";
  42572. imgFront.style.marginLeft = "-50px";
  42573. imgFront.style.marginTop = "-50px";
  42574. this._loadingDiv.appendChild(imgFront);
  42575. this._resizeLoadingUI();
  42576. window.addEventListener("resize", this._resizeLoadingUI);
  42577. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  42578. document.body.appendChild(this._loadingDiv);
  42579. setTimeout(function () {
  42580. _this._loadingDiv.style.opacity = "1";
  42581. imgBack.style.transform = "rotateZ(360deg)";
  42582. imgBack.style.webkitTransform = "rotateZ(360deg)";
  42583. }, 0);
  42584. };
  42585. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  42586. var _this = this;
  42587. if (!this._loadingDiv) {
  42588. return;
  42589. }
  42590. var onTransitionEnd = function () {
  42591. if (!_this._loadingDiv) {
  42592. return;
  42593. }
  42594. document.body.removeChild(_this._loadingDiv);
  42595. window.removeEventListener("resize", _this._resizeLoadingUI);
  42596. _this._loadingDiv = null;
  42597. };
  42598. this._loadingDiv.style.opacity = "0";
  42599. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  42600. };
  42601. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  42602. set: function (text) {
  42603. this._loadingText = text;
  42604. if (this._loadingTextDiv) {
  42605. this._loadingTextDiv.innerHTML = this._loadingText;
  42606. }
  42607. },
  42608. enumerable: true,
  42609. configurable: true
  42610. });
  42611. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  42612. get: function () {
  42613. return this._loadingDivBackgroundColor;
  42614. },
  42615. set: function (color) {
  42616. this._loadingDivBackgroundColor = color;
  42617. if (!this._loadingDiv) {
  42618. return;
  42619. }
  42620. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  42621. },
  42622. enumerable: true,
  42623. configurable: true
  42624. });
  42625. return DefaultLoadingScreen;
  42626. }());
  42627. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  42628. })(BABYLON || (BABYLON = {}));
  42629. //# sourceMappingURL=babylon.loadingScreen.js.map
  42630. var BABYLON;
  42631. (function (BABYLON) {
  42632. var SceneLoader = (function () {
  42633. function SceneLoader() {
  42634. }
  42635. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  42636. get: function () {
  42637. return 0;
  42638. },
  42639. enumerable: true,
  42640. configurable: true
  42641. });
  42642. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  42643. get: function () {
  42644. return 1;
  42645. },
  42646. enumerable: true,
  42647. configurable: true
  42648. });
  42649. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  42650. get: function () {
  42651. return 2;
  42652. },
  42653. enumerable: true,
  42654. configurable: true
  42655. });
  42656. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  42657. get: function () {
  42658. return 3;
  42659. },
  42660. enumerable: true,
  42661. configurable: true
  42662. });
  42663. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  42664. get: function () {
  42665. return SceneLoader._ForceFullSceneLoadingForIncremental;
  42666. },
  42667. set: function (value) {
  42668. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  42669. },
  42670. enumerable: true,
  42671. configurable: true
  42672. });
  42673. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  42674. get: function () {
  42675. return SceneLoader._ShowLoadingScreen;
  42676. },
  42677. set: function (value) {
  42678. SceneLoader._ShowLoadingScreen = value;
  42679. },
  42680. enumerable: true,
  42681. configurable: true
  42682. });
  42683. Object.defineProperty(SceneLoader, "loggingLevel", {
  42684. get: function () {
  42685. return SceneLoader._loggingLevel;
  42686. },
  42687. set: function (value) {
  42688. SceneLoader._loggingLevel = value;
  42689. },
  42690. enumerable: true,
  42691. configurable: true
  42692. });
  42693. SceneLoader._getDefaultPlugin = function () {
  42694. return SceneLoader._registeredPlugins[".babylon"];
  42695. };
  42696. SceneLoader._getPluginForExtension = function (extension) {
  42697. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  42698. if (registeredPlugin) {
  42699. return registeredPlugin;
  42700. }
  42701. return SceneLoader._getDefaultPlugin();
  42702. };
  42703. SceneLoader._getPluginForFilename = function (sceneFilename) {
  42704. if (sceneFilename.name) {
  42705. sceneFilename = sceneFilename.name;
  42706. }
  42707. var dotPosition = sceneFilename.lastIndexOf(".");
  42708. var queryStringPosition = sceneFilename.indexOf("?");
  42709. if (queryStringPosition === -1) {
  42710. queryStringPosition = sceneFilename.length;
  42711. }
  42712. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  42713. return SceneLoader._getPluginForExtension(extension);
  42714. };
  42715. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  42716. SceneLoader._getDirectLoad = function (sceneFilename) {
  42717. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  42718. return sceneFilename.substr(5);
  42719. }
  42720. return null;
  42721. };
  42722. // Public functions
  42723. SceneLoader.GetPluginForExtension = function (extension) {
  42724. return SceneLoader._getPluginForExtension(extension).plugin;
  42725. };
  42726. SceneLoader.RegisterPlugin = function (plugin) {
  42727. if (typeof plugin.extensions === "string") {
  42728. var extension = plugin.extensions;
  42729. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  42730. plugin: plugin,
  42731. isBinary: false
  42732. };
  42733. }
  42734. else {
  42735. var extensions = plugin.extensions;
  42736. Object.keys(extensions).forEach(function (extension) {
  42737. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  42738. plugin: plugin,
  42739. isBinary: extensions[extension].isBinary
  42740. };
  42741. });
  42742. }
  42743. };
  42744. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  42745. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  42746. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  42747. return;
  42748. }
  42749. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  42750. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  42751. return;
  42752. }
  42753. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  42754. var loadingToken = {};
  42755. scene._addPendingData(loadingToken);
  42756. var manifestChecked = function (success) {
  42757. scene.database = database;
  42758. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  42759. var plugin = registeredPlugin.plugin;
  42760. var useArrayBuffer = registeredPlugin.isBinary;
  42761. var importMeshFromData = function (data) {
  42762. var meshes = [];
  42763. var particleSystems = [];
  42764. var skeletons = [];
  42765. if (scene.isDisposed) {
  42766. if (onerror) {
  42767. onerror(scene, 'Scene was disposed before being able to load ' + rootUrl + sceneFilename);
  42768. }
  42769. return;
  42770. }
  42771. try {
  42772. if (plugin.importMesh) {
  42773. var syncedPlugin = plugin;
  42774. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  42775. if (onerror) {
  42776. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  42777. }
  42778. scene._removePendingData(loadingToken);
  42779. return;
  42780. }
  42781. if (onsuccess) {
  42782. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  42783. onsuccess(meshes, particleSystems, skeletons);
  42784. scene._removePendingData(loadingToken);
  42785. }
  42786. }
  42787. else {
  42788. var asyncedPlugin = plugin;
  42789. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  42790. if (onsuccess) {
  42791. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  42792. onsuccess(meshes, particleSystems, skeletons);
  42793. scene._removePendingData(loadingToken);
  42794. }
  42795. }, function () {
  42796. if (onerror) {
  42797. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  42798. }
  42799. scene._removePendingData(loadingToken);
  42800. });
  42801. }
  42802. }
  42803. catch (e) {
  42804. if (onerror) {
  42805. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  42806. }
  42807. scene._removePendingData(loadingToken);
  42808. }
  42809. };
  42810. if (directLoad) {
  42811. importMeshFromData(directLoad);
  42812. return;
  42813. }
  42814. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  42815. importMeshFromData(data);
  42816. }, progressCallBack, database, useArrayBuffer, function () {
  42817. if (onerror) {
  42818. onerror(scene, 'Unable to load file ' + rootUrl + sceneFilename);
  42819. }
  42820. });
  42821. };
  42822. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  42823. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  42824. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  42825. }
  42826. else {
  42827. // If the scene is a data stream or offline support is not enabled, it's a direct load
  42828. manifestChecked(true);
  42829. }
  42830. };
  42831. /**
  42832. * Load a scene
  42833. * @param rootUrl a string that defines the root url for scene and resources
  42834. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  42835. * @param engine is the instance of BABYLON.Engine to use to create the scene
  42836. */
  42837. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  42838. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  42839. };
  42840. /**
  42841. * Append a scene
  42842. * @param rootUrl a string that defines the root url for scene and resources
  42843. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  42844. * @param scene is the instance of BABYLON.Scene to append to
  42845. */
  42846. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  42847. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  42848. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  42849. return;
  42850. }
  42851. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  42852. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  42853. var plugin = registeredPlugin.plugin;
  42854. var useArrayBuffer = registeredPlugin.isBinary;
  42855. var database;
  42856. var loadingToken = {};
  42857. scene._addPendingData(loadingToken);
  42858. if (SceneLoader.ShowLoadingScreen) {
  42859. scene.getEngine().displayLoadingUI();
  42860. }
  42861. var loadSceneFromData = function (data) {
  42862. scene.database = database;
  42863. if (plugin.load) {
  42864. var syncedPlugin = plugin;
  42865. if (!syncedPlugin.load(scene, data, rootUrl)) {
  42866. if (onerror) {
  42867. onerror(scene);
  42868. }
  42869. scene._removePendingData(loadingToken);
  42870. scene.getEngine().hideLoadingUI();
  42871. return;
  42872. }
  42873. if (onsuccess) {
  42874. onsuccess(scene);
  42875. }
  42876. scene._removePendingData(loadingToken);
  42877. }
  42878. else {
  42879. var asyncedPlugin = plugin;
  42880. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  42881. if (onsuccess) {
  42882. onsuccess(scene);
  42883. }
  42884. scene._removePendingData(loadingToken);
  42885. }, function () {
  42886. if (onerror) {
  42887. onerror(scene);
  42888. }
  42889. scene._removePendingData(loadingToken);
  42890. scene.getEngine().hideLoadingUI();
  42891. });
  42892. }
  42893. if (SceneLoader.ShowLoadingScreen) {
  42894. scene.executeWhenReady(function () {
  42895. scene.getEngine().hideLoadingUI();
  42896. });
  42897. }
  42898. };
  42899. var manifestChecked = function (success) {
  42900. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  42901. };
  42902. if (directLoad) {
  42903. loadSceneFromData(directLoad);
  42904. return;
  42905. }
  42906. if (rootUrl.indexOf("file:") === -1) {
  42907. if (scene.getEngine().enableOfflineSupport) {
  42908. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  42909. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  42910. }
  42911. else {
  42912. manifestChecked(true);
  42913. }
  42914. }
  42915. else {
  42916. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  42917. }
  42918. };
  42919. return SceneLoader;
  42920. }());
  42921. // Flags
  42922. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  42923. SceneLoader._ShowLoadingScreen = true;
  42924. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  42925. // Members
  42926. SceneLoader._registeredPlugins = {};
  42927. BABYLON.SceneLoader = SceneLoader;
  42928. ;
  42929. })(BABYLON || (BABYLON = {}));
  42930. //# sourceMappingURL=babylon.sceneLoader.js.map
  42931. var BABYLON;
  42932. (function (BABYLON) {
  42933. var Internals;
  42934. (function (Internals) {
  42935. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  42936. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  42937. var parsedMaterial = parsedData.materials[index];
  42938. if (parsedMaterial.id === id) {
  42939. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  42940. }
  42941. }
  42942. return null;
  42943. };
  42944. var isDescendantOf = function (mesh, names, hierarchyIds) {
  42945. names = (names instanceof Array) ? names : [names];
  42946. for (var i in names) {
  42947. if (mesh.name === names[i]) {
  42948. hierarchyIds.push(mesh.id);
  42949. return true;
  42950. }
  42951. }
  42952. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  42953. hierarchyIds.push(mesh.id);
  42954. return true;
  42955. }
  42956. return false;
  42957. };
  42958. var logOperation = function (operation, producer) {
  42959. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  42960. };
  42961. BABYLON.SceneLoader.RegisterPlugin({
  42962. extensions: ".babylon",
  42963. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  42964. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  42965. // when SceneLoader.debugLogging = true (default), or exception encountered.
  42966. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  42967. // and avoid problems with multiple concurrent .babylon loads.
  42968. var log = "importMesh has failed JSON parse";
  42969. try {
  42970. var parsedData = JSON.parse(data);
  42971. log = "";
  42972. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  42973. var loadedSkeletonsIds = [];
  42974. var loadedMaterialsIds = [];
  42975. var hierarchyIds = [];
  42976. var index;
  42977. var cache;
  42978. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  42979. var parsedMesh = parsedData.meshes[index];
  42980. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  42981. if (meshesNames instanceof Array) {
  42982. // Remove found mesh name from list.
  42983. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  42984. }
  42985. //Geometry?
  42986. if (parsedMesh.geometryId) {
  42987. //does the file contain geometries?
  42988. if (parsedData.geometries) {
  42989. //find the correct geometry and add it to the scene
  42990. var found = false;
  42991. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  42992. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  42993. return;
  42994. }
  42995. else {
  42996. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  42997. if (parsedGeometryData.id === parsedMesh.geometryId) {
  42998. switch (geometryType) {
  42999. case "boxes":
  43000. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  43001. break;
  43002. case "spheres":
  43003. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  43004. break;
  43005. case "cylinders":
  43006. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  43007. break;
  43008. case "toruses":
  43009. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  43010. break;
  43011. case "grounds":
  43012. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  43013. break;
  43014. case "planes":
  43015. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  43016. break;
  43017. case "torusKnots":
  43018. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  43019. break;
  43020. case "vertexData":
  43021. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  43022. break;
  43023. }
  43024. found = true;
  43025. }
  43026. });
  43027. }
  43028. });
  43029. if (!found) {
  43030. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  43031. }
  43032. }
  43033. }
  43034. // Material ?
  43035. if (parsedMesh.materialId) {
  43036. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  43037. if (!materialFound && parsedData.multiMaterials) {
  43038. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  43039. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  43040. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  43041. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  43042. var subMatId = parsedMultiMaterial.materials[matIndex];
  43043. loadedMaterialsIds.push(subMatId);
  43044. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  43045. log += "\n\tMaterial " + mat.toString(fullDetails);
  43046. }
  43047. loadedMaterialsIds.push(parsedMultiMaterial.id);
  43048. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  43049. materialFound = true;
  43050. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  43051. break;
  43052. }
  43053. }
  43054. }
  43055. if (!materialFound) {
  43056. loadedMaterialsIds.push(parsedMesh.materialId);
  43057. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  43058. if (!mat) {
  43059. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  43060. }
  43061. else {
  43062. log += "\n\tMaterial " + mat.toString(fullDetails);
  43063. }
  43064. }
  43065. }
  43066. // Skeleton ?
  43067. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  43068. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  43069. if (!skeletonAlreadyLoaded) {
  43070. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  43071. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  43072. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  43073. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  43074. skeletons.push(skeleton);
  43075. loadedSkeletonsIds.push(parsedSkeleton.id);
  43076. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  43077. }
  43078. }
  43079. }
  43080. }
  43081. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  43082. meshes.push(mesh);
  43083. log += "\n\tMesh " + mesh.toString(fullDetails);
  43084. }
  43085. }
  43086. // Connecting parents
  43087. var currentMesh;
  43088. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  43089. currentMesh = scene.meshes[index];
  43090. if (currentMesh._waitingParentId) {
  43091. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  43092. currentMesh._waitingParentId = undefined;
  43093. }
  43094. }
  43095. // freeze and compute world matrix application
  43096. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  43097. currentMesh = scene.meshes[index];
  43098. if (currentMesh._waitingFreezeWorldMatrix) {
  43099. currentMesh.freezeWorldMatrix();
  43100. currentMesh._waitingFreezeWorldMatrix = undefined;
  43101. }
  43102. else {
  43103. currentMesh.computeWorldMatrix(true);
  43104. }
  43105. }
  43106. // Particles
  43107. if (parsedData.particleSystems) {
  43108. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  43109. var parsedParticleSystem = parsedData.particleSystems[index];
  43110. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  43111. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  43112. }
  43113. }
  43114. }
  43115. return true;
  43116. }
  43117. catch (err) {
  43118. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  43119. log = null;
  43120. throw err;
  43121. }
  43122. finally {
  43123. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  43124. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  43125. }
  43126. }
  43127. },
  43128. load: function (scene, data, rootUrl) {
  43129. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  43130. // when SceneLoader.debugLogging = true (default), or exception encountered.
  43131. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  43132. // and avoid problems with multiple concurrent .babylon loads.
  43133. var log = "importScene has failed JSON parse";
  43134. try {
  43135. var parsedData = JSON.parse(data);
  43136. log = "";
  43137. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  43138. // Scene
  43139. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  43140. scene.autoClear = parsedData.autoClear;
  43141. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  43142. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  43143. if (parsedData.gravity) {
  43144. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  43145. }
  43146. // Fog
  43147. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  43148. scene.fogMode = parsedData.fogMode;
  43149. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  43150. scene.fogStart = parsedData.fogStart;
  43151. scene.fogEnd = parsedData.fogEnd;
  43152. scene.fogDensity = parsedData.fogDensity;
  43153. log += "\tFog mode for scene: ";
  43154. switch (scene.fogMode) {
  43155. // getters not compiling, so using hardcoded
  43156. case 1:
  43157. log += "exp\n";
  43158. break;
  43159. case 2:
  43160. log += "exp2\n";
  43161. break;
  43162. case 3:
  43163. log += "linear\n";
  43164. break;
  43165. }
  43166. }
  43167. //Physics
  43168. if (parsedData.physicsEnabled) {
  43169. var physicsPlugin;
  43170. if (parsedData.physicsEngine === "cannon") {
  43171. physicsPlugin = new BABYLON.CannonJSPlugin();
  43172. }
  43173. else if (parsedData.physicsEngine === "oimo") {
  43174. physicsPlugin = new BABYLON.OimoJSPlugin();
  43175. }
  43176. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  43177. //else - default engine, which is currently oimo
  43178. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  43179. scene.enablePhysics(physicsGravity, physicsPlugin);
  43180. }
  43181. // Metadata
  43182. if (parsedData.metadata !== undefined) {
  43183. scene.metadata = parsedData.metadata;
  43184. }
  43185. //collisions, if defined. otherwise, default is true
  43186. if (parsedData.collisionsEnabled != undefined) {
  43187. scene.collisionsEnabled = parsedData.collisionsEnabled;
  43188. }
  43189. scene.workerCollisions = !!parsedData.workerCollisions;
  43190. var index;
  43191. var cache;
  43192. // Lights
  43193. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  43194. var parsedLight = parsedData.lights[index];
  43195. var light = BABYLON.Light.Parse(parsedLight, scene);
  43196. log += (index === 0 ? "\n\tLights:" : "");
  43197. log += "\n\t\t" + light.toString(fullDetails);
  43198. }
  43199. // Animations
  43200. if (parsedData.animations) {
  43201. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  43202. var parsedAnimation = parsedData.animations[index];
  43203. var animation = BABYLON.Animation.Parse(parsedAnimation);
  43204. scene.animations.push(animation);
  43205. log += (index === 0 ? "\n\tAnimations:" : "");
  43206. log += "\n\t\t" + animation.toString(fullDetails);
  43207. }
  43208. }
  43209. if (parsedData.autoAnimate) {
  43210. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  43211. }
  43212. // Materials
  43213. if (parsedData.materials) {
  43214. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  43215. var parsedMaterial = parsedData.materials[index];
  43216. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  43217. log += (index === 0 ? "\n\tMaterials:" : "");
  43218. log += "\n\t\t" + mat.toString(fullDetails);
  43219. }
  43220. }
  43221. if (parsedData.multiMaterials) {
  43222. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  43223. var parsedMultiMaterial = parsedData.multiMaterials[index];
  43224. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  43225. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  43226. log += "\n\t\t" + mmat.toString(fullDetails);
  43227. }
  43228. }
  43229. // Morph targets
  43230. if (parsedData.morphTargetManagers) {
  43231. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  43232. var managerData = _a[_i];
  43233. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  43234. }
  43235. }
  43236. // Skeletons
  43237. if (parsedData.skeletons) {
  43238. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  43239. var parsedSkeleton = parsedData.skeletons[index];
  43240. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  43241. log += (index === 0 ? "\n\tSkeletons:" : "");
  43242. log += "\n\t\t" + skeleton.toString(fullDetails);
  43243. }
  43244. }
  43245. // Geometries
  43246. var geometries = parsedData.geometries;
  43247. if (geometries) {
  43248. // Boxes
  43249. var boxes = geometries.boxes;
  43250. if (boxes) {
  43251. for (index = 0, cache = boxes.length; index < cache; index++) {
  43252. var parsedBox = boxes[index];
  43253. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  43254. }
  43255. }
  43256. // Spheres
  43257. var spheres = geometries.spheres;
  43258. if (spheres) {
  43259. for (index = 0, cache = spheres.length; index < cache; index++) {
  43260. var parsedSphere = spheres[index];
  43261. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  43262. }
  43263. }
  43264. // Cylinders
  43265. var cylinders = geometries.cylinders;
  43266. if (cylinders) {
  43267. for (index = 0, cache = cylinders.length; index < cache; index++) {
  43268. var parsedCylinder = cylinders[index];
  43269. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  43270. }
  43271. }
  43272. // Toruses
  43273. var toruses = geometries.toruses;
  43274. if (toruses) {
  43275. for (index = 0, cache = toruses.length; index < cache; index++) {
  43276. var parsedTorus = toruses[index];
  43277. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  43278. }
  43279. }
  43280. // Grounds
  43281. var grounds = geometries.grounds;
  43282. if (grounds) {
  43283. for (index = 0, cache = grounds.length; index < cache; index++) {
  43284. var parsedGround = grounds[index];
  43285. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  43286. }
  43287. }
  43288. // Planes
  43289. var planes = geometries.planes;
  43290. if (planes) {
  43291. for (index = 0, cache = planes.length; index < cache; index++) {
  43292. var parsedPlane = planes[index];
  43293. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  43294. }
  43295. }
  43296. // TorusKnots
  43297. var torusKnots = geometries.torusKnots;
  43298. if (torusKnots) {
  43299. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  43300. var parsedTorusKnot = torusKnots[index];
  43301. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  43302. }
  43303. }
  43304. // VertexData
  43305. var vertexData = geometries.vertexData;
  43306. if (vertexData) {
  43307. for (index = 0, cache = vertexData.length; index < cache; index++) {
  43308. var parsedVertexData = vertexData[index];
  43309. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  43310. }
  43311. }
  43312. }
  43313. // Meshes
  43314. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  43315. var parsedMesh = parsedData.meshes[index];
  43316. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  43317. log += (index === 0 ? "\n\tMeshes:" : "");
  43318. log += "\n\t\t" + mesh.toString(fullDetails);
  43319. }
  43320. // Cameras
  43321. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  43322. var parsedCamera = parsedData.cameras[index];
  43323. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  43324. log += (index === 0 ? "\n\tCameras:" : "");
  43325. log += "\n\t\t" + camera.toString(fullDetails);
  43326. }
  43327. if (parsedData.activeCameraID) {
  43328. scene.setActiveCameraByID(parsedData.activeCameraID);
  43329. }
  43330. // Browsing all the graph to connect the dots
  43331. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  43332. var camera = scene.cameras[index];
  43333. if (camera._waitingParentId) {
  43334. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  43335. camera._waitingParentId = undefined;
  43336. }
  43337. }
  43338. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  43339. var light = scene.lights[index];
  43340. if (light._waitingParentId) {
  43341. light.parent = scene.getLastEntryByID(light._waitingParentId);
  43342. light._waitingParentId = undefined;
  43343. }
  43344. }
  43345. // Sounds
  43346. var loadedSounds = [];
  43347. var loadedSound;
  43348. if (BABYLON.AudioEngine && parsedData.sounds) {
  43349. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  43350. var parsedSound = parsedData.sounds[index];
  43351. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43352. if (!parsedSound.url)
  43353. parsedSound.url = parsedSound.name;
  43354. if (!loadedSounds[parsedSound.url]) {
  43355. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  43356. loadedSounds[parsedSound.url] = loadedSound;
  43357. }
  43358. else {
  43359. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  43360. }
  43361. }
  43362. else {
  43363. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  43364. }
  43365. }
  43366. }
  43367. loadedSounds = [];
  43368. // Connect parents & children and parse actions
  43369. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  43370. var mesh = scene.meshes[index];
  43371. if (mesh._waitingParentId) {
  43372. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  43373. mesh._waitingParentId = undefined;
  43374. }
  43375. if (mesh._waitingActions) {
  43376. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  43377. mesh._waitingActions = undefined;
  43378. }
  43379. }
  43380. // freeze world matrix application
  43381. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  43382. var currentMesh = scene.meshes[index];
  43383. if (currentMesh._waitingFreezeWorldMatrix) {
  43384. currentMesh.freezeWorldMatrix();
  43385. currentMesh._waitingFreezeWorldMatrix = undefined;
  43386. }
  43387. else {
  43388. currentMesh.computeWorldMatrix(true);
  43389. }
  43390. }
  43391. // Particles Systems
  43392. if (parsedData.particleSystems) {
  43393. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  43394. var parsedParticleSystem = parsedData.particleSystems[index];
  43395. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  43396. }
  43397. }
  43398. // Lens flares
  43399. if (parsedData.lensFlareSystems) {
  43400. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  43401. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  43402. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  43403. }
  43404. }
  43405. // Shadows
  43406. if (parsedData.shadowGenerators) {
  43407. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  43408. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  43409. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  43410. }
  43411. }
  43412. // Lights exclusions / inclusions
  43413. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  43414. var light = scene.lights[index];
  43415. // Excluded check
  43416. if (light._excludedMeshesIds.length > 0) {
  43417. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  43418. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  43419. if (excludedMesh) {
  43420. light.excludedMeshes.push(excludedMesh);
  43421. }
  43422. }
  43423. light._excludedMeshesIds = [];
  43424. }
  43425. // Included check
  43426. if (light._includedOnlyMeshesIds.length > 0) {
  43427. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  43428. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  43429. if (includedOnlyMesh) {
  43430. light.includedOnlyMeshes.push(includedOnlyMesh);
  43431. }
  43432. }
  43433. light._includedOnlyMeshesIds = [];
  43434. }
  43435. }
  43436. // Actions (scene)
  43437. if (parsedData.actions) {
  43438. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  43439. }
  43440. // Finish
  43441. return true;
  43442. }
  43443. catch (err) {
  43444. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  43445. log = null;
  43446. throw err;
  43447. }
  43448. finally {
  43449. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  43450. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  43451. }
  43452. }
  43453. }
  43454. });
  43455. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43456. })(BABYLON || (BABYLON = {}));
  43457. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  43458. var BABYLON;
  43459. (function (BABYLON) {
  43460. var FilesInput = (function () {
  43461. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  43462. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  43463. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  43464. this._engine = p_engine;
  43465. this._canvas = p_canvas;
  43466. this._currentScene = p_scene;
  43467. this._sceneLoadedCallback = p_sceneLoadedCallback;
  43468. this._progressCallback = p_progressCallback;
  43469. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  43470. this._textureLoadingCallback = p_textureLoadingCallback;
  43471. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  43472. }
  43473. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  43474. var _this = this;
  43475. if (p_elementToMonitor) {
  43476. this._elementToMonitor = p_elementToMonitor;
  43477. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  43478. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  43479. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  43480. }
  43481. };
  43482. FilesInput.prototype.renderFunction = function () {
  43483. if (this._additionnalRenderLoopLogicCallback) {
  43484. this._additionnalRenderLoopLogicCallback();
  43485. }
  43486. if (this._currentScene) {
  43487. if (this._textureLoadingCallback) {
  43488. var remaining = this._currentScene.getWaitingItemsCount();
  43489. if (remaining > 0) {
  43490. this._textureLoadingCallback(remaining);
  43491. }
  43492. }
  43493. this._currentScene.render();
  43494. }
  43495. };
  43496. FilesInput.prototype.drag = function (e) {
  43497. e.stopPropagation();
  43498. e.preventDefault();
  43499. };
  43500. FilesInput.prototype.drop = function (eventDrop) {
  43501. eventDrop.stopPropagation();
  43502. eventDrop.preventDefault();
  43503. this.loadFiles(eventDrop);
  43504. };
  43505. FilesInput.prototype.loadFiles = function (event) {
  43506. if (this._startingProcessingFilesCallback)
  43507. this._startingProcessingFilesCallback();
  43508. // Handling data transfer via drag'n'drop
  43509. if (event && event.dataTransfer && event.dataTransfer.files) {
  43510. this._filesToLoad = event.dataTransfer.files;
  43511. }
  43512. // Handling files from input files
  43513. if (event && event.target && event.target.files) {
  43514. this._filesToLoad = event.target.files;
  43515. }
  43516. if (this._filesToLoad && this._filesToLoad.length > 0) {
  43517. for (var i = 0; i < this._filesToLoad.length; i++) {
  43518. var name_1 = this._filesToLoad[i].name.toLowerCase();
  43519. var extension = name_1.split('.').pop();
  43520. var type = this._filesToLoad[i].type;
  43521. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  43522. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  43523. this._sceneFileToLoad = this._filesToLoad[i];
  43524. }
  43525. else {
  43526. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  43527. }
  43528. }
  43529. this.reload();
  43530. }
  43531. };
  43532. FilesInput.prototype.reload = function () {
  43533. var _this = this;
  43534. var that = this;
  43535. // If a ".babylon" file has been provided
  43536. if (this._sceneFileToLoad) {
  43537. if (this._currentScene) {
  43538. if (BABYLON.Tools.errorsCount > 0) {
  43539. BABYLON.Tools.ClearLogCache();
  43540. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  43541. }
  43542. this._engine.stopRenderLoop();
  43543. this._currentScene.dispose();
  43544. }
  43545. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  43546. that._currentScene = newScene;
  43547. // Wait for textures and shaders to be ready
  43548. that._currentScene.executeWhenReady(function () {
  43549. if (that._sceneLoadedCallback) {
  43550. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  43551. }
  43552. that._engine.runRenderLoop(function () { that.renderFunction(); });
  43553. });
  43554. }, function (progress) {
  43555. if (_this._progressCallback) {
  43556. _this._progressCallback(progress);
  43557. }
  43558. });
  43559. }
  43560. else {
  43561. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  43562. }
  43563. };
  43564. return FilesInput;
  43565. }());
  43566. FilesInput.FilesToLoad = new Array();
  43567. BABYLON.FilesInput = FilesInput;
  43568. })(BABYLON || (BABYLON = {}));
  43569. //# sourceMappingURL=babylon.filesInput.js.map
  43570. var BABYLON;
  43571. (function (BABYLON) {
  43572. /**
  43573. * This class implement a typical dictionary using a string as key and the generic type T as value.
  43574. * The underlying implementation relies on an associative array to ensure the best performances.
  43575. * The value can be anything including 'null' but except 'undefined'
  43576. */
  43577. var StringDictionary = (function () {
  43578. function StringDictionary() {
  43579. this._count = 0;
  43580. this._data = {};
  43581. }
  43582. /**
  43583. * This will clear this dictionary and copy the content from the 'source' one.
  43584. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  43585. * @param source the dictionary to take the content from and copy to this dictionary
  43586. */
  43587. StringDictionary.prototype.copyFrom = function (source) {
  43588. var _this = this;
  43589. this.clear();
  43590. source.forEach(function (t, v) { return _this.add(t, v); });
  43591. };
  43592. /**
  43593. * Get a value based from its key
  43594. * @param key the given key to get the matching value from
  43595. * @return the value if found, otherwise undefined is returned
  43596. */
  43597. StringDictionary.prototype.get = function (key) {
  43598. var val = this._data[key];
  43599. if (val !== undefined) {
  43600. return val;
  43601. }
  43602. return undefined;
  43603. };
  43604. /**
  43605. * Get a value from its key or add it if it doesn't exist.
  43606. * This method will ensure you that a given key/data will be present in the dictionary.
  43607. * @param key the given key to get the matching value from
  43608. * @param factory the factory that will create the value if the key is not present in the dictionary.
  43609. * The factory will only be invoked if there's no data for the given key.
  43610. * @return the value corresponding to the key.
  43611. */
  43612. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  43613. var val = this.get(key);
  43614. if (val !== undefined) {
  43615. return val;
  43616. }
  43617. val = factory(key);
  43618. if (val) {
  43619. this.add(key, val);
  43620. }
  43621. return val;
  43622. };
  43623. /**
  43624. * Get a value from its key if present in the dictionary otherwise add it
  43625. * @param key the key to get the value from
  43626. * @param val if there's no such key/value pair in the dictionary add it with this value
  43627. * @return the value corresponding to the key
  43628. */
  43629. StringDictionary.prototype.getOrAdd = function (key, val) {
  43630. var curVal = this.get(key);
  43631. if (curVal !== undefined) {
  43632. return curVal;
  43633. }
  43634. this.add(key, val);
  43635. return val;
  43636. };
  43637. /**
  43638. * Check if there's a given key in the dictionary
  43639. * @param key the key to check for
  43640. * @return true if the key is present, false otherwise
  43641. */
  43642. StringDictionary.prototype.contains = function (key) {
  43643. return this._data[key] !== undefined;
  43644. };
  43645. /**
  43646. * Add a new key and its corresponding value
  43647. * @param key the key to add
  43648. * @param value the value corresponding to the key
  43649. * @return true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary
  43650. */
  43651. StringDictionary.prototype.add = function (key, value) {
  43652. if (this._data[key] !== undefined) {
  43653. return false;
  43654. }
  43655. this._data[key] = value;
  43656. ++this._count;
  43657. return true;
  43658. };
  43659. StringDictionary.prototype.set = function (key, value) {
  43660. if (this._data[key] === undefined) {
  43661. return false;
  43662. }
  43663. this._data[key] = value;
  43664. return true;
  43665. };
  43666. /**
  43667. * Get the element of the given key and remove it from the dictionary
  43668. * @param key
  43669. */
  43670. StringDictionary.prototype.getAndRemove = function (key) {
  43671. var val = this.get(key);
  43672. if (val !== undefined) {
  43673. delete this._data[key];
  43674. --this._count;
  43675. return val;
  43676. }
  43677. return null;
  43678. };
  43679. /**
  43680. * Remove a key/value from the dictionary.
  43681. * @param key the key to remove
  43682. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  43683. */
  43684. StringDictionary.prototype.remove = function (key) {
  43685. if (this.contains(key)) {
  43686. delete this._data[key];
  43687. --this._count;
  43688. return true;
  43689. }
  43690. return false;
  43691. };
  43692. /**
  43693. * Clear the whole content of the dictionary
  43694. */
  43695. StringDictionary.prototype.clear = function () {
  43696. this._data = {};
  43697. this._count = 0;
  43698. };
  43699. Object.defineProperty(StringDictionary.prototype, "count", {
  43700. get: function () {
  43701. return this._count;
  43702. },
  43703. enumerable: true,
  43704. configurable: true
  43705. });
  43706. /**
  43707. * Execute a callback on each key/val of the dictionary.
  43708. * Note that you can remove any element in this dictionary in the callback implementation
  43709. * @param callback the callback to execute on a given key/value pair
  43710. */
  43711. StringDictionary.prototype.forEach = function (callback) {
  43712. for (var cur in this._data) {
  43713. var val = this._data[cur];
  43714. callback(cur, val);
  43715. }
  43716. };
  43717. /**
  43718. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  43719. * If the callback returns null or undefined the method will iterate to the next key/value pair
  43720. * Note that you can remove any element in this dictionary in the callback implementation
  43721. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  43722. */
  43723. StringDictionary.prototype.first = function (callback) {
  43724. for (var cur in this._data) {
  43725. var val = this._data[cur];
  43726. var res = callback(cur, val);
  43727. if (res) {
  43728. return res;
  43729. }
  43730. }
  43731. return null;
  43732. };
  43733. return StringDictionary;
  43734. }());
  43735. BABYLON.StringDictionary = StringDictionary;
  43736. })(BABYLON || (BABYLON = {}));
  43737. //# sourceMappingURL=babylon.stringDictionary.js.map
  43738. var BABYLON;
  43739. (function (BABYLON) {
  43740. var Tags = (function () {
  43741. function Tags() {
  43742. }
  43743. Tags.EnableFor = function (obj) {
  43744. obj._tags = obj._tags || {};
  43745. obj.hasTags = function () {
  43746. return Tags.HasTags(obj);
  43747. };
  43748. obj.addTags = function (tagsString) {
  43749. return Tags.AddTagsTo(obj, tagsString);
  43750. };
  43751. obj.removeTags = function (tagsString) {
  43752. return Tags.RemoveTagsFrom(obj, tagsString);
  43753. };
  43754. obj.matchesTagsQuery = function (tagsQuery) {
  43755. return Tags.MatchesQuery(obj, tagsQuery);
  43756. };
  43757. };
  43758. Tags.DisableFor = function (obj) {
  43759. delete obj._tags;
  43760. delete obj.hasTags;
  43761. delete obj.addTags;
  43762. delete obj.removeTags;
  43763. delete obj.matchesTagsQuery;
  43764. };
  43765. Tags.HasTags = function (obj) {
  43766. if (!obj._tags) {
  43767. return false;
  43768. }
  43769. return !BABYLON.Tools.IsEmpty(obj._tags);
  43770. };
  43771. Tags.GetTags = function (obj, asString) {
  43772. if (asString === void 0) { asString = true; }
  43773. if (!obj._tags) {
  43774. return null;
  43775. }
  43776. if (asString) {
  43777. var tagsArray = [];
  43778. for (var tag in obj._tags) {
  43779. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  43780. tagsArray.push(tag);
  43781. }
  43782. }
  43783. return tagsArray.join(" ");
  43784. }
  43785. else {
  43786. return obj._tags;
  43787. }
  43788. };
  43789. // the tags 'true' and 'false' are reserved and cannot be used as tags
  43790. // a tag cannot start with '||', '&&', and '!'
  43791. // it cannot contain whitespaces
  43792. Tags.AddTagsTo = function (obj, tagsString) {
  43793. if (!tagsString) {
  43794. return;
  43795. }
  43796. if (typeof tagsString !== "string") {
  43797. return;
  43798. }
  43799. var tags = tagsString.split(" ");
  43800. tags.forEach(function (tag, index, array) {
  43801. Tags._AddTagTo(obj, tag);
  43802. });
  43803. };
  43804. Tags._AddTagTo = function (obj, tag) {
  43805. tag = tag.trim();
  43806. if (tag === "" || tag === "true" || tag === "false") {
  43807. return;
  43808. }
  43809. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  43810. return;
  43811. }
  43812. Tags.EnableFor(obj);
  43813. obj._tags[tag] = true;
  43814. };
  43815. Tags.RemoveTagsFrom = function (obj, tagsString) {
  43816. if (!Tags.HasTags(obj)) {
  43817. return;
  43818. }
  43819. var tags = tagsString.split(" ");
  43820. for (var t in tags) {
  43821. Tags._RemoveTagFrom(obj, tags[t]);
  43822. }
  43823. };
  43824. Tags._RemoveTagFrom = function (obj, tag) {
  43825. delete obj._tags[tag];
  43826. };
  43827. Tags.MatchesQuery = function (obj, tagsQuery) {
  43828. if (tagsQuery === undefined) {
  43829. return true;
  43830. }
  43831. if (tagsQuery === "") {
  43832. return Tags.HasTags(obj);
  43833. }
  43834. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  43835. };
  43836. return Tags;
  43837. }());
  43838. BABYLON.Tags = Tags;
  43839. })(BABYLON || (BABYLON = {}));
  43840. //# sourceMappingURL=babylon.tags.js.map
  43841. var BABYLON;
  43842. (function (BABYLON) {
  43843. var Internals;
  43844. (function (Internals) {
  43845. var AndOrNotEvaluator = (function () {
  43846. function AndOrNotEvaluator() {
  43847. }
  43848. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  43849. if (!query.match(/\([^\(\)]*\)/g)) {
  43850. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  43851. }
  43852. else {
  43853. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  43854. // remove parenthesis
  43855. r = r.slice(1, r.length - 1);
  43856. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  43857. });
  43858. }
  43859. if (query === "true") {
  43860. return true;
  43861. }
  43862. if (query === "false") {
  43863. return false;
  43864. }
  43865. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  43866. };
  43867. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  43868. evaluateCallback = evaluateCallback || (function (r) {
  43869. return r === "true" ? true : false;
  43870. });
  43871. var result;
  43872. var or = parenthesisContent.split("||");
  43873. for (var i in or) {
  43874. if (or.hasOwnProperty(i)) {
  43875. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  43876. var and = ori.split("&&");
  43877. if (and.length > 1) {
  43878. for (var j = 0; j < and.length; ++j) {
  43879. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  43880. if (andj !== "true" && andj !== "false") {
  43881. if (andj[0] === "!") {
  43882. result = !evaluateCallback(andj.substring(1));
  43883. }
  43884. else {
  43885. result = evaluateCallback(andj);
  43886. }
  43887. }
  43888. else {
  43889. result = andj === "true" ? true : false;
  43890. }
  43891. if (!result) {
  43892. ori = "false";
  43893. break;
  43894. }
  43895. }
  43896. }
  43897. if (result || ori === "true") {
  43898. result = true;
  43899. break;
  43900. }
  43901. // result equals false (or undefined)
  43902. if (ori !== "true" && ori !== "false") {
  43903. if (ori[0] === "!") {
  43904. result = !evaluateCallback(ori.substring(1));
  43905. }
  43906. else {
  43907. result = evaluateCallback(ori);
  43908. }
  43909. }
  43910. else {
  43911. result = ori === "true" ? true : false;
  43912. }
  43913. }
  43914. }
  43915. // the whole parenthesis scope is replaced by 'true' or 'false'
  43916. return result ? "true" : "false";
  43917. };
  43918. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  43919. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  43920. // remove whitespaces
  43921. r = r.replace(/[\s]/g, function () { return ""; });
  43922. return r.length % 2 ? "!" : "";
  43923. });
  43924. booleanString = booleanString.trim();
  43925. if (booleanString === "!true") {
  43926. booleanString = "false";
  43927. }
  43928. else if (booleanString === "!false") {
  43929. booleanString = "true";
  43930. }
  43931. return booleanString;
  43932. };
  43933. return AndOrNotEvaluator;
  43934. }());
  43935. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  43936. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43937. })(BABYLON || (BABYLON = {}));
  43938. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  43939. var BABYLON;
  43940. (function (BABYLON) {
  43941. var Database = (function () {
  43942. function Database(urlToScene, callbackManifestChecked) {
  43943. // Handling various flavors of prefixed version of IndexedDB
  43944. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  43945. this.callbackManifestChecked = callbackManifestChecked;
  43946. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  43947. this.db = null;
  43948. this.enableSceneOffline = false;
  43949. this.enableTexturesOffline = false;
  43950. this.manifestVersionFound = 0;
  43951. this.mustUpdateRessources = false;
  43952. this.hasReachedQuota = false;
  43953. if (!Database.IDBStorageEnabled) {
  43954. this.callbackManifestChecked(true);
  43955. }
  43956. else {
  43957. this.checkManifestFile();
  43958. }
  43959. }
  43960. Database.prototype.checkManifestFile = function () {
  43961. var _this = this;
  43962. function noManifestFile() {
  43963. that.enableSceneOffline = false;
  43964. that.enableTexturesOffline = false;
  43965. that.callbackManifestChecked(false);
  43966. }
  43967. var that = this;
  43968. var timeStampUsed = false;
  43969. var manifestURL = this.currentSceneUrl + ".manifest";
  43970. var xhr = new XMLHttpRequest();
  43971. if (navigator.onLine) {
  43972. // Adding a timestamp to by-pass browsers' cache
  43973. timeStampUsed = true;
  43974. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  43975. }
  43976. xhr.open("GET", manifestURL, true);
  43977. xhr.addEventListener("load", function () {
  43978. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  43979. try {
  43980. var manifestFile = JSON.parse(xhr.response);
  43981. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  43982. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  43983. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  43984. _this.manifestVersionFound = manifestFile.version;
  43985. }
  43986. if (_this.callbackManifestChecked) {
  43987. _this.callbackManifestChecked(true);
  43988. }
  43989. }
  43990. catch (ex) {
  43991. noManifestFile();
  43992. }
  43993. }
  43994. else {
  43995. noManifestFile();
  43996. }
  43997. }, false);
  43998. xhr.addEventListener("error", function (event) {
  43999. if (timeStampUsed) {
  44000. timeStampUsed = false;
  44001. // Let's retry without the timeStamp
  44002. // It could fail when coupled with HTML5 Offline API
  44003. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  44004. xhr.open("GET", retryManifestURL, true);
  44005. xhr.send();
  44006. }
  44007. else {
  44008. noManifestFile();
  44009. }
  44010. }, false);
  44011. try {
  44012. xhr.send();
  44013. }
  44014. catch (ex) {
  44015. BABYLON.Tools.Error("Error on XHR send request.");
  44016. that.callbackManifestChecked(false);
  44017. }
  44018. };
  44019. Database.prototype.openAsync = function (successCallback, errorCallback) {
  44020. var _this = this;
  44021. function handleError() {
  44022. that.isSupported = false;
  44023. if (errorCallback)
  44024. errorCallback();
  44025. }
  44026. var that = this;
  44027. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  44028. // Your browser doesn't support IndexedDB
  44029. this.isSupported = false;
  44030. if (errorCallback)
  44031. errorCallback();
  44032. }
  44033. else {
  44034. // If the DB hasn't been opened or created yet
  44035. if (!this.db) {
  44036. this.hasReachedQuota = false;
  44037. this.isSupported = true;
  44038. var request = this.idbFactory.open("babylonjs", 1);
  44039. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  44040. request.onerror = function (event) {
  44041. handleError();
  44042. };
  44043. // executes when a version change transaction cannot complete due to other active transactions
  44044. request.onblocked = function (event) {
  44045. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  44046. handleError();
  44047. };
  44048. // DB has been opened successfully
  44049. request.onsuccess = function (event) {
  44050. _this.db = request.result;
  44051. successCallback();
  44052. };
  44053. // Initialization of the DB. Creating Scenes & Textures stores
  44054. request.onupgradeneeded = function (event) {
  44055. _this.db = (event.target).result;
  44056. try {
  44057. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  44058. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  44059. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  44060. }
  44061. catch (ex) {
  44062. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  44063. handleError();
  44064. }
  44065. };
  44066. }
  44067. else {
  44068. if (successCallback)
  44069. successCallback();
  44070. }
  44071. }
  44072. };
  44073. Database.prototype.loadImageFromDB = function (url, image) {
  44074. var _this = this;
  44075. var completeURL = Database.ReturnFullUrlLocation(url);
  44076. var saveAndLoadImage = function () {
  44077. if (!_this.hasReachedQuota && _this.db !== null) {
  44078. // the texture is not yet in the DB, let's try to save it
  44079. _this._saveImageIntoDBAsync(completeURL, image);
  44080. }
  44081. else {
  44082. image.src = url;
  44083. }
  44084. };
  44085. if (!this.mustUpdateRessources) {
  44086. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  44087. }
  44088. else {
  44089. saveAndLoadImage();
  44090. }
  44091. };
  44092. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  44093. if (this.isSupported && this.db !== null) {
  44094. var texture;
  44095. var transaction = this.db.transaction(["textures"]);
  44096. transaction.onabort = function (event) {
  44097. image.src = url;
  44098. };
  44099. transaction.oncomplete = function (event) {
  44100. var blobTextureURL;
  44101. if (texture) {
  44102. var URL = window.URL || window.webkitURL;
  44103. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  44104. image.onerror = function () {
  44105. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  44106. image.src = url;
  44107. };
  44108. image.src = blobTextureURL;
  44109. }
  44110. else {
  44111. notInDBCallback();
  44112. }
  44113. };
  44114. var getRequest = transaction.objectStore("textures").get(url);
  44115. getRequest.onsuccess = function (event) {
  44116. texture = (event.target).result;
  44117. };
  44118. getRequest.onerror = function (event) {
  44119. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  44120. image.src = url;
  44121. };
  44122. }
  44123. else {
  44124. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  44125. image.src = url;
  44126. }
  44127. };
  44128. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  44129. var _this = this;
  44130. if (this.isSupported) {
  44131. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  44132. var generateBlobUrl = function () {
  44133. var blobTextureURL;
  44134. if (blob) {
  44135. var URL = window.URL || window.webkitURL;
  44136. try {
  44137. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  44138. }
  44139. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  44140. catch (ex) {
  44141. blobTextureURL = URL.createObjectURL(blob);
  44142. }
  44143. }
  44144. image.src = blobTextureURL;
  44145. };
  44146. if (Database.IsUASupportingBlobStorage) {
  44147. var xhr = new XMLHttpRequest(), blob;
  44148. xhr.open("GET", url, true);
  44149. xhr.responseType = "blob";
  44150. xhr.addEventListener("load", function () {
  44151. if (xhr.status === 200) {
  44152. // Blob as response (XHR2)
  44153. blob = xhr.response;
  44154. var transaction = _this.db.transaction(["textures"], "readwrite");
  44155. // the transaction could abort because of a QuotaExceededError error
  44156. transaction.onabort = function (event) {
  44157. try {
  44158. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  44159. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  44160. _this.hasReachedQuota = true;
  44161. }
  44162. }
  44163. catch (ex) { }
  44164. generateBlobUrl();
  44165. };
  44166. transaction.oncomplete = function (event) {
  44167. generateBlobUrl();
  44168. };
  44169. var newTexture = { textureUrl: url, data: blob };
  44170. try {
  44171. // Put the blob into the dabase
  44172. var addRequest = transaction.objectStore("textures").put(newTexture);
  44173. addRequest.onsuccess = function (event) {
  44174. };
  44175. addRequest.onerror = function (event) {
  44176. generateBlobUrl();
  44177. };
  44178. }
  44179. catch (ex) {
  44180. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  44181. if (ex.code === 25) {
  44182. Database.IsUASupportingBlobStorage = false;
  44183. }
  44184. image.src = url;
  44185. }
  44186. }
  44187. else {
  44188. image.src = url;
  44189. }
  44190. }, false);
  44191. xhr.addEventListener("error", function (event) {
  44192. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  44193. image.src = url;
  44194. }, false);
  44195. xhr.send();
  44196. }
  44197. else {
  44198. image.src = url;
  44199. }
  44200. }
  44201. else {
  44202. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  44203. image.src = url;
  44204. }
  44205. };
  44206. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  44207. var _this = this;
  44208. var updateVersion = function (event) {
  44209. // the version is not yet in the DB or we need to update it
  44210. _this._saveVersionIntoDBAsync(url, versionLoaded);
  44211. };
  44212. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  44213. };
  44214. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  44215. var _this = this;
  44216. if (this.isSupported) {
  44217. var version;
  44218. try {
  44219. var transaction = this.db.transaction(["versions"]);
  44220. transaction.oncomplete = function (event) {
  44221. if (version) {
  44222. // If the version in the JSON file is > than the version in DB
  44223. if (_this.manifestVersionFound > version.data) {
  44224. _this.mustUpdateRessources = true;
  44225. updateInDBCallback();
  44226. }
  44227. else {
  44228. callback(version.data);
  44229. }
  44230. }
  44231. else {
  44232. _this.mustUpdateRessources = true;
  44233. updateInDBCallback();
  44234. }
  44235. };
  44236. transaction.onabort = function (event) {
  44237. callback(-1);
  44238. };
  44239. var getRequest = transaction.objectStore("versions").get(url);
  44240. getRequest.onsuccess = function (event) {
  44241. version = (event.target).result;
  44242. };
  44243. getRequest.onerror = function (event) {
  44244. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  44245. callback(-1);
  44246. };
  44247. }
  44248. catch (ex) {
  44249. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  44250. callback(-1);
  44251. }
  44252. }
  44253. else {
  44254. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  44255. callback(-1);
  44256. }
  44257. };
  44258. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  44259. var _this = this;
  44260. if (this.isSupported && !this.hasReachedQuota) {
  44261. try {
  44262. // Open a transaction to the database
  44263. var transaction = this.db.transaction(["versions"], "readwrite");
  44264. // the transaction could abort because of a QuotaExceededError error
  44265. transaction.onabort = function (event) {
  44266. try {
  44267. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  44268. _this.hasReachedQuota = true;
  44269. }
  44270. }
  44271. catch (ex) { }
  44272. callback(-1);
  44273. };
  44274. transaction.oncomplete = function (event) {
  44275. callback(_this.manifestVersionFound);
  44276. };
  44277. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  44278. // Put the scene into the database
  44279. var addRequest = transaction.objectStore("versions").put(newVersion);
  44280. addRequest.onsuccess = function (event) {
  44281. };
  44282. addRequest.onerror = function (event) {
  44283. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  44284. };
  44285. }
  44286. catch (ex) {
  44287. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  44288. callback(-1);
  44289. }
  44290. }
  44291. else {
  44292. callback(-1);
  44293. }
  44294. };
  44295. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  44296. var _this = this;
  44297. var completeUrl = Database.ReturnFullUrlLocation(url);
  44298. var saveAndLoadFile = function (event) {
  44299. // the scene is not yet in the DB, let's try to save it
  44300. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  44301. };
  44302. this._checkVersionFromDB(completeUrl, function (version) {
  44303. if (version !== -1) {
  44304. if (!_this.mustUpdateRessources) {
  44305. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  44306. }
  44307. else {
  44308. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  44309. }
  44310. }
  44311. else {
  44312. errorCallback();
  44313. }
  44314. });
  44315. };
  44316. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  44317. if (this.isSupported) {
  44318. var targetStore;
  44319. if (url.indexOf(".babylon") !== -1) {
  44320. targetStore = "scenes";
  44321. }
  44322. else {
  44323. targetStore = "textures";
  44324. }
  44325. var file;
  44326. var transaction = this.db.transaction([targetStore]);
  44327. transaction.oncomplete = function (event) {
  44328. if (file) {
  44329. callback(file.data);
  44330. }
  44331. else {
  44332. notInDBCallback();
  44333. }
  44334. };
  44335. transaction.onabort = function (event) {
  44336. notInDBCallback();
  44337. };
  44338. var getRequest = transaction.objectStore(targetStore).get(url);
  44339. getRequest.onsuccess = function (event) {
  44340. file = (event.target).result;
  44341. };
  44342. getRequest.onerror = function (event) {
  44343. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  44344. notInDBCallback();
  44345. };
  44346. }
  44347. else {
  44348. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  44349. callback();
  44350. }
  44351. };
  44352. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  44353. var _this = this;
  44354. if (this.isSupported) {
  44355. var targetStore;
  44356. if (url.indexOf(".babylon") !== -1) {
  44357. targetStore = "scenes";
  44358. }
  44359. else {
  44360. targetStore = "textures";
  44361. }
  44362. // Create XHR
  44363. var xhr = new XMLHttpRequest(), fileData;
  44364. xhr.open("GET", url, true);
  44365. if (useArrayBuffer) {
  44366. xhr.responseType = "arraybuffer";
  44367. }
  44368. xhr.onprogress = progressCallback;
  44369. xhr.addEventListener("load", function () {
  44370. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  44371. // Blob as response (XHR2)
  44372. //fileData = xhr.responseText;
  44373. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  44374. if (!_this.hasReachedQuota) {
  44375. // Open a transaction to the database
  44376. var transaction = _this.db.transaction([targetStore], "readwrite");
  44377. // the transaction could abort because of a QuotaExceededError error
  44378. transaction.onabort = function (event) {
  44379. try {
  44380. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  44381. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  44382. _this.hasReachedQuota = true;
  44383. }
  44384. }
  44385. catch (ex) { }
  44386. callback(fileData);
  44387. };
  44388. transaction.oncomplete = function (event) {
  44389. callback(fileData);
  44390. };
  44391. var newFile;
  44392. if (targetStore === "scenes") {
  44393. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  44394. }
  44395. else {
  44396. newFile = { textureUrl: url, data: fileData };
  44397. }
  44398. try {
  44399. // Put the scene into the database
  44400. var addRequest = transaction.objectStore(targetStore).put(newFile);
  44401. addRequest.onsuccess = function (event) {
  44402. };
  44403. addRequest.onerror = function (event) {
  44404. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  44405. };
  44406. }
  44407. catch (ex) {
  44408. callback(fileData);
  44409. }
  44410. }
  44411. else {
  44412. callback(fileData);
  44413. }
  44414. }
  44415. else {
  44416. callback();
  44417. }
  44418. }, false);
  44419. xhr.addEventListener("error", function (event) {
  44420. BABYLON.Tools.Error("error on XHR request.");
  44421. callback();
  44422. }, false);
  44423. xhr.send();
  44424. }
  44425. else {
  44426. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  44427. callback();
  44428. }
  44429. };
  44430. return Database;
  44431. }());
  44432. Database.IsUASupportingBlobStorage = true;
  44433. Database.IDBStorageEnabled = true;
  44434. Database.parseURL = function (url) {
  44435. var a = document.createElement('a');
  44436. a.href = url;
  44437. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  44438. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  44439. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  44440. return absLocation;
  44441. };
  44442. Database.ReturnFullUrlLocation = function (url) {
  44443. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  44444. return (Database.parseURL(window.location.href) + url);
  44445. }
  44446. else {
  44447. return url;
  44448. }
  44449. };
  44450. BABYLON.Database = Database;
  44451. })(BABYLON || (BABYLON = {}));
  44452. //# sourceMappingURL=babylon.database.js.map
  44453. var BABYLON;
  44454. (function (BABYLON) {
  44455. var FresnelParameters = (function () {
  44456. function FresnelParameters() {
  44457. this._isEnabled = true;
  44458. this.leftColor = BABYLON.Color3.White();
  44459. this.rightColor = BABYLON.Color3.Black();
  44460. this.bias = 0;
  44461. this.power = 1;
  44462. }
  44463. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  44464. get: function () {
  44465. return this._isEnabled;
  44466. },
  44467. set: function (value) {
  44468. if (this._isEnabled === value) {
  44469. return;
  44470. }
  44471. this._isEnabled = value;
  44472. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44473. },
  44474. enumerable: true,
  44475. configurable: true
  44476. });
  44477. FresnelParameters.prototype.clone = function () {
  44478. var newFresnelParameters = new FresnelParameters();
  44479. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  44480. return newFresnelParameters;
  44481. };
  44482. FresnelParameters.prototype.serialize = function () {
  44483. var serializationObject = {};
  44484. serializationObject.isEnabled = this.isEnabled;
  44485. serializationObject.leftColor = this.leftColor;
  44486. serializationObject.rightColor = this.rightColor;
  44487. serializationObject.bias = this.bias;
  44488. serializationObject.power = this.power;
  44489. return serializationObject;
  44490. };
  44491. FresnelParameters.Parse = function (parsedFresnelParameters) {
  44492. var fresnelParameters = new FresnelParameters();
  44493. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  44494. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  44495. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  44496. fresnelParameters.bias = parsedFresnelParameters.bias;
  44497. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  44498. return fresnelParameters;
  44499. };
  44500. return FresnelParameters;
  44501. }());
  44502. BABYLON.FresnelParameters = FresnelParameters;
  44503. })(BABYLON || (BABYLON = {}));
  44504. //# sourceMappingURL=babylon.fresnelParameters.js.map
  44505. var BABYLON;
  44506. (function (BABYLON) {
  44507. var MultiMaterial = (function (_super) {
  44508. __extends(MultiMaterial, _super);
  44509. function MultiMaterial(name, scene) {
  44510. var _this = _super.call(this, name, scene, true) || this;
  44511. _this.subMaterials = new Array();
  44512. scene.multiMaterials.push(_this);
  44513. return _this;
  44514. }
  44515. // Properties
  44516. MultiMaterial.prototype.getSubMaterial = function (index) {
  44517. if (index < 0 || index >= this.subMaterials.length) {
  44518. return this.getScene().defaultMaterial;
  44519. }
  44520. return this.subMaterials[index];
  44521. };
  44522. // Methods
  44523. MultiMaterial.prototype.getClassName = function () {
  44524. return "MultiMaterial";
  44525. };
  44526. MultiMaterial.prototype.isReady = function (mesh) {
  44527. for (var index = 0; index < this.subMaterials.length; index++) {
  44528. var subMaterial = this.subMaterials[index];
  44529. if (subMaterial) {
  44530. if (!this.subMaterials[index].isReady(mesh)) {
  44531. return false;
  44532. }
  44533. }
  44534. }
  44535. return true;
  44536. };
  44537. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  44538. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  44539. for (var index = 0; index < this.subMaterials.length; index++) {
  44540. var subMaterial = null;
  44541. if (cloneChildren) {
  44542. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  44543. }
  44544. else {
  44545. subMaterial = this.subMaterials[index];
  44546. }
  44547. newMultiMaterial.subMaterials.push(subMaterial);
  44548. }
  44549. return newMultiMaterial;
  44550. };
  44551. MultiMaterial.prototype.serialize = function () {
  44552. var serializationObject = {};
  44553. serializationObject.name = this.name;
  44554. serializationObject.id = this.id;
  44555. serializationObject.tags = BABYLON.Tags.GetTags(this);
  44556. serializationObject.materials = [];
  44557. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  44558. var subMat = this.subMaterials[matIndex];
  44559. if (subMat) {
  44560. serializationObject.materials.push(subMat.id);
  44561. }
  44562. else {
  44563. serializationObject.materials.push(null);
  44564. }
  44565. }
  44566. return serializationObject;
  44567. };
  44568. return MultiMaterial;
  44569. }(BABYLON.Material));
  44570. BABYLON.MultiMaterial = MultiMaterial;
  44571. })(BABYLON || (BABYLON = {}));
  44572. //# sourceMappingURL=babylon.multiMaterial.js.map
  44573. var BABYLON;
  44574. (function (BABYLON) {
  44575. var FreeCameraTouchInput = (function () {
  44576. function FreeCameraTouchInput() {
  44577. this._offsetX = null;
  44578. this._offsetY = null;
  44579. this._pointerCount = 0;
  44580. this._pointerPressed = [];
  44581. this.touchAngularSensibility = 200000.0;
  44582. this.touchMoveSensibility = 250.0;
  44583. }
  44584. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  44585. var _this = this;
  44586. var previousPosition;
  44587. if (this._pointerInput === undefined) {
  44588. this._onLostFocus = function (evt) {
  44589. _this._offsetX = null;
  44590. _this._offsetY = null;
  44591. };
  44592. this._pointerInput = function (p, s) {
  44593. var evt = p.event;
  44594. if (evt.pointerType === "mouse") {
  44595. return;
  44596. }
  44597. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  44598. if (!noPreventDefault) {
  44599. evt.preventDefault();
  44600. }
  44601. _this._pointerPressed.push(evt.pointerId);
  44602. if (_this._pointerPressed.length !== 1) {
  44603. return;
  44604. }
  44605. previousPosition = {
  44606. x: evt.clientX,
  44607. y: evt.clientY
  44608. };
  44609. }
  44610. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  44611. if (!noPreventDefault) {
  44612. evt.preventDefault();
  44613. }
  44614. var index = _this._pointerPressed.indexOf(evt.pointerId);
  44615. if (index === -1) {
  44616. return;
  44617. }
  44618. _this._pointerPressed.splice(index, 1);
  44619. if (index != 0) {
  44620. return;
  44621. }
  44622. previousPosition = null;
  44623. _this._offsetX = null;
  44624. _this._offsetY = null;
  44625. }
  44626. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44627. if (!noPreventDefault) {
  44628. evt.preventDefault();
  44629. }
  44630. if (!previousPosition) {
  44631. return;
  44632. }
  44633. var index = _this._pointerPressed.indexOf(evt.pointerId);
  44634. if (index != 0) {
  44635. return;
  44636. }
  44637. _this._offsetX = evt.clientX - previousPosition.x;
  44638. _this._offsetY = -(evt.clientY - previousPosition.y);
  44639. }
  44640. };
  44641. }
  44642. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  44643. element.addEventListener("blur", this._onLostFocus);
  44644. };
  44645. FreeCameraTouchInput.prototype.detachControl = function (element) {
  44646. if (this._pointerInput && element) {
  44647. this.camera.getScene().onPointerObservable.remove(this._observer);
  44648. this._observer = null;
  44649. element.removeEventListener("blur", this._onLostFocus);
  44650. this._onLostFocus = null;
  44651. this._pointerPressed = [];
  44652. this._offsetX = null;
  44653. this._offsetY = null;
  44654. this._pointerCount = 0;
  44655. }
  44656. };
  44657. FreeCameraTouchInput.prototype.checkInputs = function () {
  44658. if (this._offsetX) {
  44659. var camera = this.camera;
  44660. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  44661. if (this._pointerPressed.length > 1) {
  44662. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  44663. }
  44664. else {
  44665. var speed = camera._computeLocalCameraSpeed();
  44666. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  44667. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  44668. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  44669. }
  44670. }
  44671. };
  44672. FreeCameraTouchInput.prototype.getTypeName = function () {
  44673. return "FreeCameraTouchInput";
  44674. };
  44675. FreeCameraTouchInput.prototype.getSimpleName = function () {
  44676. return "touch";
  44677. };
  44678. return FreeCameraTouchInput;
  44679. }());
  44680. __decorate([
  44681. BABYLON.serialize()
  44682. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  44683. __decorate([
  44684. BABYLON.serialize()
  44685. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  44686. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  44687. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  44688. })(BABYLON || (BABYLON = {}));
  44689. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  44690. /// <reference path="babylon.freeCamera.ts" />
  44691. var BABYLON;
  44692. (function (BABYLON) {
  44693. // We're mainly based on the logic defined into the FreeCamera code
  44694. var TouchCamera = (function (_super) {
  44695. __extends(TouchCamera, _super);
  44696. //-- end properties for backward compatibility for inputs
  44697. function TouchCamera(name, position, scene) {
  44698. var _this = _super.call(this, name, position, scene) || this;
  44699. _this.inputs.addTouch();
  44700. _this._setupInputs();
  44701. return _this;
  44702. }
  44703. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  44704. //-- Begin properties for backward compatibility for inputs
  44705. get: function () {
  44706. var touch = this.inputs.attached["touch"];
  44707. if (touch)
  44708. return touch.touchAngularSensibility;
  44709. },
  44710. set: function (value) {
  44711. var touch = this.inputs.attached["touch"];
  44712. if (touch)
  44713. touch.touchAngularSensibility = value;
  44714. },
  44715. enumerable: true,
  44716. configurable: true
  44717. });
  44718. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  44719. get: function () {
  44720. var touch = this.inputs.attached["touch"];
  44721. if (touch)
  44722. return touch.touchMoveSensibility;
  44723. },
  44724. set: function (value) {
  44725. var touch = this.inputs.attached["touch"];
  44726. if (touch)
  44727. touch.touchMoveSensibility = value;
  44728. },
  44729. enumerable: true,
  44730. configurable: true
  44731. });
  44732. TouchCamera.prototype.getClassName = function () {
  44733. return "TouchCamera";
  44734. };
  44735. TouchCamera.prototype._setupInputs = function () {
  44736. var mouse = this.inputs.attached["mouse"];
  44737. if (mouse) {
  44738. mouse.touchEnabled = false;
  44739. }
  44740. };
  44741. return TouchCamera;
  44742. }(BABYLON.FreeCamera));
  44743. BABYLON.TouchCamera = TouchCamera;
  44744. })(BABYLON || (BABYLON = {}));
  44745. //# sourceMappingURL=babylon.touchCamera.js.map
  44746. var BABYLON;
  44747. (function (BABYLON) {
  44748. var ProceduralTexture = (function (_super) {
  44749. __extends(ProceduralTexture, _super);
  44750. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  44751. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44752. if (isCube === void 0) { isCube = false; }
  44753. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  44754. _this.isCube = isCube;
  44755. _this.isEnabled = true;
  44756. _this._currentRefreshId = -1;
  44757. _this._refreshRate = 1;
  44758. _this._vertexBuffers = {};
  44759. _this._uniforms = new Array();
  44760. _this._samplers = new Array();
  44761. _this._textures = new Array();
  44762. _this._floats = new Array();
  44763. _this._floatsArrays = {};
  44764. _this._colors3 = new Array();
  44765. _this._colors4 = new Array();
  44766. _this._vectors2 = new Array();
  44767. _this._vectors3 = new Array();
  44768. _this._matrices = new Array();
  44769. _this._fallbackTextureUsed = false;
  44770. scene._proceduralTextures.push(_this);
  44771. _this.name = name;
  44772. _this.isRenderTarget = true;
  44773. _this._size = size;
  44774. _this._generateMipMaps = generateMipMaps;
  44775. _this.setFragment(fragment);
  44776. _this._fallbackTexture = fallbackTexture;
  44777. var engine = scene.getEngine();
  44778. if (isCube) {
  44779. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  44780. _this.setFloat("face", 0);
  44781. }
  44782. else {
  44783. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  44784. }
  44785. // VBO
  44786. var vertices = [];
  44787. vertices.push(1, 1);
  44788. vertices.push(-1, 1);
  44789. vertices.push(-1, -1);
  44790. vertices.push(1, -1);
  44791. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  44792. // Indices
  44793. var indices = [];
  44794. indices.push(0);
  44795. indices.push(1);
  44796. indices.push(2);
  44797. indices.push(0);
  44798. indices.push(2);
  44799. indices.push(3);
  44800. _this._indexBuffer = engine.createIndexBuffer(indices);
  44801. return _this;
  44802. }
  44803. ProceduralTexture.prototype.reset = function () {
  44804. if (this._effect === undefined) {
  44805. return;
  44806. }
  44807. var engine = this.getScene().getEngine();
  44808. engine._releaseEffect(this._effect);
  44809. };
  44810. ProceduralTexture.prototype.isReady = function () {
  44811. var _this = this;
  44812. var engine = this.getScene().getEngine();
  44813. var shaders;
  44814. if (!this._fragment) {
  44815. return false;
  44816. }
  44817. if (this._fallbackTextureUsed) {
  44818. return true;
  44819. }
  44820. if (this._fragment.fragmentElement !== undefined) {
  44821. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  44822. }
  44823. else {
  44824. shaders = { vertex: "procedural", fragment: this._fragment };
  44825. }
  44826. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  44827. _this.releaseInternalTexture();
  44828. if (_this._fallbackTexture) {
  44829. _this._texture = _this._fallbackTexture._texture;
  44830. _this._texture.references++;
  44831. }
  44832. _this._fallbackTextureUsed = true;
  44833. });
  44834. return this._effect.isReady();
  44835. };
  44836. ProceduralTexture.prototype.resetRefreshCounter = function () {
  44837. this._currentRefreshId = -1;
  44838. };
  44839. ProceduralTexture.prototype.setFragment = function (fragment) {
  44840. this._fragment = fragment;
  44841. };
  44842. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  44843. get: function () {
  44844. return this._refreshRate;
  44845. },
  44846. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  44847. set: function (value) {
  44848. this._refreshRate = value;
  44849. this.resetRefreshCounter();
  44850. },
  44851. enumerable: true,
  44852. configurable: true
  44853. });
  44854. ProceduralTexture.prototype._shouldRender = function () {
  44855. if (!this.isEnabled || !this.isReady() || !this._texture) {
  44856. return false;
  44857. }
  44858. if (this._fallbackTextureUsed) {
  44859. return false;
  44860. }
  44861. if (this._currentRefreshId === -1) {
  44862. this._currentRefreshId = 1;
  44863. return true;
  44864. }
  44865. if (this.refreshRate === this._currentRefreshId) {
  44866. this._currentRefreshId = 1;
  44867. return true;
  44868. }
  44869. this._currentRefreshId++;
  44870. return false;
  44871. };
  44872. ProceduralTexture.prototype.getRenderSize = function () {
  44873. return this._size;
  44874. };
  44875. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  44876. if (this._fallbackTextureUsed) {
  44877. return;
  44878. }
  44879. this.releaseInternalTexture();
  44880. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  44881. };
  44882. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  44883. if (this._uniforms.indexOf(uniformName) === -1) {
  44884. this._uniforms.push(uniformName);
  44885. }
  44886. };
  44887. ProceduralTexture.prototype.setTexture = function (name, texture) {
  44888. if (this._samplers.indexOf(name) === -1) {
  44889. this._samplers.push(name);
  44890. }
  44891. this._textures[name] = texture;
  44892. return this;
  44893. };
  44894. ProceduralTexture.prototype.setFloat = function (name, value) {
  44895. this._checkUniform(name);
  44896. this._floats[name] = value;
  44897. return this;
  44898. };
  44899. ProceduralTexture.prototype.setFloats = function (name, value) {
  44900. this._checkUniform(name);
  44901. this._floatsArrays[name] = value;
  44902. return this;
  44903. };
  44904. ProceduralTexture.prototype.setColor3 = function (name, value) {
  44905. this._checkUniform(name);
  44906. this._colors3[name] = value;
  44907. return this;
  44908. };
  44909. ProceduralTexture.prototype.setColor4 = function (name, value) {
  44910. this._checkUniform(name);
  44911. this._colors4[name] = value;
  44912. return this;
  44913. };
  44914. ProceduralTexture.prototype.setVector2 = function (name, value) {
  44915. this._checkUniform(name);
  44916. this._vectors2[name] = value;
  44917. return this;
  44918. };
  44919. ProceduralTexture.prototype.setVector3 = function (name, value) {
  44920. this._checkUniform(name);
  44921. this._vectors3[name] = value;
  44922. return this;
  44923. };
  44924. ProceduralTexture.prototype.setMatrix = function (name, value) {
  44925. this._checkUniform(name);
  44926. this._matrices[name] = value;
  44927. return this;
  44928. };
  44929. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  44930. var scene = this.getScene();
  44931. var engine = scene.getEngine();
  44932. // Render
  44933. engine.enableEffect(this._effect);
  44934. engine.setState(false);
  44935. // Texture
  44936. for (var name in this._textures) {
  44937. this._effect.setTexture(name, this._textures[name]);
  44938. }
  44939. // Float
  44940. for (name in this._floats) {
  44941. this._effect.setFloat(name, this._floats[name]);
  44942. }
  44943. // Floats
  44944. for (name in this._floatsArrays) {
  44945. this._effect.setArray(name, this._floatsArrays[name]);
  44946. }
  44947. // Color3
  44948. for (name in this._colors3) {
  44949. this._effect.setColor3(name, this._colors3[name]);
  44950. }
  44951. // Color4
  44952. for (name in this._colors4) {
  44953. var color = this._colors4[name];
  44954. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  44955. }
  44956. // Vector2
  44957. for (name in this._vectors2) {
  44958. this._effect.setVector2(name, this._vectors2[name]);
  44959. }
  44960. // Vector3
  44961. for (name in this._vectors3) {
  44962. this._effect.setVector3(name, this._vectors3[name]);
  44963. }
  44964. // Matrix
  44965. for (name in this._matrices) {
  44966. this._effect.setMatrix(name, this._matrices[name]);
  44967. }
  44968. if (this.isCube) {
  44969. for (var face = 0; face < 6; face++) {
  44970. engine.bindFramebuffer(this._texture, face);
  44971. // VBOs
  44972. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  44973. this._effect.setFloat("face", face);
  44974. // Clear
  44975. engine.clear(scene.clearColor, true, true, true);
  44976. // Draw order
  44977. engine.draw(true, 0, 6);
  44978. // Mipmaps
  44979. if (face === 5) {
  44980. engine.generateMipMapsForCubemap(this._texture);
  44981. }
  44982. }
  44983. }
  44984. else {
  44985. engine.bindFramebuffer(this._texture);
  44986. // VBOs
  44987. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  44988. // Clear
  44989. engine.clear(scene.clearColor, true, true, true);
  44990. // Draw order
  44991. engine.draw(true, 0, 6);
  44992. }
  44993. // Unbind
  44994. engine.unBindFramebuffer(this._texture, this.isCube);
  44995. if (this.onGenerated) {
  44996. this.onGenerated();
  44997. }
  44998. };
  44999. ProceduralTexture.prototype.clone = function () {
  45000. var textureSize = this.getSize();
  45001. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  45002. // Base texture
  45003. newTexture.hasAlpha = this.hasAlpha;
  45004. newTexture.level = this.level;
  45005. // RenderTarget Texture
  45006. newTexture.coordinatesMode = this.coordinatesMode;
  45007. return newTexture;
  45008. };
  45009. ProceduralTexture.prototype.dispose = function () {
  45010. var index = this.getScene()._proceduralTextures.indexOf(this);
  45011. if (index >= 0) {
  45012. this.getScene()._proceduralTextures.splice(index, 1);
  45013. }
  45014. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  45015. if (vertexBuffer) {
  45016. vertexBuffer.dispose();
  45017. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  45018. }
  45019. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  45020. this._indexBuffer = null;
  45021. }
  45022. _super.prototype.dispose.call(this);
  45023. };
  45024. return ProceduralTexture;
  45025. }(BABYLON.Texture));
  45026. BABYLON.ProceduralTexture = ProceduralTexture;
  45027. })(BABYLON || (BABYLON = {}));
  45028. //# sourceMappingURL=babylon.proceduralTexture.js.map
  45029. /// <reference path="babylon.proceduralTexture.ts" />
  45030. var BABYLON;
  45031. (function (BABYLON) {
  45032. var CustomProceduralTexture = (function (_super) {
  45033. __extends(CustomProceduralTexture, _super);
  45034. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  45035. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  45036. _this._animate = true;
  45037. _this._time = 0;
  45038. _this._texturePath = texturePath;
  45039. //Try to load json
  45040. _this.loadJson(texturePath);
  45041. _this.refreshRate = 1;
  45042. return _this;
  45043. }
  45044. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  45045. var _this = this;
  45046. var that = this;
  45047. function noConfigFile() {
  45048. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  45049. try {
  45050. that.setFragment(that._texturePath);
  45051. }
  45052. catch (ex) {
  45053. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  45054. }
  45055. }
  45056. var configFileUrl = jsonUrl + "/config.json";
  45057. var xhr = new XMLHttpRequest();
  45058. xhr.open("GET", configFileUrl, true);
  45059. xhr.addEventListener("load", function () {
  45060. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  45061. try {
  45062. _this._config = JSON.parse(xhr.response);
  45063. _this.updateShaderUniforms();
  45064. _this.updateTextures();
  45065. _this.setFragment(_this._texturePath + "/custom");
  45066. _this._animate = _this._config.animate;
  45067. _this.refreshRate = _this._config.refreshrate;
  45068. }
  45069. catch (ex) {
  45070. noConfigFile();
  45071. }
  45072. }
  45073. else {
  45074. noConfigFile();
  45075. }
  45076. }, false);
  45077. xhr.addEventListener("error", function () {
  45078. noConfigFile();
  45079. }, false);
  45080. try {
  45081. xhr.send();
  45082. }
  45083. catch (ex) {
  45084. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  45085. }
  45086. };
  45087. CustomProceduralTexture.prototype.isReady = function () {
  45088. if (!_super.prototype.isReady.call(this)) {
  45089. return false;
  45090. }
  45091. for (var name in this._textures) {
  45092. var texture = this._textures[name];
  45093. if (!texture.isReady()) {
  45094. return false;
  45095. }
  45096. }
  45097. return true;
  45098. };
  45099. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  45100. if (this._animate) {
  45101. this._time += this.getScene().getAnimationRatio() * 0.03;
  45102. this.updateShaderUniforms();
  45103. }
  45104. _super.prototype.render.call(this, useCameraPostProcess);
  45105. };
  45106. CustomProceduralTexture.prototype.updateTextures = function () {
  45107. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  45108. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  45109. }
  45110. };
  45111. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  45112. if (this._config) {
  45113. for (var j = 0; j < this._config.uniforms.length; j++) {
  45114. var uniform = this._config.uniforms[j];
  45115. switch (uniform.type) {
  45116. case "float":
  45117. this.setFloat(uniform.name, uniform.value);
  45118. break;
  45119. case "color3":
  45120. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  45121. break;
  45122. case "color4":
  45123. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  45124. break;
  45125. case "vector2":
  45126. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  45127. break;
  45128. case "vector3":
  45129. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  45130. break;
  45131. }
  45132. }
  45133. }
  45134. this.setFloat("time", this._time);
  45135. };
  45136. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  45137. get: function () {
  45138. return this._animate;
  45139. },
  45140. set: function (value) {
  45141. this._animate = value;
  45142. },
  45143. enumerable: true,
  45144. configurable: true
  45145. });
  45146. return CustomProceduralTexture;
  45147. }(BABYLON.ProceduralTexture));
  45148. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  45149. })(BABYLON || (BABYLON = {}));
  45150. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  45151. var BABYLON;
  45152. (function (BABYLON) {
  45153. var FreeCameraGamepadInput = (function () {
  45154. function FreeCameraGamepadInput() {
  45155. this.gamepadAngularSensibility = 200;
  45156. this.gamepadMoveSensibility = 40;
  45157. // private members
  45158. this._cameraTransform = BABYLON.Matrix.Identity();
  45159. this._deltaTransform = BABYLON.Vector3.Zero();
  45160. this._vector3 = BABYLON.Vector3.Zero();
  45161. this._vector2 = BABYLON.Vector2.Zero();
  45162. }
  45163. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  45164. var _this = this;
  45165. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  45166. };
  45167. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  45168. if (this._gamepads) {
  45169. this._gamepads.dispose();
  45170. }
  45171. this.gamepad = null;
  45172. };
  45173. FreeCameraGamepadInput.prototype.checkInputs = function () {
  45174. if (this.gamepad && this.gamepad.leftStick) {
  45175. var camera = this.camera;
  45176. var LSValues = this.gamepad.leftStick;
  45177. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  45178. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  45179. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  45180. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  45181. var RSValues = this.gamepad.rightStick;
  45182. if (RSValues) {
  45183. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  45184. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  45185. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  45186. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  45187. }
  45188. else {
  45189. RSValues = { x: 0, y: 0 };
  45190. }
  45191. if (!camera.rotationQuaternion) {
  45192. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  45193. }
  45194. else {
  45195. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  45196. }
  45197. var speed = camera._computeLocalCameraSpeed() * 50.0;
  45198. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  45199. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  45200. camera.cameraDirection.addInPlace(this._deltaTransform);
  45201. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  45202. camera.cameraRotation.addInPlace(this._vector2);
  45203. }
  45204. };
  45205. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  45206. // Only the first gamepad found can control the camera
  45207. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  45208. // prioritize XBOX gamepads.
  45209. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  45210. this.gamepad = gamepad;
  45211. }
  45212. }
  45213. };
  45214. FreeCameraGamepadInput.prototype.getTypeName = function () {
  45215. return "FreeCameraGamepadInput";
  45216. };
  45217. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  45218. return "gamepad";
  45219. };
  45220. return FreeCameraGamepadInput;
  45221. }());
  45222. __decorate([
  45223. BABYLON.serialize()
  45224. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  45225. __decorate([
  45226. BABYLON.serialize()
  45227. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  45228. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  45229. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  45230. })(BABYLON || (BABYLON = {}));
  45231. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  45232. var BABYLON;
  45233. (function (BABYLON) {
  45234. var ArcRotateCameraGamepadInput = (function () {
  45235. function ArcRotateCameraGamepadInput() {
  45236. this.gamepadRotationSensibility = 80;
  45237. this.gamepadMoveSensibility = 40;
  45238. }
  45239. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  45240. var _this = this;
  45241. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  45242. };
  45243. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  45244. if (this._gamepads) {
  45245. this._gamepads.dispose();
  45246. }
  45247. this.gamepad = null;
  45248. };
  45249. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  45250. if (this.gamepad) {
  45251. var camera = this.camera;
  45252. var RSValues = this.gamepad.rightStick;
  45253. if (RSValues) {
  45254. if (RSValues.x != 0) {
  45255. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  45256. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  45257. camera.inertialAlphaOffset += normalizedRX;
  45258. }
  45259. }
  45260. if (RSValues.y != 0) {
  45261. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  45262. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  45263. camera.inertialBetaOffset += normalizedRY;
  45264. }
  45265. }
  45266. }
  45267. var LSValues = this.gamepad.leftStick;
  45268. if (LSValues && LSValues.y != 0) {
  45269. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  45270. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  45271. this.camera.inertialRadiusOffset -= normalizedLY;
  45272. }
  45273. }
  45274. }
  45275. };
  45276. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  45277. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  45278. // prioritize XBOX gamepads.
  45279. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  45280. this.gamepad = gamepad;
  45281. }
  45282. }
  45283. };
  45284. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  45285. return "ArcRotateCameraGamepadInput";
  45286. };
  45287. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  45288. return "gamepad";
  45289. };
  45290. return ArcRotateCameraGamepadInput;
  45291. }());
  45292. __decorate([
  45293. BABYLON.serialize()
  45294. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  45295. __decorate([
  45296. BABYLON.serialize()
  45297. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  45298. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  45299. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  45300. })(BABYLON || (BABYLON = {}));
  45301. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  45302. var BABYLON;
  45303. (function (BABYLON) {
  45304. var Gamepads = (function () {
  45305. function Gamepads(ongamedpadconnected) {
  45306. var _this = this;
  45307. this.babylonGamepads = [];
  45308. this.oneGamepadConnected = false;
  45309. this.isMonitoring = false;
  45310. this.gamepadEventSupported = 'GamepadEvent' in window;
  45311. this.gamepadSupport = (navigator.getGamepads ||
  45312. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  45313. this._callbackGamepadConnected = ongamedpadconnected;
  45314. if (this.gamepadSupport) {
  45315. //first add already-connected gamepads
  45316. this._updateGamepadObjects();
  45317. if (this.babylonGamepads.length) {
  45318. this._startMonitoringGamepads();
  45319. }
  45320. // Checking if the gamepad connected event is supported (like in Firefox)
  45321. if (this.gamepadEventSupported) {
  45322. this._onGamepadConnectedEvent = function (evt) {
  45323. _this._onGamepadConnected(evt.gamepad);
  45324. };
  45325. this._onGamepadDisonnectedEvent = function (evt) {
  45326. _this._onGamepadDisconnected(evt);
  45327. };
  45328. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  45329. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  45330. }
  45331. else {
  45332. this._startMonitoringGamepads();
  45333. }
  45334. }
  45335. }
  45336. Gamepads.prototype.dispose = function () {
  45337. if (Gamepads.gamepadDOMInfo) {
  45338. document.body.removeChild(Gamepads.gamepadDOMInfo);
  45339. }
  45340. if (this._onGamepadConnectedEvent) {
  45341. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  45342. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  45343. this._onGamepadConnectedEvent = null;
  45344. this._onGamepadDisonnectedEvent = null;
  45345. }
  45346. };
  45347. Gamepads.prototype._onGamepadConnected = function (gamepad) {
  45348. var newGamepad = this._addNewGamepad(gamepad);
  45349. if (this._callbackGamepadConnected)
  45350. this._callbackGamepadConnected(newGamepad);
  45351. this._startMonitoringGamepads();
  45352. };
  45353. Gamepads.prototype._addNewGamepad = function (gamepad) {
  45354. if (!this.oneGamepadConnected) {
  45355. this.oneGamepadConnected = true;
  45356. if (Gamepads.gamepadDOMInfo) {
  45357. document.body.removeChild(Gamepads.gamepadDOMInfo);
  45358. Gamepads.gamepadDOMInfo = null;
  45359. }
  45360. }
  45361. var newGamepad;
  45362. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  45363. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  45364. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  45365. }
  45366. else if (gamepad.pose) {
  45367. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  45368. }
  45369. else {
  45370. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  45371. }
  45372. this.babylonGamepads.push(newGamepad);
  45373. return newGamepad;
  45374. };
  45375. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  45376. // Remove the gamepad from the list of gamepads to monitor.
  45377. for (var i in this.babylonGamepads) {
  45378. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  45379. this.babylonGamepads.splice(+i, 1);
  45380. break;
  45381. }
  45382. }
  45383. // If no gamepads are left, stop the polling loop.
  45384. if (this.babylonGamepads.length == 0) {
  45385. this._stopMonitoringGamepads();
  45386. }
  45387. };
  45388. Gamepads.prototype._startMonitoringGamepads = function () {
  45389. if (!this.isMonitoring) {
  45390. this.isMonitoring = true;
  45391. this._checkGamepadsStatus();
  45392. }
  45393. };
  45394. Gamepads.prototype._stopMonitoringGamepads = function () {
  45395. this.isMonitoring = false;
  45396. };
  45397. Gamepads.prototype._checkGamepadsStatus = function () {
  45398. var _this = this;
  45399. // updating gamepad objects
  45400. this._updateGamepadObjects();
  45401. for (var i in this.babylonGamepads) {
  45402. this.babylonGamepads[i].update();
  45403. }
  45404. if (this.isMonitoring) {
  45405. if (window.requestAnimationFrame) {
  45406. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45407. }
  45408. else if (window.mozRequestAnimationFrame) {
  45409. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45410. }
  45411. else if (window.webkitRequestAnimationFrame) {
  45412. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45413. }
  45414. }
  45415. };
  45416. // This function is called only on Chrome, which does not yet support
  45417. // connection/disconnection events, but requires you to monitor
  45418. // an array for changes.
  45419. Gamepads.prototype._updateGamepadObjects = function () {
  45420. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  45421. for (var i = 0; i < gamepads.length; i++) {
  45422. if (gamepads[i]) {
  45423. if (!(gamepads[i].index in this.babylonGamepads)) {
  45424. var newGamepad = this._addNewGamepad(gamepads[i]);
  45425. if (this._callbackGamepadConnected) {
  45426. this._callbackGamepadConnected(newGamepad);
  45427. }
  45428. }
  45429. else {
  45430. this.babylonGamepads[i].browserGamepad = gamepads[i];
  45431. }
  45432. }
  45433. }
  45434. };
  45435. return Gamepads;
  45436. }());
  45437. BABYLON.Gamepads = Gamepads;
  45438. var StickValues = (function () {
  45439. function StickValues(x, y) {
  45440. this.x = x;
  45441. this.y = y;
  45442. }
  45443. return StickValues;
  45444. }());
  45445. BABYLON.StickValues = StickValues;
  45446. var Gamepad = (function () {
  45447. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  45448. if (leftStickX === void 0) { leftStickX = 0; }
  45449. if (leftStickY === void 0) { leftStickY = 1; }
  45450. if (rightStickX === void 0) { rightStickX = 2; }
  45451. if (rightStickY === void 0) { rightStickY = 3; }
  45452. this.id = id;
  45453. this.index = index;
  45454. this.browserGamepad = browserGamepad;
  45455. this.type = Gamepad.GAMEPAD;
  45456. this._leftStickAxisX = leftStickX;
  45457. this._leftStickAxisY = leftStickY;
  45458. this._rightStickAxisX = rightStickX;
  45459. this._rightStickAxisY = rightStickY;
  45460. if (this.browserGamepad.axes.length >= 2) {
  45461. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  45462. }
  45463. if (this.browserGamepad.axes.length >= 4) {
  45464. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  45465. }
  45466. }
  45467. Gamepad.prototype.onleftstickchanged = function (callback) {
  45468. this._onleftstickchanged = callback;
  45469. };
  45470. Gamepad.prototype.onrightstickchanged = function (callback) {
  45471. this._onrightstickchanged = callback;
  45472. };
  45473. Object.defineProperty(Gamepad.prototype, "leftStick", {
  45474. get: function () {
  45475. return this._leftStick;
  45476. },
  45477. set: function (newValues) {
  45478. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  45479. this._onleftstickchanged(newValues);
  45480. }
  45481. this._leftStick = newValues;
  45482. },
  45483. enumerable: true,
  45484. configurable: true
  45485. });
  45486. Object.defineProperty(Gamepad.prototype, "rightStick", {
  45487. get: function () {
  45488. return this._rightStick;
  45489. },
  45490. set: function (newValues) {
  45491. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  45492. this._onrightstickchanged(newValues);
  45493. }
  45494. this._rightStick = newValues;
  45495. },
  45496. enumerable: true,
  45497. configurable: true
  45498. });
  45499. Gamepad.prototype.update = function () {
  45500. if (this._leftStick) {
  45501. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  45502. }
  45503. if (this._rightStick) {
  45504. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  45505. }
  45506. };
  45507. return Gamepad;
  45508. }());
  45509. Gamepad.GAMEPAD = 0;
  45510. Gamepad.GENERIC = 1;
  45511. Gamepad.XBOX = 2;
  45512. Gamepad.POSE_ENABLED = 3;
  45513. BABYLON.Gamepad = Gamepad;
  45514. var GenericPad = (function (_super) {
  45515. __extends(GenericPad, _super);
  45516. function GenericPad(id, index, gamepad) {
  45517. var _this = _super.call(this, id, index, gamepad) || this;
  45518. _this.id = id;
  45519. _this.index = index;
  45520. _this.gamepad = gamepad;
  45521. _this.type = Gamepad.GENERIC;
  45522. _this._buttons = new Array(gamepad.buttons.length);
  45523. return _this;
  45524. }
  45525. GenericPad.prototype.onbuttondown = function (callback) {
  45526. this._onbuttondown = callback;
  45527. };
  45528. GenericPad.prototype.onbuttonup = function (callback) {
  45529. this._onbuttonup = callback;
  45530. };
  45531. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  45532. if (newValue !== currentValue) {
  45533. if (this._onbuttondown && newValue === 1) {
  45534. this._onbuttondown(buttonIndex);
  45535. }
  45536. if (this._onbuttonup && newValue === 0) {
  45537. this._onbuttonup(buttonIndex);
  45538. }
  45539. }
  45540. return newValue;
  45541. };
  45542. GenericPad.prototype.update = function () {
  45543. _super.prototype.update.call(this);
  45544. for (var index = 0; index < this._buttons.length; index++) {
  45545. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  45546. }
  45547. };
  45548. return GenericPad;
  45549. }(Gamepad));
  45550. BABYLON.GenericPad = GenericPad;
  45551. var Xbox360Button;
  45552. (function (Xbox360Button) {
  45553. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  45554. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  45555. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  45556. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  45557. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  45558. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  45559. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  45560. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  45561. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  45562. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  45563. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  45564. var Xbox360Dpad;
  45565. (function (Xbox360Dpad) {
  45566. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  45567. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  45568. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  45569. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  45570. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  45571. var Xbox360Pad = (function (_super) {
  45572. __extends(Xbox360Pad, _super);
  45573. function Xbox360Pad(id, index, gamepad, xboxOne) {
  45574. if (xboxOne === void 0) { xboxOne = false; }
  45575. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  45576. _this._leftTrigger = 0;
  45577. _this._rightTrigger = 0;
  45578. _this._buttonA = 0;
  45579. _this._buttonB = 0;
  45580. _this._buttonX = 0;
  45581. _this._buttonY = 0;
  45582. _this._buttonBack = 0;
  45583. _this._buttonStart = 0;
  45584. _this._buttonLB = 0;
  45585. _this._buttonRB = 0;
  45586. _this._buttonLeftStick = 0;
  45587. _this._buttonRightStick = 0;
  45588. _this._dPadUp = 0;
  45589. _this._dPadDown = 0;
  45590. _this._dPadLeft = 0;
  45591. _this._dPadRight = 0;
  45592. _this._isXboxOnePad = false;
  45593. _this.type = Gamepad.XBOX;
  45594. _this._isXboxOnePad = xboxOne;
  45595. return _this;
  45596. }
  45597. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  45598. this._onlefttriggerchanged = callback;
  45599. };
  45600. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  45601. this._onrighttriggerchanged = callback;
  45602. };
  45603. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  45604. get: function () {
  45605. return this._leftTrigger;
  45606. },
  45607. set: function (newValue) {
  45608. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  45609. this._onlefttriggerchanged(newValue);
  45610. }
  45611. this._leftTrigger = newValue;
  45612. },
  45613. enumerable: true,
  45614. configurable: true
  45615. });
  45616. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  45617. get: function () {
  45618. return this._rightTrigger;
  45619. },
  45620. set: function (newValue) {
  45621. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  45622. this._onrighttriggerchanged(newValue);
  45623. }
  45624. this._rightTrigger = newValue;
  45625. },
  45626. enumerable: true,
  45627. configurable: true
  45628. });
  45629. Xbox360Pad.prototype.onbuttondown = function (callback) {
  45630. this._onbuttondown = callback;
  45631. };
  45632. Xbox360Pad.prototype.onbuttonup = function (callback) {
  45633. this._onbuttonup = callback;
  45634. };
  45635. Xbox360Pad.prototype.ondpaddown = function (callback) {
  45636. this._ondpaddown = callback;
  45637. };
  45638. Xbox360Pad.prototype.ondpadup = function (callback) {
  45639. this._ondpadup = callback;
  45640. };
  45641. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  45642. if (newValue !== currentValue) {
  45643. if (this._onbuttondown && newValue === 1) {
  45644. this._onbuttondown(buttonType);
  45645. }
  45646. if (this._onbuttonup && newValue === 0) {
  45647. this._onbuttonup(buttonType);
  45648. }
  45649. }
  45650. return newValue;
  45651. };
  45652. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  45653. if (newValue !== currentValue) {
  45654. if (this._ondpaddown && newValue === 1) {
  45655. this._ondpaddown(buttonType);
  45656. }
  45657. if (this._ondpadup && newValue === 0) {
  45658. this._ondpadup(buttonType);
  45659. }
  45660. }
  45661. return newValue;
  45662. };
  45663. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  45664. get: function () {
  45665. return this._buttonA;
  45666. },
  45667. set: function (value) {
  45668. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  45669. },
  45670. enumerable: true,
  45671. configurable: true
  45672. });
  45673. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  45674. get: function () {
  45675. return this._buttonB;
  45676. },
  45677. set: function (value) {
  45678. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  45679. },
  45680. enumerable: true,
  45681. configurable: true
  45682. });
  45683. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  45684. get: function () {
  45685. return this._buttonX;
  45686. },
  45687. set: function (value) {
  45688. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  45689. },
  45690. enumerable: true,
  45691. configurable: true
  45692. });
  45693. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  45694. get: function () {
  45695. return this._buttonY;
  45696. },
  45697. set: function (value) {
  45698. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  45699. },
  45700. enumerable: true,
  45701. configurable: true
  45702. });
  45703. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  45704. get: function () {
  45705. return this._buttonStart;
  45706. },
  45707. set: function (value) {
  45708. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  45709. },
  45710. enumerable: true,
  45711. configurable: true
  45712. });
  45713. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  45714. get: function () {
  45715. return this._buttonBack;
  45716. },
  45717. set: function (value) {
  45718. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  45719. },
  45720. enumerable: true,
  45721. configurable: true
  45722. });
  45723. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  45724. get: function () {
  45725. return this._buttonLB;
  45726. },
  45727. set: function (value) {
  45728. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  45729. },
  45730. enumerable: true,
  45731. configurable: true
  45732. });
  45733. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  45734. get: function () {
  45735. return this._buttonRB;
  45736. },
  45737. set: function (value) {
  45738. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  45739. },
  45740. enumerable: true,
  45741. configurable: true
  45742. });
  45743. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  45744. get: function () {
  45745. return this._buttonLeftStick;
  45746. },
  45747. set: function (value) {
  45748. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  45749. },
  45750. enumerable: true,
  45751. configurable: true
  45752. });
  45753. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  45754. get: function () {
  45755. return this._buttonRightStick;
  45756. },
  45757. set: function (value) {
  45758. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  45759. },
  45760. enumerable: true,
  45761. configurable: true
  45762. });
  45763. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  45764. get: function () {
  45765. return this._dPadUp;
  45766. },
  45767. set: function (value) {
  45768. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  45769. },
  45770. enumerable: true,
  45771. configurable: true
  45772. });
  45773. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  45774. get: function () {
  45775. return this._dPadDown;
  45776. },
  45777. set: function (value) {
  45778. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  45779. },
  45780. enumerable: true,
  45781. configurable: true
  45782. });
  45783. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  45784. get: function () {
  45785. return this._dPadLeft;
  45786. },
  45787. set: function (value) {
  45788. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  45789. },
  45790. enumerable: true,
  45791. configurable: true
  45792. });
  45793. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  45794. get: function () {
  45795. return this._dPadRight;
  45796. },
  45797. set: function (value) {
  45798. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  45799. },
  45800. enumerable: true,
  45801. configurable: true
  45802. });
  45803. Xbox360Pad.prototype.update = function () {
  45804. _super.prototype.update.call(this);
  45805. if (this._isXboxOnePad) {
  45806. this.buttonA = this.browserGamepad.buttons[0].value;
  45807. this.buttonB = this.browserGamepad.buttons[1].value;
  45808. this.buttonX = this.browserGamepad.buttons[2].value;
  45809. this.buttonY = this.browserGamepad.buttons[3].value;
  45810. this.buttonLB = this.browserGamepad.buttons[4].value;
  45811. this.buttonRB = this.browserGamepad.buttons[5].value;
  45812. this.leftTrigger = this.browserGamepad.axes[2];
  45813. this.rightTrigger = this.browserGamepad.axes[5];
  45814. this.buttonBack = this.browserGamepad.buttons[9].value;
  45815. this.buttonStart = this.browserGamepad.buttons[8].value;
  45816. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  45817. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  45818. this.dPadUp = this.browserGamepad.buttons[11].value;
  45819. this.dPadDown = this.browserGamepad.buttons[12].value;
  45820. this.dPadLeft = this.browserGamepad.buttons[13].value;
  45821. this.dPadRight = this.browserGamepad.buttons[14].value;
  45822. }
  45823. else {
  45824. this.buttonA = this.browserGamepad.buttons[0].value;
  45825. this.buttonB = this.browserGamepad.buttons[1].value;
  45826. this.buttonX = this.browserGamepad.buttons[2].value;
  45827. this.buttonY = this.browserGamepad.buttons[3].value;
  45828. this.buttonLB = this.browserGamepad.buttons[4].value;
  45829. this.buttonRB = this.browserGamepad.buttons[5].value;
  45830. this.leftTrigger = this.browserGamepad.buttons[6].value;
  45831. this.rightTrigger = this.browserGamepad.buttons[7].value;
  45832. this.buttonBack = this.browserGamepad.buttons[8].value;
  45833. this.buttonStart = this.browserGamepad.buttons[9].value;
  45834. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  45835. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  45836. this.dPadUp = this.browserGamepad.buttons[12].value;
  45837. this.dPadDown = this.browserGamepad.buttons[13].value;
  45838. this.dPadLeft = this.browserGamepad.buttons[14].value;
  45839. this.dPadRight = this.browserGamepad.buttons[15].value;
  45840. }
  45841. };
  45842. return Xbox360Pad;
  45843. }(Gamepad));
  45844. BABYLON.Xbox360Pad = Xbox360Pad;
  45845. })(BABYLON || (BABYLON = {}));
  45846. //# sourceMappingURL=babylon.gamepads.js.map
  45847. var BABYLON;
  45848. (function (BABYLON) {
  45849. var PoseEnabledControllerType;
  45850. (function (PoseEnabledControllerType) {
  45851. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  45852. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  45853. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 2] = "GENERIC";
  45854. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  45855. var PoseEnabledControllerHelper = (function () {
  45856. function PoseEnabledControllerHelper() {
  45857. }
  45858. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  45859. // for now, only Oculus and Vive are supported
  45860. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  45861. return new OculusTouchController(vrGamepad);
  45862. }
  45863. else {
  45864. return new ViveController(vrGamepad);
  45865. }
  45866. };
  45867. return PoseEnabledControllerHelper;
  45868. }());
  45869. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  45870. var PoseEnabledController = (function (_super) {
  45871. __extends(PoseEnabledController, _super);
  45872. function PoseEnabledController(vrGamepad) {
  45873. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  45874. _this.vrGamepad = vrGamepad;
  45875. _this.deviceScaleFactor = 1;
  45876. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  45877. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  45878. _this.controllerType = PoseEnabledControllerType.GENERIC;
  45879. _this.position = BABYLON.Vector3.Zero();
  45880. _this.rotationQuaternion = new BABYLON.Quaternion();
  45881. _this.devicePosition = BABYLON.Vector3.Zero();
  45882. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  45883. _this._calculatedPosition = BABYLON.Vector3.Zero();
  45884. _this._calculatedRotation = new BABYLON.Quaternion();
  45885. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  45886. return _this;
  45887. }
  45888. PoseEnabledController.prototype.update = function () {
  45889. _super.prototype.update.call(this);
  45890. var pose = this.vrGamepad.pose;
  45891. this.updateFromDevice(pose);
  45892. if (this._mesh) {
  45893. this._mesh.position.copyFrom(this._calculatedPosition);
  45894. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  45895. }
  45896. };
  45897. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  45898. if (poseData) {
  45899. this.rawPose = poseData;
  45900. if (poseData.position) {
  45901. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  45902. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  45903. this.devicePosition.z *= -1;
  45904. }
  45905. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  45906. this._calculatedPosition.addInPlace(this.position);
  45907. }
  45908. if (poseData.orientation) {
  45909. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  45910. if (this._mesh) {
  45911. if (this._mesh.getScene().useRightHandedSystem) {
  45912. this.deviceRotationQuaternion.z *= -1;
  45913. this.deviceRotationQuaternion.w *= -1;
  45914. }
  45915. else {
  45916. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  45917. }
  45918. }
  45919. // if the camera is set, rotate to the camera's rotation
  45920. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  45921. }
  45922. }
  45923. };
  45924. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  45925. if (this._mesh) {
  45926. this._mesh.parent = undefined;
  45927. }
  45928. this._mesh = mesh;
  45929. if (this._poseControlledCamera) {
  45930. this._mesh.parent = this._poseControlledCamera;
  45931. }
  45932. if (!this._mesh.rotationQuaternion) {
  45933. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  45934. }
  45935. };
  45936. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  45937. this._poseControlledCamera = camera;
  45938. if (this._mesh) {
  45939. this._mesh.parent = this._poseControlledCamera;
  45940. }
  45941. };
  45942. PoseEnabledController.prototype.detachMesh = function () {
  45943. this._mesh = undefined;
  45944. };
  45945. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  45946. get: function () {
  45947. return this._mesh;
  45948. },
  45949. enumerable: true,
  45950. configurable: true
  45951. });
  45952. PoseEnabledController.prototype.getForwardRay = function (length) {
  45953. if (length === void 0) { length = 100; }
  45954. if (!this.mesh) {
  45955. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  45956. }
  45957. var m = this.mesh.getWorldMatrix();
  45958. var origin = m.getTranslation();
  45959. var forward = new BABYLON.Vector3(0, 0, -1);
  45960. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  45961. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  45962. return new BABYLON.Ray(origin, direction, length);
  45963. };
  45964. return PoseEnabledController;
  45965. }(BABYLON.Gamepad));
  45966. BABYLON.PoseEnabledController = PoseEnabledController;
  45967. var WebVRController = (function (_super) {
  45968. __extends(WebVRController, _super);
  45969. function WebVRController(vrGamepad) {
  45970. var _this = _super.call(this, vrGamepad) || this;
  45971. //public onTriggerStateChangedObservable = new Observable<{ state: ExtendedGamepadButton, changes: GamepadButtonChanges }>();
  45972. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  45973. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  45974. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  45975. _this.onPadStateChangedObservable = new BABYLON.Observable();
  45976. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  45977. _this.pad = { x: 0, y: 0 };
  45978. // avoid GC, store state in a tmp object
  45979. _this._changes = {
  45980. pressChanged: false,
  45981. touchChanged: false,
  45982. valueChanged: false,
  45983. changed: false
  45984. };
  45985. _this._buttons = new Array(vrGamepad.buttons.length);
  45986. _this.hand = vrGamepad.hand;
  45987. return _this;
  45988. }
  45989. WebVRController.prototype.onButtonStateChange = function (callback) {
  45990. this._onButtonStateChange = callback;
  45991. };
  45992. WebVRController.prototype.update = function () {
  45993. _super.prototype.update.call(this);
  45994. for (var index = 0; index < this._buttons.length; index++) {
  45995. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  45996. }
  45997. ;
  45998. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  45999. this.pad.x = this.leftStick.x;
  46000. this.pad.y = this.leftStick.y;
  46001. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  46002. }
  46003. };
  46004. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  46005. if (!currentState) {
  46006. this._buttons[buttonIndex] = {
  46007. pressed: newState.pressed,
  46008. touched: newState.touched,
  46009. value: newState.value
  46010. };
  46011. return;
  46012. }
  46013. this._checkChanges(newState, currentState);
  46014. if (this._changes.changed) {
  46015. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  46016. this.handleButtonChange(buttonIndex, newState, this._changes);
  46017. }
  46018. this._buttons[buttonIndex].pressed = newState.pressed;
  46019. this._buttons[buttonIndex].touched = newState.touched;
  46020. // oculus triggers are never 0, thou not touched.
  46021. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  46022. };
  46023. WebVRController.prototype._checkChanges = function (newState, currentState) {
  46024. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  46025. this._changes.touchChanged = newState.touched !== currentState.touched;
  46026. this._changes.valueChanged = newState.value !== currentState.value;
  46027. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  46028. return this._changes;
  46029. };
  46030. return WebVRController;
  46031. }(PoseEnabledController));
  46032. BABYLON.WebVRController = WebVRController;
  46033. var OculusTouchController = (function (_super) {
  46034. __extends(OculusTouchController, _super);
  46035. function OculusTouchController(vrGamepad) {
  46036. var _this = _super.call(this, vrGamepad) || this;
  46037. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  46038. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  46039. _this.controllerType = PoseEnabledControllerType.OCULUS;
  46040. return _this;
  46041. }
  46042. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  46043. var _this = this;
  46044. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  46045. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  46046. /*
  46047. Parent Mesh name: oculus_touch_left
  46048. - body
  46049. - trigger
  46050. - thumbstick
  46051. - grip
  46052. - button_y
  46053. - button_x
  46054. - button_enter
  46055. */
  46056. _this._defaultModel = newMeshes[1];
  46057. if (meshLoaded) {
  46058. meshLoaded(_this._defaultModel);
  46059. }
  46060. _this.attachToMesh(_this._defaultModel);
  46061. });
  46062. };
  46063. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  46064. // helper getters for left and right hand.
  46065. get: function () {
  46066. if (this.hand === 'right') {
  46067. return this.onMainButtonStateChangedObservable;
  46068. }
  46069. else {
  46070. throw new Error('No A button on left hand');
  46071. }
  46072. },
  46073. enumerable: true,
  46074. configurable: true
  46075. });
  46076. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  46077. get: function () {
  46078. if (this.hand === 'right') {
  46079. return this.onSecondaryButtonStateChangedObservable;
  46080. }
  46081. else {
  46082. throw new Error('No B button on left hand');
  46083. }
  46084. },
  46085. enumerable: true,
  46086. configurable: true
  46087. });
  46088. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  46089. get: function () {
  46090. if (this.hand === 'left') {
  46091. return this.onMainButtonStateChangedObservable;
  46092. }
  46093. else {
  46094. throw new Error('No X button on right hand');
  46095. }
  46096. },
  46097. enumerable: true,
  46098. configurable: true
  46099. });
  46100. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  46101. get: function () {
  46102. if (this.hand === 'left') {
  46103. return this.onSecondaryButtonStateChangedObservable;
  46104. }
  46105. else {
  46106. throw new Error('No Y button on right hand');
  46107. }
  46108. },
  46109. enumerable: true,
  46110. configurable: true
  46111. });
  46112. /*
  46113. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  46114. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  46115. 2) secondary trigger (same)
  46116. 3) A (right) X (left), touch, pressed = value
  46117. 4) B / Y
  46118. 5) thumb rest
  46119. */
  46120. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  46121. var notifyObject = state; //{ state: state, changes: changes };
  46122. var triggerDirection = this.hand === 'right' ? -1 : 1;
  46123. switch (buttonIdx) {
  46124. case 0:
  46125. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  46126. return;
  46127. case 1:
  46128. if (this._defaultModel) {
  46129. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  46130. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  46131. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  46132. }
  46133. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  46134. return;
  46135. case 2:
  46136. if (this._defaultModel) {
  46137. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  46138. }
  46139. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  46140. return;
  46141. case 3:
  46142. if (this._defaultModel) {
  46143. if (notifyObject.pressed) {
  46144. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  46145. }
  46146. else {
  46147. (this._defaultModel.getChildren()[1]).position.y = 0;
  46148. }
  46149. }
  46150. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  46151. return;
  46152. case 4:
  46153. if (this._defaultModel) {
  46154. if (notifyObject.pressed) {
  46155. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  46156. }
  46157. else {
  46158. (this._defaultModel.getChildren()[2]).position.y = 0;
  46159. }
  46160. }
  46161. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  46162. return;
  46163. case 5:
  46164. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  46165. return;
  46166. }
  46167. };
  46168. return OculusTouchController;
  46169. }(WebVRController));
  46170. BABYLON.OculusTouchController = OculusTouchController;
  46171. var ViveController = (function (_super) {
  46172. __extends(ViveController, _super);
  46173. function ViveController(vrGamepad) {
  46174. var _this = _super.call(this, vrGamepad) || this;
  46175. _this.controllerType = PoseEnabledControllerType.VIVE;
  46176. return _this;
  46177. }
  46178. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  46179. var _this = this;
  46180. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  46181. /*
  46182. Parent Mesh name: ViveWand
  46183. - body
  46184. - r_gripper
  46185. - l_gripper
  46186. - menu_button
  46187. - system_button
  46188. - trackpad
  46189. - trigger
  46190. - LED
  46191. */
  46192. _this._defaultModel = newMeshes[1];
  46193. if (meshLoaded) {
  46194. meshLoaded(_this._defaultModel);
  46195. }
  46196. _this.attachToMesh(_this._defaultModel);
  46197. });
  46198. };
  46199. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  46200. get: function () {
  46201. return this.onMainButtonStateChangedObservable;
  46202. },
  46203. enumerable: true,
  46204. configurable: true
  46205. });
  46206. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  46207. get: function () {
  46208. return this.onMainButtonStateChangedObservable;
  46209. },
  46210. enumerable: true,
  46211. configurable: true
  46212. });
  46213. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  46214. get: function () {
  46215. return this.onSecondaryButtonStateChangedObservable;
  46216. },
  46217. enumerable: true,
  46218. configurable: true
  46219. });
  46220. /**
  46221. * Vive mapping:
  46222. * 0: touchpad
  46223. * 1: trigger
  46224. * 2: left AND right buttons
  46225. * 3: menu button
  46226. */
  46227. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  46228. var notifyObject = state; //{ state: state, changes: changes };
  46229. switch (buttonIdx) {
  46230. case 0:
  46231. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  46232. return;
  46233. case 1:
  46234. if (this._defaultModel) {
  46235. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  46236. }
  46237. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  46238. return;
  46239. case 2:
  46240. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  46241. return;
  46242. case 3:
  46243. if (this._defaultModel) {
  46244. if (notifyObject.pressed) {
  46245. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  46246. }
  46247. else {
  46248. (this._defaultModel.getChildren()[2]).position.y = 0;
  46249. }
  46250. }
  46251. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  46252. return;
  46253. }
  46254. };
  46255. return ViveController;
  46256. }(WebVRController));
  46257. BABYLON.ViveController = ViveController;
  46258. })(BABYLON || (BABYLON = {}));
  46259. //# sourceMappingURL=babylon.extendedGamepad.js.map
  46260. /// <reference path="babylon.targetCamera.ts" />
  46261. var BABYLON;
  46262. (function (BABYLON) {
  46263. var FollowCamera = (function (_super) {
  46264. __extends(FollowCamera, _super);
  46265. function FollowCamera(name, position, scene, lockedTarget) {
  46266. var _this = _super.call(this, name, position, scene) || this;
  46267. _this.radius = 12;
  46268. _this.rotationOffset = 0;
  46269. _this.heightOffset = 4;
  46270. _this.cameraAcceleration = 0.05;
  46271. _this.maxCameraSpeed = 20;
  46272. _this.lockedTarget = lockedTarget;
  46273. return _this;
  46274. }
  46275. FollowCamera.prototype.getRadians = function (degrees) {
  46276. return degrees * Math.PI / 180;
  46277. };
  46278. FollowCamera.prototype.follow = function (cameraTarget) {
  46279. if (!cameraTarget)
  46280. return;
  46281. var yRotation;
  46282. if (cameraTarget.rotationQuaternion) {
  46283. var rotMatrix = new BABYLON.Matrix();
  46284. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  46285. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  46286. }
  46287. else {
  46288. yRotation = cameraTarget.rotation.y;
  46289. }
  46290. var radians = this.getRadians(this.rotationOffset) + yRotation;
  46291. var targetPosition = cameraTarget.getAbsolutePosition();
  46292. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  46293. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  46294. var dx = targetX - this.position.x;
  46295. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  46296. var dz = (targetZ) - this.position.z;
  46297. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  46298. var vy = dy * this.cameraAcceleration;
  46299. var vz = dz * this.cameraAcceleration * 2;
  46300. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  46301. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  46302. }
  46303. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  46304. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  46305. }
  46306. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  46307. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  46308. }
  46309. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  46310. this.setTarget(targetPosition);
  46311. };
  46312. FollowCamera.prototype._checkInputs = function () {
  46313. _super.prototype._checkInputs.call(this);
  46314. this.follow(this.lockedTarget);
  46315. };
  46316. FollowCamera.prototype.getClassName = function () {
  46317. return "FollowCamera";
  46318. };
  46319. return FollowCamera;
  46320. }(BABYLON.TargetCamera));
  46321. __decorate([
  46322. BABYLON.serialize()
  46323. ], FollowCamera.prototype, "radius", void 0);
  46324. __decorate([
  46325. BABYLON.serialize()
  46326. ], FollowCamera.prototype, "rotationOffset", void 0);
  46327. __decorate([
  46328. BABYLON.serialize()
  46329. ], FollowCamera.prototype, "heightOffset", void 0);
  46330. __decorate([
  46331. BABYLON.serialize()
  46332. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  46333. __decorate([
  46334. BABYLON.serialize()
  46335. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  46336. __decorate([
  46337. BABYLON.serializeAsMeshReference("lockedTargetId")
  46338. ], FollowCamera.prototype, "lockedTarget", void 0);
  46339. BABYLON.FollowCamera = FollowCamera;
  46340. var ArcFollowCamera = (function (_super) {
  46341. __extends(ArcFollowCamera, _super);
  46342. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  46343. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  46344. _this.alpha = alpha;
  46345. _this.beta = beta;
  46346. _this.radius = radius;
  46347. _this.target = target;
  46348. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  46349. _this.follow();
  46350. return _this;
  46351. }
  46352. ArcFollowCamera.prototype.follow = function () {
  46353. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  46354. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  46355. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  46356. var targetPosition = this.target.getAbsolutePosition();
  46357. this.position = targetPosition.add(this._cartesianCoordinates);
  46358. this.setTarget(targetPosition);
  46359. };
  46360. ArcFollowCamera.prototype._checkInputs = function () {
  46361. _super.prototype._checkInputs.call(this);
  46362. this.follow();
  46363. };
  46364. ArcFollowCamera.prototype.getClassName = function () {
  46365. return "ArcFollowCamera";
  46366. };
  46367. return ArcFollowCamera;
  46368. }(BABYLON.TargetCamera));
  46369. BABYLON.ArcFollowCamera = ArcFollowCamera;
  46370. })(BABYLON || (BABYLON = {}));
  46371. //# sourceMappingURL=babylon.followCamera.js.map
  46372. /// <reference path="babylon.touchCamera.ts" />
  46373. var BABYLON;
  46374. (function (BABYLON) {
  46375. // We're mainly based on the logic defined into the FreeCamera code
  46376. var UniversalCamera = (function (_super) {
  46377. __extends(UniversalCamera, _super);
  46378. //-- end properties for backward compatibility for inputs
  46379. function UniversalCamera(name, position, scene) {
  46380. var _this = _super.call(this, name, position, scene) || this;
  46381. _this.inputs.addGamepad();
  46382. return _this;
  46383. }
  46384. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  46385. //-- Begin properties for backward compatibility for inputs
  46386. get: function () {
  46387. var gamepad = this.inputs.attached["gamepad"];
  46388. if (gamepad)
  46389. return gamepad.gamepadAngularSensibility;
  46390. },
  46391. set: function (value) {
  46392. var gamepad = this.inputs.attached["gamepad"];
  46393. if (gamepad)
  46394. gamepad.gamepadAngularSensibility = value;
  46395. },
  46396. enumerable: true,
  46397. configurable: true
  46398. });
  46399. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  46400. get: function () {
  46401. var gamepad = this.inputs.attached["gamepad"];
  46402. if (gamepad)
  46403. return gamepad.gamepadMoveSensibility;
  46404. },
  46405. set: function (value) {
  46406. var gamepad = this.inputs.attached["gamepad"];
  46407. if (gamepad)
  46408. gamepad.gamepadMoveSensibility = value;
  46409. },
  46410. enumerable: true,
  46411. configurable: true
  46412. });
  46413. UniversalCamera.prototype.getClassName = function () {
  46414. return "UniversalCamera";
  46415. };
  46416. return UniversalCamera;
  46417. }(BABYLON.TouchCamera));
  46418. BABYLON.UniversalCamera = UniversalCamera;
  46419. })(BABYLON || (BABYLON = {}));
  46420. //# sourceMappingURL=babylon.universalCamera.js.map
  46421. /// <reference path="babylon.universalCamera.ts" />
  46422. var BABYLON;
  46423. (function (BABYLON) {
  46424. // We're mainly based on the logic defined into the FreeCamera code
  46425. var GamepadCamera = (function (_super) {
  46426. __extends(GamepadCamera, _super);
  46427. //-- end properties for backward compatibility for inputs
  46428. function GamepadCamera(name, position, scene) {
  46429. return _super.call(this, name, position, scene) || this;
  46430. }
  46431. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  46432. //-- Begin properties for backward compatibility for inputs
  46433. get: function () {
  46434. var gamepad = this.inputs.attached["gamepad"];
  46435. if (gamepad)
  46436. return gamepad.gamepadAngularSensibility;
  46437. },
  46438. set: function (value) {
  46439. var gamepad = this.inputs.attached["gamepad"];
  46440. if (gamepad)
  46441. gamepad.gamepadAngularSensibility = value;
  46442. },
  46443. enumerable: true,
  46444. configurable: true
  46445. });
  46446. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  46447. get: function () {
  46448. var gamepad = this.inputs.attached["gamepad"];
  46449. if (gamepad)
  46450. return gamepad.gamepadMoveSensibility;
  46451. },
  46452. set: function (value) {
  46453. var gamepad = this.inputs.attached["gamepad"];
  46454. if (gamepad)
  46455. gamepad.gamepadMoveSensibility = value;
  46456. },
  46457. enumerable: true,
  46458. configurable: true
  46459. });
  46460. GamepadCamera.prototype.getClassName = function () {
  46461. return "GamepadCamera";
  46462. };
  46463. return GamepadCamera;
  46464. }(BABYLON.UniversalCamera));
  46465. BABYLON.GamepadCamera = GamepadCamera;
  46466. })(BABYLON || (BABYLON = {}));
  46467. //# sourceMappingURL=babylon.gamepadCamera.js.map
  46468. var BABYLON;
  46469. (function (BABYLON) {
  46470. var PostProcessRenderPipelineManager = (function () {
  46471. function PostProcessRenderPipelineManager() {
  46472. this._renderPipelines = {};
  46473. }
  46474. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  46475. this._renderPipelines[renderPipeline._name] = renderPipeline;
  46476. };
  46477. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  46478. var renderPipeline = this._renderPipelines[renderPipelineName];
  46479. if (!renderPipeline) {
  46480. return;
  46481. }
  46482. renderPipeline._attachCameras(cameras, unique);
  46483. };
  46484. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  46485. var renderPipeline = this._renderPipelines[renderPipelineName];
  46486. if (!renderPipeline) {
  46487. return;
  46488. }
  46489. renderPipeline._detachCameras(cameras);
  46490. };
  46491. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  46492. var renderPipeline = this._renderPipelines[renderPipelineName];
  46493. if (!renderPipeline) {
  46494. return;
  46495. }
  46496. renderPipeline._enableEffect(renderEffectName, cameras);
  46497. };
  46498. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  46499. var renderPipeline = this._renderPipelines[renderPipelineName];
  46500. if (!renderPipeline) {
  46501. return;
  46502. }
  46503. renderPipeline._disableEffect(renderEffectName, cameras);
  46504. };
  46505. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  46506. var renderPipeline = this._renderPipelines[renderPipelineName];
  46507. if (!renderPipeline) {
  46508. return;
  46509. }
  46510. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  46511. };
  46512. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  46513. var renderPipeline = this._renderPipelines[renderPipelineName];
  46514. if (!renderPipeline) {
  46515. return;
  46516. }
  46517. renderPipeline._disableDisplayOnlyPass(cameras);
  46518. };
  46519. PostProcessRenderPipelineManager.prototype.update = function () {
  46520. for (var renderPipelineName in this._renderPipelines) {
  46521. var pipeline = this._renderPipelines[renderPipelineName];
  46522. if (!pipeline.isSupported) {
  46523. pipeline.dispose();
  46524. delete this._renderPipelines[renderPipelineName];
  46525. }
  46526. else {
  46527. pipeline._update();
  46528. }
  46529. }
  46530. };
  46531. return PostProcessRenderPipelineManager;
  46532. }());
  46533. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  46534. })(BABYLON || (BABYLON = {}));
  46535. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  46536. var BABYLON;
  46537. (function (BABYLON) {
  46538. var PostProcessRenderPass = (function () {
  46539. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  46540. this._enabled = true;
  46541. this._refCount = 0;
  46542. this._name = name;
  46543. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  46544. this.setRenderList(renderList);
  46545. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  46546. this._renderTexture.onAfterRenderObservable.add(afterRender);
  46547. this._scene = scene;
  46548. this._renderList = renderList;
  46549. }
  46550. // private
  46551. PostProcessRenderPass.prototype._incRefCount = function () {
  46552. if (this._refCount === 0) {
  46553. this._scene.customRenderTargets.push(this._renderTexture);
  46554. }
  46555. return ++this._refCount;
  46556. };
  46557. PostProcessRenderPass.prototype._decRefCount = function () {
  46558. this._refCount--;
  46559. if (this._refCount <= 0) {
  46560. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  46561. }
  46562. return this._refCount;
  46563. };
  46564. PostProcessRenderPass.prototype._update = function () {
  46565. this.setRenderList(this._renderList);
  46566. };
  46567. // public
  46568. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  46569. this._renderTexture.renderList = renderList;
  46570. };
  46571. PostProcessRenderPass.prototype.getRenderTexture = function () {
  46572. return this._renderTexture;
  46573. };
  46574. return PostProcessRenderPass;
  46575. }());
  46576. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  46577. })(BABYLON || (BABYLON = {}));
  46578. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  46579. var BABYLON;
  46580. (function (BABYLON) {
  46581. var PostProcessRenderEffect = (function () {
  46582. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  46583. this._engine = engine;
  46584. this._name = name;
  46585. this._singleInstance = singleInstance || true;
  46586. this._getPostProcess = getPostProcess;
  46587. this._cameras = [];
  46588. this._indicesForCamera = [];
  46589. this._postProcesses = {};
  46590. this._renderPasses = {};
  46591. this._renderEffectAsPasses = {};
  46592. }
  46593. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  46594. get: function () {
  46595. for (var index in this._postProcesses) {
  46596. if (!this._postProcesses[index].isSupported) {
  46597. return false;
  46598. }
  46599. }
  46600. return true;
  46601. },
  46602. enumerable: true,
  46603. configurable: true
  46604. });
  46605. PostProcessRenderEffect.prototype._update = function () {
  46606. for (var renderPassName in this._renderPasses) {
  46607. this._renderPasses[renderPassName]._update();
  46608. }
  46609. };
  46610. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  46611. this._renderPasses[renderPass._name] = renderPass;
  46612. this._linkParameters();
  46613. };
  46614. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  46615. delete this._renderPasses[renderPass._name];
  46616. this._linkParameters();
  46617. };
  46618. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  46619. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  46620. this._linkParameters();
  46621. };
  46622. PostProcessRenderEffect.prototype.getPass = function (passName) {
  46623. for (var renderPassName in this._renderPasses) {
  46624. if (renderPassName === passName) {
  46625. return this._renderPasses[passName];
  46626. }
  46627. }
  46628. };
  46629. PostProcessRenderEffect.prototype.emptyPasses = function () {
  46630. this._renderPasses = {};
  46631. this._linkParameters();
  46632. };
  46633. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  46634. var cameraKey;
  46635. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46636. for (var i = 0; i < _cam.length; i++) {
  46637. var camera = _cam[i];
  46638. var cameraName = camera.name;
  46639. if (this._singleInstance) {
  46640. cameraKey = 0;
  46641. }
  46642. else {
  46643. cameraKey = cameraName;
  46644. }
  46645. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  46646. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  46647. if (!this._indicesForCamera[cameraName]) {
  46648. this._indicesForCamera[cameraName] = [];
  46649. }
  46650. this._indicesForCamera[cameraName].push(index);
  46651. if (this._cameras.indexOf(camera) === -1) {
  46652. this._cameras[cameraName] = camera;
  46653. }
  46654. for (var passName in this._renderPasses) {
  46655. this._renderPasses[passName]._incRefCount();
  46656. }
  46657. }
  46658. this._linkParameters();
  46659. };
  46660. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  46661. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46662. for (var i = 0; i < _cam.length; i++) {
  46663. var camera = _cam[i];
  46664. var cameraName = camera.name;
  46665. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  46666. var index = this._cameras.indexOf(cameraName);
  46667. this._indicesForCamera.splice(index, 1);
  46668. this._cameras.splice(index, 1);
  46669. for (var passName in this._renderPasses) {
  46670. this._renderPasses[passName]._decRefCount();
  46671. }
  46672. }
  46673. };
  46674. PostProcessRenderEffect.prototype._enable = function (cameras) {
  46675. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46676. for (var i = 0; i < _cam.length; i++) {
  46677. var camera = _cam[i];
  46678. var cameraName = camera.name;
  46679. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  46680. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  46681. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  46682. }
  46683. }
  46684. for (var passName in this._renderPasses) {
  46685. this._renderPasses[passName]._incRefCount();
  46686. }
  46687. }
  46688. };
  46689. PostProcessRenderEffect.prototype._disable = function (cameras) {
  46690. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46691. for (var i = 0; i < _cam.length; i++) {
  46692. var camera = _cam[i];
  46693. var cameraName = camera.Name;
  46694. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  46695. for (var passName in this._renderPasses) {
  46696. this._renderPasses[passName]._decRefCount();
  46697. }
  46698. }
  46699. };
  46700. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  46701. if (this._singleInstance) {
  46702. return this._postProcesses[0];
  46703. }
  46704. else {
  46705. return this._postProcesses[camera.name];
  46706. }
  46707. };
  46708. PostProcessRenderEffect.prototype._linkParameters = function () {
  46709. var _this = this;
  46710. for (var index in this._postProcesses) {
  46711. if (this.applyParameters) {
  46712. this.applyParameters(this._postProcesses[index]);
  46713. }
  46714. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  46715. _this._linkTextures(effect);
  46716. });
  46717. }
  46718. };
  46719. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  46720. for (var renderPassName in this._renderPasses) {
  46721. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  46722. }
  46723. for (var renderEffectName in this._renderEffectAsPasses) {
  46724. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  46725. }
  46726. };
  46727. return PostProcessRenderEffect;
  46728. }());
  46729. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  46730. })(BABYLON || (BABYLON = {}));
  46731. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  46732. var BABYLON;
  46733. (function (BABYLON) {
  46734. var PostProcessRenderPipeline = (function () {
  46735. function PostProcessRenderPipeline(engine, name) {
  46736. this._engine = engine;
  46737. this._name = name;
  46738. this._renderEffects = {};
  46739. this._renderEffectsForIsolatedPass = {};
  46740. this._cameras = [];
  46741. }
  46742. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  46743. get: function () {
  46744. for (var renderEffectName in this._renderEffects) {
  46745. if (!this._renderEffects[renderEffectName].isSupported) {
  46746. return false;
  46747. }
  46748. }
  46749. return true;
  46750. },
  46751. enumerable: true,
  46752. configurable: true
  46753. });
  46754. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  46755. this._renderEffects[renderEffect._name] = renderEffect;
  46756. };
  46757. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  46758. var renderEffects = this._renderEffects[renderEffectName];
  46759. if (!renderEffects) {
  46760. return;
  46761. }
  46762. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  46763. };
  46764. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  46765. var renderEffects = this._renderEffects[renderEffectName];
  46766. if (!renderEffects) {
  46767. return;
  46768. }
  46769. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  46770. };
  46771. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  46772. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46773. var indicesToDelete = [];
  46774. var i;
  46775. for (i = 0; i < _cam.length; i++) {
  46776. var camera = _cam[i];
  46777. var cameraName = camera.name;
  46778. if (this._cameras.indexOf(camera) === -1) {
  46779. this._cameras[cameraName] = camera;
  46780. }
  46781. else if (unique) {
  46782. indicesToDelete.push(i);
  46783. }
  46784. }
  46785. for (i = 0; i < indicesToDelete.length; i++) {
  46786. cameras.splice(indicesToDelete[i], 1);
  46787. }
  46788. for (var renderEffectName in this._renderEffects) {
  46789. this._renderEffects[renderEffectName]._attachCameras(_cam);
  46790. }
  46791. };
  46792. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  46793. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46794. for (var renderEffectName in this._renderEffects) {
  46795. this._renderEffects[renderEffectName]._detachCameras(_cam);
  46796. }
  46797. for (var i = 0; i < _cam.length; i++) {
  46798. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  46799. }
  46800. };
  46801. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  46802. var _this = this;
  46803. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46804. var pass = null;
  46805. var renderEffectName;
  46806. for (renderEffectName in this._renderEffects) {
  46807. pass = this._renderEffects[renderEffectName].getPass(passName);
  46808. if (pass != null) {
  46809. break;
  46810. }
  46811. }
  46812. if (pass === null) {
  46813. return;
  46814. }
  46815. for (renderEffectName in this._renderEffects) {
  46816. this._renderEffects[renderEffectName]._disable(_cam);
  46817. }
  46818. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  46819. for (var i = 0; i < _cam.length; i++) {
  46820. var camera = _cam[i];
  46821. var cameraName = camera.name;
  46822. 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); });
  46823. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  46824. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  46825. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  46826. }
  46827. };
  46828. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  46829. var _this = this;
  46830. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46831. for (var i = 0; i < _cam.length; i++) {
  46832. var camera = _cam[i];
  46833. var cameraName = camera.name;
  46834. 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); });
  46835. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  46836. }
  46837. for (var renderEffectName in this._renderEffects) {
  46838. this._renderEffects[renderEffectName]._enable(_cam);
  46839. }
  46840. };
  46841. PostProcessRenderPipeline.prototype._update = function () {
  46842. for (var renderEffectName in this._renderEffects) {
  46843. this._renderEffects[renderEffectName]._update();
  46844. }
  46845. for (var i = 0; i < this._cameras.length; i++) {
  46846. var cameraName = this._cameras[i].name;
  46847. if (this._renderEffectsForIsolatedPass[cameraName]) {
  46848. this._renderEffectsForIsolatedPass[cameraName]._update();
  46849. }
  46850. }
  46851. };
  46852. PostProcessRenderPipeline.prototype.dispose = function () {
  46853. // Must be implemented by children
  46854. };
  46855. return PostProcessRenderPipeline;
  46856. }());
  46857. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  46858. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  46859. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  46860. })(BABYLON || (BABYLON = {}));
  46861. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  46862. var BABYLON;
  46863. (function (BABYLON) {
  46864. var DepthRenderer = (function () {
  46865. function DepthRenderer(scene, type) {
  46866. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  46867. var _this = this;
  46868. this._viewMatrix = BABYLON.Matrix.Zero();
  46869. this._projectionMatrix = BABYLON.Matrix.Zero();
  46870. this._transformMatrix = BABYLON.Matrix.Zero();
  46871. this._worldViewProjection = BABYLON.Matrix.Zero();
  46872. this._scene = scene;
  46873. var engine = scene.getEngine();
  46874. // Render target
  46875. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  46876. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46877. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46878. this._depthMap.refreshRate = 1;
  46879. this._depthMap.renderParticles = false;
  46880. this._depthMap.renderList = null;
  46881. // set default depth value to 1.0 (far away)
  46882. this._depthMap.onClearObservable.add(function (engine) {
  46883. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  46884. });
  46885. // Custom render function
  46886. var renderSubMesh = function (subMesh) {
  46887. var mesh = subMesh.getRenderingMesh();
  46888. var scene = _this._scene;
  46889. var engine = scene.getEngine();
  46890. // Culling
  46891. engine.setState(subMesh.getMaterial().backFaceCulling);
  46892. // Managing instances
  46893. var batch = mesh._getInstancesRenderList(subMesh._id);
  46894. if (batch.mustReturn) {
  46895. return;
  46896. }
  46897. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  46898. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  46899. engine.enableEffect(_this._effect);
  46900. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  46901. var material = subMesh.getMaterial();
  46902. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  46903. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  46904. // Alpha test
  46905. if (material && material.needAlphaTesting()) {
  46906. var alphaTexture = material.getAlphaTestTexture();
  46907. _this._effect.setTexture("diffuseSampler", alphaTexture);
  46908. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  46909. }
  46910. // Bones
  46911. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46912. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  46913. }
  46914. // Draw
  46915. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  46916. }
  46917. };
  46918. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  46919. var index;
  46920. for (index = 0; index < opaqueSubMeshes.length; index++) {
  46921. renderSubMesh(opaqueSubMeshes.data[index]);
  46922. }
  46923. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  46924. renderSubMesh(alphaTestSubMeshes.data[index]);
  46925. }
  46926. };
  46927. }
  46928. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  46929. var material = subMesh.getMaterial();
  46930. if (material.disableDepthWrite) {
  46931. return false;
  46932. }
  46933. var defines = [];
  46934. var attribs = [BABYLON.VertexBuffer.PositionKind];
  46935. var mesh = subMesh.getMesh();
  46936. var scene = mesh.getScene();
  46937. // Alpha test
  46938. if (material && material.needAlphaTesting()) {
  46939. defines.push("#define ALPHATEST");
  46940. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  46941. attribs.push(BABYLON.VertexBuffer.UVKind);
  46942. defines.push("#define UV1");
  46943. }
  46944. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  46945. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  46946. defines.push("#define UV2");
  46947. }
  46948. }
  46949. // Bones
  46950. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46951. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  46952. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  46953. if (mesh.numBoneInfluencers > 4) {
  46954. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  46955. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  46956. }
  46957. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46958. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46959. }
  46960. else {
  46961. defines.push("#define NUM_BONE_INFLUENCERS 0");
  46962. }
  46963. // Instances
  46964. if (useInstances) {
  46965. defines.push("#define INSTANCES");
  46966. attribs.push("world0");
  46967. attribs.push("world1");
  46968. attribs.push("world2");
  46969. attribs.push("world3");
  46970. }
  46971. // Get correct effect
  46972. var join = defines.join("\n");
  46973. if (this._cachedDefines !== join) {
  46974. this._cachedDefines = join;
  46975. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  46976. }
  46977. return this._effect.isReady();
  46978. };
  46979. DepthRenderer.prototype.getDepthMap = function () {
  46980. return this._depthMap;
  46981. };
  46982. // Methods
  46983. DepthRenderer.prototype.dispose = function () {
  46984. this._depthMap.dispose();
  46985. };
  46986. return DepthRenderer;
  46987. }());
  46988. BABYLON.DepthRenderer = DepthRenderer;
  46989. })(BABYLON || (BABYLON = {}));
  46990. //# sourceMappingURL=babylon.depthRenderer.js.map
  46991. var BABYLON;
  46992. (function (BABYLON) {
  46993. var SSAORenderingPipeline = (function (_super) {
  46994. __extends(SSAORenderingPipeline, _super);
  46995. /**
  46996. * @constructor
  46997. * @param {string} name - The rendering pipeline name
  46998. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  46999. * @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 }
  47000. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47001. */
  47002. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  47003. var _this = _super.call(this, scene.getEngine(), name) || this;
  47004. // Members
  47005. /**
  47006. * The PassPostProcess id in the pipeline that contains the original scene color
  47007. * @type {string}
  47008. */
  47009. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  47010. /**
  47011. * The SSAO PostProcess id in the pipeline
  47012. * @type {string}
  47013. */
  47014. _this.SSAORenderEffect = "SSAORenderEffect";
  47015. /**
  47016. * The horizontal blur PostProcess id in the pipeline
  47017. * @type {string}
  47018. */
  47019. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  47020. /**
  47021. * The vertical blur PostProcess id in the pipeline
  47022. * @type {string}
  47023. */
  47024. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  47025. /**
  47026. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  47027. * @type {string}
  47028. */
  47029. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  47030. /**
  47031. * The output strength of the SSAO post-process. Default value is 1.0.
  47032. * @type {number}
  47033. */
  47034. _this.totalStrength = 1.0;
  47035. /**
  47036. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  47037. * @type {number}
  47038. */
  47039. _this.radius = 0.0001;
  47040. /**
  47041. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  47042. * Must not be equal to fallOff and superior to fallOff.
  47043. * Default value is 0.975
  47044. * @type {number}
  47045. */
  47046. _this.area = 0.0075;
  47047. /**
  47048. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  47049. * Must not be equal to area and inferior to area.
  47050. * Default value is 0.0
  47051. * @type {number}
  47052. */
  47053. _this.fallOff = 0.000001;
  47054. /**
  47055. * The base color of the SSAO post-process
  47056. * The final result is "base + ssao" between [0, 1]
  47057. * @type {number}
  47058. */
  47059. _this.base = 0.5;
  47060. _this._firstUpdate = true;
  47061. _this._scene = scene;
  47062. // Set up assets
  47063. _this._createRandomTexture();
  47064. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  47065. var ssaoRatio = ratio.ssaoRatio || ratio;
  47066. var combineRatio = ratio.combineRatio || ratio;
  47067. _this._ratio = {
  47068. ssaoRatio: ssaoRatio,
  47069. combineRatio: combineRatio
  47070. };
  47071. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  47072. _this._createSSAOPostProcess(ssaoRatio);
  47073. _this._createBlurPostProcess(ssaoRatio);
  47074. _this._createSSAOCombinePostProcess(combineRatio);
  47075. // Set up pipeline
  47076. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  47077. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  47078. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  47079. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  47080. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  47081. // Finish
  47082. scene.postProcessRenderPipelineManager.addPipeline(_this);
  47083. if (cameras)
  47084. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47085. return _this;
  47086. }
  47087. // Public Methods
  47088. /**
  47089. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  47090. */
  47091. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  47092. if (disableDepthRender === void 0) { disableDepthRender = false; }
  47093. for (var i = 0; i < this._scene.cameras.length; i++) {
  47094. var camera = this._scene.cameras[i];
  47095. this._originalColorPostProcess.dispose(camera);
  47096. this._ssaoPostProcess.dispose(camera);
  47097. this._blurHPostProcess.dispose(camera);
  47098. this._blurVPostProcess.dispose(camera);
  47099. this._ssaoCombinePostProcess.dispose(camera);
  47100. }
  47101. this._randomTexture.dispose();
  47102. if (disableDepthRender)
  47103. this._scene.disableDepthRenderer();
  47104. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47105. _super.prototype.dispose.call(this);
  47106. };
  47107. // Private Methods
  47108. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  47109. var _this = this;
  47110. /*
  47111. var samplerOffsets = [
  47112. -8.0, -6.0, -4.0, -2.0,
  47113. 0.0,
  47114. 2.0, 4.0, 6.0, 8.0
  47115. ];
  47116. */
  47117. var samples = 16;
  47118. var samplerOffsets = [];
  47119. for (var i = -8; i < 8; i++) {
  47120. samplerOffsets.push(i * 2);
  47121. }
  47122. this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16");
  47123. this._blurHPostProcess.onApply = function (effect) {
  47124. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  47125. effect.setTexture("depthSampler", _this._depthTexture);
  47126. if (_this._firstUpdate) {
  47127. effect.setArray("samplerOffsets", samplerOffsets);
  47128. }
  47129. };
  47130. this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define SAMPLES 16");
  47131. this._blurVPostProcess.onApply = function (effect) {
  47132. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  47133. effect.setTexture("depthSampler", _this._depthTexture);
  47134. if (_this._firstUpdate) {
  47135. effect.setArray("samplerOffsets", samplerOffsets);
  47136. _this._firstUpdate = false;
  47137. }
  47138. };
  47139. };
  47140. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  47141. var _this = this;
  47142. var numSamples = 16;
  47143. var sampleSphere = [
  47144. 0.5381, 0.1856, -0.4319,
  47145. 0.1379, 0.2486, 0.4430,
  47146. 0.3371, 0.5679, -0.0057,
  47147. -0.6999, -0.0451, -0.0019,
  47148. 0.0689, -0.1598, -0.8547,
  47149. 0.0560, 0.0069, -0.1843,
  47150. -0.0146, 0.1402, 0.0762,
  47151. 0.0100, -0.1924, -0.0344,
  47152. -0.3577, -0.5301, -0.4358,
  47153. -0.3169, 0.1063, 0.0158,
  47154. 0.0103, -0.5869, 0.0046,
  47155. -0.0897, -0.4940, 0.3287,
  47156. 0.7119, -0.0154, -0.0918,
  47157. -0.0533, 0.0596, -0.5411,
  47158. 0.0352, -0.0631, 0.5460,
  47159. -0.4776, 0.2847, -0.0271
  47160. ];
  47161. var samplesFactor = 1.0 / numSamples;
  47162. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  47163. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  47164. "area", "fallOff", "base", "range", "viewport"
  47165. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  47166. var viewport = new BABYLON.Vector2(0, 0);
  47167. this._ssaoPostProcess.onApply = function (effect) {
  47168. if (_this._firstUpdate) {
  47169. effect.setArray3("sampleSphere", sampleSphere);
  47170. effect.setFloat("samplesFactor", samplesFactor);
  47171. effect.setFloat("randTextureTiles", 4.0);
  47172. }
  47173. effect.setFloat("totalStrength", _this.totalStrength);
  47174. effect.setFloat("radius", _this.radius);
  47175. effect.setFloat("area", _this.area);
  47176. effect.setFloat("fallOff", _this.fallOff);
  47177. effect.setFloat("base", _this.base);
  47178. effect.setTexture("textureSampler", _this._depthTexture);
  47179. effect.setTexture("randomSampler", _this._randomTexture);
  47180. };
  47181. };
  47182. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  47183. var _this = this;
  47184. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47185. this._ssaoCombinePostProcess.onApply = function (effect) {
  47186. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  47187. };
  47188. };
  47189. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  47190. var size = 512;
  47191. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  47192. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  47193. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  47194. var context = this._randomTexture.getContext();
  47195. var rand = function (min, max) {
  47196. return Math.random() * (max - min) + min;
  47197. };
  47198. var randVector = BABYLON.Vector3.Zero();
  47199. for (var x = 0; x < size; x++) {
  47200. for (var y = 0; y < size; y++) {
  47201. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  47202. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  47203. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  47204. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  47205. context.fillRect(x, y, 1, 1);
  47206. }
  47207. }
  47208. this._randomTexture.update(false);
  47209. };
  47210. return SSAORenderingPipeline;
  47211. }(BABYLON.PostProcessRenderPipeline));
  47212. __decorate([
  47213. BABYLON.serialize()
  47214. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  47215. __decorate([
  47216. BABYLON.serialize()
  47217. ], SSAORenderingPipeline.prototype, "radius", void 0);
  47218. __decorate([
  47219. BABYLON.serialize()
  47220. ], SSAORenderingPipeline.prototype, "area", void 0);
  47221. __decorate([
  47222. BABYLON.serialize()
  47223. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  47224. __decorate([
  47225. BABYLON.serialize()
  47226. ], SSAORenderingPipeline.prototype, "base", void 0);
  47227. __decorate([
  47228. BABYLON.serialize()
  47229. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  47230. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  47231. })(BABYLON || (BABYLON = {}));
  47232. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  47233. // BABYLON.JS Chromatic Aberration GLSL Shader
  47234. // Author: Olivier Guyot
  47235. // Separates very slightly R, G and B colors on the edges of the screen
  47236. // Inspired by Francois Tarlier & Martins Upitis
  47237. var BABYLON;
  47238. (function (BABYLON) {
  47239. var LensRenderingPipeline = (function (_super) {
  47240. __extends(LensRenderingPipeline, _super);
  47241. /**
  47242. * @constructor
  47243. *
  47244. * Effect parameters are as follow:
  47245. * {
  47246. * chromatic_aberration: number; // from 0 to x (1 for realism)
  47247. * edge_blur: number; // from 0 to x (1 for realism)
  47248. * distortion: number; // from 0 to x (1 for realism)
  47249. * grain_amount: number; // from 0 to 1
  47250. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  47251. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  47252. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  47253. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  47254. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  47255. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  47256. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  47257. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  47258. * }
  47259. * Note: if an effect parameter is unset, effect is disabled
  47260. *
  47261. * @param {string} name - The rendering pipeline name
  47262. * @param {object} parameters - An object containing all parameters (see above)
  47263. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47264. * @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)
  47265. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47266. */
  47267. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  47268. if (ratio === void 0) { ratio = 1.0; }
  47269. var _this = _super.call(this, scene.getEngine(), name) || this;
  47270. // Lens effects can be of the following:
  47271. // - chromatic aberration (slight shift of RGB colors)
  47272. // - blur on the edge of the lens
  47273. // - lens distortion
  47274. // - depth-of-field blur & highlights enhancing
  47275. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  47276. // - grain effect (noise or custom texture)
  47277. // Two additional texture samplers are needed:
  47278. // - depth map (for depth-of-field)
  47279. // - grain texture
  47280. /**
  47281. * The chromatic aberration PostProcess id in the pipeline
  47282. * @type {string}
  47283. */
  47284. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  47285. /**
  47286. * The highlights enhancing PostProcess id in the pipeline
  47287. * @type {string}
  47288. */
  47289. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  47290. /**
  47291. * The depth-of-field PostProcess id in the pipeline
  47292. * @type {string}
  47293. */
  47294. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  47295. _this._scene = scene;
  47296. // Fetch texture samplers
  47297. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  47298. if (parameters.grain_texture) {
  47299. _this._grainTexture = parameters.grain_texture;
  47300. }
  47301. else {
  47302. _this._createGrainTexture();
  47303. }
  47304. // save parameters
  47305. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  47306. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  47307. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  47308. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  47309. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  47310. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  47311. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  47312. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  47313. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  47314. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  47315. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  47316. // Create effects
  47317. _this._createChromaticAberrationPostProcess(ratio);
  47318. _this._createHighlightsPostProcess(ratio);
  47319. _this._createDepthOfFieldPostProcess(ratio / 4);
  47320. // Set up pipeline
  47321. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  47322. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  47323. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  47324. if (_this._highlightsGain === -1) {
  47325. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  47326. }
  47327. // Finish
  47328. scene.postProcessRenderPipelineManager.addPipeline(_this);
  47329. if (cameras) {
  47330. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47331. }
  47332. return _this;
  47333. }
  47334. // public methods (self explanatory)
  47335. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  47336. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  47337. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  47338. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  47339. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  47340. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  47341. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  47342. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  47343. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  47344. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  47345. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  47346. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  47347. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  47348. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  47349. };
  47350. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  47351. this._highlightsPostProcess.updateEffect();
  47352. };
  47353. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  47354. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  47355. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  47356. this._highlightsGain = amount;
  47357. };
  47358. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  47359. if (this._highlightsGain === -1) {
  47360. this._highlightsGain = 1.0;
  47361. }
  47362. this._highlightsThreshold = amount;
  47363. };
  47364. LensRenderingPipeline.prototype.disableHighlights = function () {
  47365. this._highlightsGain = -1;
  47366. };
  47367. /**
  47368. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  47369. */
  47370. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  47371. if (disableDepthRender === void 0) { disableDepthRender = false; }
  47372. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47373. this._chromaticAberrationPostProcess = undefined;
  47374. this._highlightsPostProcess = undefined;
  47375. this._depthOfFieldPostProcess = undefined;
  47376. this._grainTexture.dispose();
  47377. if (disableDepthRender)
  47378. this._scene.disableDepthRenderer();
  47379. };
  47380. // colors shifting and distortion
  47381. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  47382. var _this = this;
  47383. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  47384. [], // samplers
  47385. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47386. this._chromaticAberrationPostProcess.onApply = function (effect) {
  47387. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  47388. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47389. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47390. };
  47391. };
  47392. // highlights enhancing
  47393. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  47394. var _this = this;
  47395. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  47396. [], // samplers
  47397. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  47398. this._highlightsPostProcess.onApply = function (effect) {
  47399. effect.setFloat('gain', _this._highlightsGain);
  47400. effect.setFloat('threshold', _this._highlightsThreshold);
  47401. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  47402. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47403. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47404. };
  47405. };
  47406. // colors shifting and distortion
  47407. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  47408. var _this = this;
  47409. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  47410. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  47411. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  47412. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47413. this._depthOfFieldPostProcess.onApply = function (effect) {
  47414. effect.setTexture("depthSampler", _this._depthTexture);
  47415. effect.setTexture("grainSampler", _this._grainTexture);
  47416. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  47417. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  47418. effect.setFloat('grain_amount', _this._grainAmount);
  47419. effect.setBool('blur_noise', _this._blurNoise);
  47420. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47421. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47422. effect.setFloat('distortion', _this._distortion);
  47423. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  47424. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  47425. effect.setFloat('aperture', _this._dofAperture);
  47426. effect.setFloat('darken', _this._dofDarken);
  47427. effect.setFloat('edge_blur', _this._edgeBlur);
  47428. effect.setBool('highlights', (_this._highlightsGain !== -1));
  47429. effect.setFloat('near', _this._scene.activeCamera.minZ);
  47430. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  47431. };
  47432. };
  47433. // creates a black and white random noise texture, 512x512
  47434. LensRenderingPipeline.prototype._createGrainTexture = function () {
  47435. var size = 512;
  47436. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47437. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  47438. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  47439. var context = this._grainTexture.getContext();
  47440. var rand = function (min, max) {
  47441. return Math.random() * (max - min) + min;
  47442. };
  47443. var value;
  47444. for (var x = 0; x < size; x++) {
  47445. for (var y = 0; y < size; y++) {
  47446. value = Math.floor(rand(0.42, 0.58) * 255);
  47447. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  47448. context.fillRect(x, y, 1, 1);
  47449. }
  47450. }
  47451. this._grainTexture.update(false);
  47452. };
  47453. return LensRenderingPipeline;
  47454. }(BABYLON.PostProcessRenderPipeline));
  47455. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  47456. })(BABYLON || (BABYLON = {}));
  47457. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  47458. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  47459. var BABYLON;
  47460. (function (BABYLON) {
  47461. var HDRRenderingPipeline = (function (_super) {
  47462. __extends(HDRRenderingPipeline, _super);
  47463. /**
  47464. * @constructor
  47465. * @param {string} name - The rendering pipeline name
  47466. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47467. * @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)
  47468. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  47469. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47470. */
  47471. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  47472. if (originalPostProcess === void 0) { originalPostProcess = null; }
  47473. var _this = _super.call(this, scene.getEngine(), name) || this;
  47474. /**
  47475. * Public members
  47476. */
  47477. // Gaussian Blur
  47478. /**
  47479. * Gaussian blur coefficient
  47480. * @type {number}
  47481. */
  47482. _this.gaussCoeff = 0.3;
  47483. /**
  47484. * Gaussian blur mean
  47485. * @type {number}
  47486. */
  47487. _this.gaussMean = 1.0;
  47488. /**
  47489. * Gaussian blur standard deviation
  47490. * @type {number}
  47491. */
  47492. _this.gaussStandDev = 0.8;
  47493. /**
  47494. * Gaussian blur multiplier. Multiplies the blur effect
  47495. * @type {number}
  47496. */
  47497. _this.gaussMultiplier = 4.0;
  47498. // HDR
  47499. /**
  47500. * Exposure, controls the overall intensity of the pipeline
  47501. * @type {number}
  47502. */
  47503. _this.exposure = 1.0;
  47504. /**
  47505. * Minimum luminance that the post-process can output. Luminance is >= 0
  47506. * @type {number}
  47507. */
  47508. _this.minimumLuminance = 1.0;
  47509. /**
  47510. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  47511. * @type {number}
  47512. */
  47513. _this.maximumLuminance = 1e20;
  47514. /**
  47515. * Increase rate for luminance: eye adaptation speed to dark
  47516. * @type {number}
  47517. */
  47518. _this.luminanceIncreaserate = 0.5;
  47519. /**
  47520. * Decrease rate for luminance: eye adaptation speed to bright
  47521. * @type {number}
  47522. */
  47523. _this.luminanceDecreaseRate = 0.5;
  47524. // Bright pass
  47525. /**
  47526. * Minimum luminance needed to compute HDR
  47527. * @type {number}
  47528. */
  47529. _this.brightThreshold = 0.8;
  47530. _this._needUpdate = true;
  47531. _this._scene = scene;
  47532. // Bright pass
  47533. _this._createBrightPassPostProcess(scene, ratio);
  47534. // Down sample X4
  47535. _this._createDownSampleX4PostProcess(scene, ratio);
  47536. // Create gaussian blur post-processes
  47537. _this._createGaussianBlurPostProcess(scene, ratio);
  47538. // Texture adder
  47539. _this._createTextureAdderPostProcess(scene, ratio);
  47540. // Luminance generator
  47541. _this._createLuminanceGeneratorPostProcess(scene);
  47542. // HDR
  47543. _this._createHDRPostProcess(scene, ratio);
  47544. // Pass postprocess
  47545. if (originalPostProcess === null) {
  47546. _this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  47547. }
  47548. else {
  47549. _this._originalPostProcess = originalPostProcess;
  47550. }
  47551. // Configure pipeline
  47552. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  47553. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  47554. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  47555. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  47556. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  47557. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  47558. var addDownSamplerPostProcess = function (id) {
  47559. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  47560. };
  47561. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  47562. addDownSamplerPostProcess(i);
  47563. }
  47564. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  47565. // Finish
  47566. scene.postProcessRenderPipelineManager.addPipeline(_this);
  47567. if (cameras !== null) {
  47568. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47569. }
  47570. _this.update();
  47571. return _this;
  47572. }
  47573. /**
  47574. * Tells the pipeline to update its post-processes
  47575. */
  47576. HDRRenderingPipeline.prototype.update = function () {
  47577. this._needUpdate = true;
  47578. };
  47579. /**
  47580. * Returns the current calculated luminance
  47581. */
  47582. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  47583. return this._hdrCurrentLuminance;
  47584. };
  47585. /**
  47586. * Returns the currently drawn luminance
  47587. */
  47588. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  47589. return this._hdrOutputLuminance;
  47590. };
  47591. /**
  47592. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  47593. */
  47594. HDRRenderingPipeline.prototype.dispose = function () {
  47595. for (var i = 0; i < this._scene.cameras.length; i++) {
  47596. var camera = this._scene.cameras[i];
  47597. this._originalPostProcess.dispose(camera);
  47598. this._brightPassPostProcess.dispose(camera);
  47599. this._downSampleX4PostProcess.dispose(camera);
  47600. this._guassianBlurHPostProcess.dispose(camera);
  47601. this._guassianBlurVPostProcess.dispose(camera);
  47602. this._textureAdderPostProcess.dispose(camera);
  47603. for (var j = HDRRenderingPipeline.LUM_STEPS - 1; j >= 0; j--) {
  47604. this._downSamplePostProcesses[j].dispose(camera);
  47605. }
  47606. this._hdrPostProcess.dispose(camera);
  47607. }
  47608. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47609. _super.prototype.dispose.call(this);
  47610. };
  47611. /**
  47612. * Creates the HDR post-process and computes the luminance adaptation
  47613. */
  47614. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  47615. var _this = this;
  47616. var hdrLastLuminance = 0.0;
  47617. this._hdrOutputLuminance = -1.0;
  47618. this._hdrCurrentLuminance = 1.0;
  47619. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  47620. this._hdrPostProcess.onApply = function (effect) {
  47621. if (_this._hdrOutputLuminance < 0.0) {
  47622. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  47623. }
  47624. else {
  47625. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  47626. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  47627. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  47628. }
  47629. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  47630. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  47631. }
  47632. else {
  47633. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  47634. }
  47635. }
  47636. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  47637. hdrLastLuminance += scene.getEngine().getDeltaTime();
  47638. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  47639. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  47640. effect.setFloat("exposure", _this.exposure);
  47641. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  47642. _this._needUpdate = false;
  47643. };
  47644. };
  47645. /**
  47646. * Texture Adder post-process
  47647. */
  47648. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  47649. var _this = this;
  47650. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  47651. this._textureAdderPostProcess.onApply = function (effect) {
  47652. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  47653. };
  47654. };
  47655. /**
  47656. * Down sample X4 post-process
  47657. */
  47658. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  47659. var _this = this;
  47660. var downSampleX4Offsets = new Array(32);
  47661. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  47662. this._downSampleX4PostProcess.onApply = function (effect) {
  47663. if (_this._needUpdate) {
  47664. var id = 0;
  47665. for (var i = -2; i < 2; i++) {
  47666. for (var j = -2; j < 2; j++) {
  47667. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  47668. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  47669. id += 2;
  47670. }
  47671. }
  47672. }
  47673. effect.setArray2("dsOffsets", downSampleX4Offsets);
  47674. };
  47675. };
  47676. /**
  47677. * Bright pass post-process
  47678. */
  47679. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  47680. var _this = this;
  47681. var brightOffsets = new Array(8);
  47682. var brightPassCallback = function (effect) {
  47683. if (_this._needUpdate) {
  47684. var sU = (1.0 / _this._brightPassPostProcess.width);
  47685. var sV = (1.0 / _this._brightPassPostProcess.height);
  47686. brightOffsets[0] = -0.5 * sU;
  47687. brightOffsets[1] = 0.5 * sV;
  47688. brightOffsets[2] = 0.5 * sU;
  47689. brightOffsets[3] = 0.5 * sV;
  47690. brightOffsets[4] = -0.5 * sU;
  47691. brightOffsets[5] = -0.5 * sV;
  47692. brightOffsets[6] = 0.5 * sU;
  47693. brightOffsets[7] = -0.5 * sV;
  47694. }
  47695. effect.setArray2("dsOffsets", brightOffsets);
  47696. effect.setFloat("brightThreshold", _this.brightThreshold);
  47697. };
  47698. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  47699. this._brightPassPostProcess.onApply = brightPassCallback;
  47700. };
  47701. /**
  47702. * Luminance generator. Creates the luminance post-process and down sample post-processes
  47703. */
  47704. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  47705. var _this = this;
  47706. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  47707. var luminanceOffsets = new Array(8);
  47708. var downSampleOffsets = new Array(18);
  47709. var halfDestPixelSize;
  47710. this._downSamplePostProcesses = new Array(lumSteps);
  47711. // Utils for luminance
  47712. var luminanceUpdateSourceOffsets = function (width, height) {
  47713. var sU = (1.0 / width);
  47714. var sV = (1.0 / height);
  47715. luminanceOffsets[0] = -0.5 * sU;
  47716. luminanceOffsets[1] = 0.5 * sV;
  47717. luminanceOffsets[2] = 0.5 * sU;
  47718. luminanceOffsets[3] = 0.5 * sV;
  47719. luminanceOffsets[4] = -0.5 * sU;
  47720. luminanceOffsets[5] = -0.5 * sV;
  47721. luminanceOffsets[6] = 0.5 * sU;
  47722. luminanceOffsets[7] = -0.5 * sV;
  47723. };
  47724. var luminanceUpdateDestOffsets = function (width, height) {
  47725. var id = 0;
  47726. for (var x = -1; x < 2; x++) {
  47727. for (var y = -1; y < 2; y++) {
  47728. downSampleOffsets[id] = (x) / width;
  47729. downSampleOffsets[id + 1] = (y) / height;
  47730. id += 2;
  47731. }
  47732. }
  47733. };
  47734. // Luminance callback
  47735. var luminanceCallback = function (effect) {
  47736. if (_this._needUpdate) {
  47737. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  47738. }
  47739. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  47740. effect.setArray2("lumOffsets", luminanceOffsets);
  47741. };
  47742. // Down sample callbacks
  47743. var downSampleCallback = function (indice) {
  47744. var i = indice;
  47745. return function (effect) {
  47746. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  47747. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  47748. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  47749. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  47750. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  47751. effect.setArray2("dsOffsets", downSampleOffsets);
  47752. };
  47753. };
  47754. var downSampleAfterRenderCallback = function (effect) {
  47755. // Unpack result
  47756. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  47757. 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);
  47758. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  47759. };
  47760. // Create luminance post-process
  47761. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  47762. 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);
  47763. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  47764. // Create down sample post-processes
  47765. for (var i = lumSteps - 2; i >= 0; i--) {
  47766. var length = Math.pow(3, i);
  47767. ratio = { width: length, height: length };
  47768. var defines = "#define DOWN_SAMPLE\n";
  47769. if (i === 0) {
  47770. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  47771. }
  47772. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  47773. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  47774. if (i === 0) {
  47775. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  47776. }
  47777. }
  47778. };
  47779. /**
  47780. * Gaussian blur post-processes. Horizontal and Vertical
  47781. */
  47782. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  47783. var _this = this;
  47784. var blurOffsetsW = new Array(9);
  47785. var blurOffsetsH = new Array(9);
  47786. var blurWeights = new Array(9);
  47787. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  47788. // Utils for gaussian blur
  47789. var calculateBlurOffsets = function (height) {
  47790. var lastOutputDimensions = {
  47791. width: scene.getEngine().getRenderWidth(),
  47792. height: scene.getEngine().getRenderHeight()
  47793. };
  47794. for (var i = 0; i < 9; i++) {
  47795. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  47796. if (height) {
  47797. blurOffsetsH[i] = value;
  47798. }
  47799. else {
  47800. blurOffsetsW[i] = value;
  47801. }
  47802. }
  47803. };
  47804. var calculateWeights = function () {
  47805. var x = 0.0;
  47806. for (var i = 0; i < 9; i++) {
  47807. x = (i - 4.0) / 4.0;
  47808. 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));
  47809. }
  47810. };
  47811. // Callback
  47812. var gaussianBlurCallback = function (height) {
  47813. return function (effect) {
  47814. if (_this._needUpdate) {
  47815. calculateWeights();
  47816. calculateBlurOffsets(height);
  47817. }
  47818. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  47819. effect.setArray("blurWeights", blurWeights);
  47820. effect.setFloat("multiplier", _this.gaussMultiplier);
  47821. };
  47822. };
  47823. // Create horizontal gaussian blur post-processes
  47824. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  47825. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  47826. // Create vertical gaussian blur post-process
  47827. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  47828. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  47829. };
  47830. return HDRRenderingPipeline;
  47831. }(BABYLON.PostProcessRenderPipeline));
  47832. // Luminance generator
  47833. HDRRenderingPipeline.LUM_STEPS = 6;
  47834. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  47835. })(BABYLON || (BABYLON = {}));
  47836. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  47837. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  47838. var BABYLON;
  47839. (function (BABYLON) {
  47840. var StandardRenderingPipeline = (function (_super) {
  47841. __extends(StandardRenderingPipeline, _super);
  47842. /**
  47843. * @constructor
  47844. * @param {string} name - The rendering pipeline name
  47845. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47846. * @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)
  47847. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  47848. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47849. */
  47850. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  47851. if (originalPostProcess === void 0) { originalPostProcess = null; }
  47852. var _this = _super.call(this, scene.getEngine(), name) || this;
  47853. _this.downSampleX4PostProcess = null;
  47854. _this.brightPassPostProcess = null;
  47855. _this.gaussianBlurHPostProcesses = [];
  47856. _this.gaussianBlurVPostProcesses = [];
  47857. _this.textureAdderPostProcess = null;
  47858. _this.luminancePostProcess = null;
  47859. _this.luminanceDownSamplePostProcesses = [];
  47860. _this.hdrPostProcess = null;
  47861. _this.textureAdderFinalPostProcess = null;
  47862. _this.lensFlareFinalPostProcess = null;
  47863. _this.hdrFinalPostProcess = null;
  47864. _this.lensFlarePostProcess = null;
  47865. _this.lensFlareComposePostProcess = null;
  47866. _this.depthOfFieldPostProcess = null;
  47867. // Values
  47868. _this.brightThreshold = 1.0;
  47869. _this.blurWidth = 2.0;
  47870. _this.horizontalBlur = false;
  47871. _this.gaussianCoefficient = 0.25;
  47872. _this.gaussianMean = 1.0;
  47873. _this.gaussianStandardDeviation = 1.0;
  47874. _this.exposure = 1.0;
  47875. _this.lensTexture = null;
  47876. _this.hdrMinimumLuminance = 1.0;
  47877. _this.hdrDecreaseRate = 0.5;
  47878. _this.hdrIncreaseRate = 0.5;
  47879. _this.lensColorTexture = null;
  47880. _this.lensFlareStrength = 20.0;
  47881. _this.lensFlareGhostDispersal = 1.4;
  47882. _this.lensFlareHaloWidth = 0.7;
  47883. _this.lensFlareDistortionStrength = 16.0;
  47884. _this.lensStarTexture = null;
  47885. _this.lensFlareDirtTexture = null;
  47886. _this.depthOfFieldDistance = 10.0;
  47887. _this.depthOfFieldBlurWidth = 2.0;
  47888. // IAnimatable
  47889. _this.animations = [];
  47890. _this._depthRenderer = null;
  47891. _this._currentDepthOfFieldSource = null;
  47892. _this._currentHDRSource = null;
  47893. _this._hdrCurrentLuminance = 1.0;
  47894. // Getters and setters
  47895. _this._depthOfFieldEnabled = true;
  47896. _this._lensFlareEnabled = true;
  47897. _this._hdrEnabled = true;
  47898. _this._cameras = cameras || [];
  47899. // Initialize
  47900. _this._scene = scene;
  47901. // Create pass post-processe
  47902. if (!originalPostProcess) {
  47903. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  47904. }
  47905. else {
  47906. _this.originalPostProcess = originalPostProcess;
  47907. }
  47908. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  47909. // Create down sample X4 post-process
  47910. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  47911. // Create bright pass post-process
  47912. _this._createBrightPassPostProcess(scene, ratio / 2);
  47913. // Create gaussian blur post-processes (down sampling blurs)
  47914. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  47915. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  47916. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  47917. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  47918. // Create texture adder post-process
  47919. _this._createTextureAdderPostProcess(scene, ratio);
  47920. // Create depth-of-field source post-process
  47921. _this.textureAdderFinalPostProcess = new BABYLON.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  47922. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  47923. // Create lens flare post-process
  47924. _this._createLensFlarePostProcess(scene, ratio);
  47925. // Create depth-of-field source post-process post lens-flare and disable it now
  47926. _this.lensFlareFinalPostProcess = new BABYLON.PostProcess("HDRPostLensFlareDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  47927. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  47928. // Create luminance
  47929. _this._createLuminancePostProcesses(scene);
  47930. // Create HDR
  47931. _this._createHdrPostProcess(scene, ratio);
  47932. // Create depth-of-field source post-process post lens-flare and disable it now
  47933. _this.hdrFinalPostProcess = new BABYLON.PostProcess("HDRPostHDReDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  47934. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  47935. // Create gaussian blur used by depth-of-field
  47936. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5, "depthOfFieldBlurWidth");
  47937. // Create depth-of-field post-process
  47938. _this._createDepthOfFieldPostProcess(scene, ratio);
  47939. // Finish
  47940. scene.postProcessRenderPipelineManager.addPipeline(_this);
  47941. if (cameras !== null) {
  47942. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47943. }
  47944. // Deactivate
  47945. _this.LensFlareEnabled = false;
  47946. _this.DepthOfFieldEnabled = false;
  47947. _this.HDREnabled = false;
  47948. return _this;
  47949. }
  47950. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  47951. get: function () {
  47952. return this._depthOfFieldEnabled;
  47953. },
  47954. set: function (enabled) {
  47955. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  47956. if (enabled && !this._depthOfFieldEnabled) {
  47957. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  47958. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  47959. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  47960. this._depthRenderer = this._scene.enableDepthRenderer();
  47961. }
  47962. else if (!enabled && this._depthOfFieldEnabled) {
  47963. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._cameras);
  47964. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._cameras);
  47965. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._cameras);
  47966. }
  47967. this._depthOfFieldEnabled = enabled;
  47968. },
  47969. enumerable: true,
  47970. configurable: true
  47971. });
  47972. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  47973. get: function () {
  47974. return this._lensFlareEnabled;
  47975. },
  47976. set: function (enabled) {
  47977. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  47978. if (enabled && !this._lensFlareEnabled) {
  47979. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  47980. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  47981. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  47982. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  47983. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  47984. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRPostLensFlareDepthOfFieldSource", this._scene.cameras);
  47985. }
  47986. else if (!enabled && this._lensFlareEnabled) {
  47987. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  47988. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  47989. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  47990. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  47991. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  47992. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRPostLensFlareDepthOfFieldSource", this._scene.cameras);
  47993. }
  47994. this._lensFlareEnabled = enabled;
  47995. },
  47996. enumerable: true,
  47997. configurable: true
  47998. });
  47999. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  48000. get: function () {
  48001. return this._hdrEnabled;
  48002. },
  48003. set: function (enabled) {
  48004. if (enabled && !this._hdrEnabled) {
  48005. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLuminance", this._scene.cameras);
  48006. for (var i = 0; i < this.luminanceDownSamplePostProcesses.length; i++) {
  48007. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLuminanceDownSample" + i, this._scene.cameras);
  48008. }
  48009. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDR", this._scene.cameras);
  48010. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRPostHDReDepthOfFieldSource", this._scene.cameras);
  48011. }
  48012. else if (!enabled && this._hdrEnabled) {
  48013. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLuminance", this._scene.cameras);
  48014. for (var i = 0; i < this.luminanceDownSamplePostProcesses.length; i++) {
  48015. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLuminanceDownSample" + i, this._scene.cameras);
  48016. }
  48017. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDR", this._scene.cameras);
  48018. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRPostHDReDepthOfFieldSource", this._scene.cameras);
  48019. }
  48020. this._hdrEnabled = enabled;
  48021. },
  48022. enumerable: true,
  48023. configurable: true
  48024. });
  48025. // Down Sample X4 Post-Processs
  48026. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  48027. var _this = this;
  48028. var downSampleX4Offsets = new Array(32);
  48029. this.downSampleX4PostProcess = new BABYLON.PostProcess("HDRDownSampleX4", "standard", ["dsOffsets"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  48030. this.downSampleX4PostProcess.onApply = function (effect) {
  48031. var id = 0;
  48032. for (var i = -2; i < 2; i++) {
  48033. for (var j = -2; j < 2; j++) {
  48034. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  48035. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  48036. id += 2;
  48037. }
  48038. }
  48039. effect.setArray2("dsOffsets", downSampleX4Offsets);
  48040. };
  48041. // Add to pipeline
  48042. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  48043. };
  48044. // Brightpass Post-Process
  48045. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  48046. var _this = this;
  48047. var brightOffsets = new Array(8);
  48048. this.brightPassPostProcess = new BABYLON.PostProcess("HDRBrightPass", "standard", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  48049. this.brightPassPostProcess.onApply = function (effect) {
  48050. var sU = (1.0 / _this.brightPassPostProcess.width);
  48051. var sV = (1.0 / _this.brightPassPostProcess.height);
  48052. brightOffsets[0] = -0.5 * sU;
  48053. brightOffsets[1] = 0.5 * sV;
  48054. brightOffsets[2] = 0.5 * sU;
  48055. brightOffsets[3] = 0.5 * sV;
  48056. brightOffsets[4] = -0.5 * sU;
  48057. brightOffsets[5] = -0.5 * sV;
  48058. brightOffsets[6] = 0.5 * sU;
  48059. brightOffsets[7] = -0.5 * sV;
  48060. effect.setArray2("dsOffsets", brightOffsets);
  48061. effect.setFloat("brightThreshold", _this.brightThreshold);
  48062. };
  48063. // Add to pipeline
  48064. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  48065. };
  48066. // Create gaussian blur H&V post-processes
  48067. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  48068. var _this = this;
  48069. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  48070. var blurOffsets = new Array(9);
  48071. var blurWeights = new Array(9);
  48072. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  48073. var callback = function (height) {
  48074. return function (effect) {
  48075. // Weights
  48076. var x = 0.0;
  48077. for (var i = 0; i < 9; i++) {
  48078. x = (i - 4.0) / 4.0;
  48079. blurWeights[i] =
  48080. _this.gaussianCoefficient
  48081. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  48082. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  48083. }
  48084. var lastOutputDimensions = {
  48085. width: scene.getEngine().getRenderWidth(),
  48086. height: scene.getEngine().getRenderHeight()
  48087. };
  48088. for (var i = 0; i < 9; i++) {
  48089. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  48090. blurOffsets[i] = value;
  48091. }
  48092. effect.setArray("blurOffsets", blurOffsets);
  48093. effect.setArray("blurWeights", blurWeights);
  48094. if (height) {
  48095. effect.setFloat("blurWidth", _this.horizontalBlur ? 1.0 : _this[blurWidthKey]);
  48096. }
  48097. else {
  48098. effect.setFloat("blurWidth", _this[blurWidthKey]);
  48099. }
  48100. };
  48101. };
  48102. // Create horizontal gaussian blur post-processes
  48103. var gaussianBlurHPostProcess = new BABYLON.PostProcess("HDRGaussianBlurH_" + ratio + "_" + indice, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  48104. gaussianBlurHPostProcess.onApply = callback(false);
  48105. // Create vertical gaussian blur post-process
  48106. var gaussianBlurVPostProcess = new BABYLON.PostProcess("HDRGaussianBlurV_" + ratio + "_" + indice, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  48107. gaussianBlurVPostProcess.onApply = callback(true);
  48108. // Add to pipeline
  48109. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  48110. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  48111. // Finish
  48112. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  48113. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  48114. };
  48115. // Create texture adder post-process
  48116. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  48117. var _this = this;
  48118. this.textureAdderPostProcess = new BABYLON.PostProcess("HDRTextureAdder", "standard", ["exposure"], ["otherSampler", "lensSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  48119. this.textureAdderPostProcess.onApply = function (effect) {
  48120. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  48121. effect.setTexture("lensSampler", _this.lensTexture);
  48122. effect.setFloat("exposure", _this.exposure);
  48123. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  48124. _this._currentHDRSource = _this.textureAdderFinalPostProcess;
  48125. };
  48126. // Add to pipeline
  48127. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  48128. };
  48129. // Create luminance
  48130. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene) {
  48131. var _this = this;
  48132. // Create luminance
  48133. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  48134. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", BABYLON.Engine.TEXTURETYPE_FLOAT);
  48135. var offsets = [];
  48136. this.luminancePostProcess.onApply = function (effect) {
  48137. var sU = (1.0 / _this.luminancePostProcess.width);
  48138. var sV = (1.0 / _this.luminancePostProcess.height);
  48139. offsets[0] = -0.5 * sU;
  48140. offsets[1] = 0.5 * sV;
  48141. offsets[2] = 0.5 * sU;
  48142. offsets[3] = 0.5 * sV;
  48143. offsets[4] = -0.5 * sU;
  48144. offsets[5] = -0.5 * sV;
  48145. offsets[6] = 0.5 * sU;
  48146. offsets[7] = -0.5 * sV;
  48147. effect.setArray2("lumOffsets", offsets);
  48148. };
  48149. // Add to pipeline
  48150. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  48151. // Create down sample luminance
  48152. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  48153. var size = Math.pow(3, i);
  48154. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  48155. if (i === 0) {
  48156. defines += "#define FINAL_DOWN_SAMPLER";
  48157. }
  48158. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  48159. this.luminanceDownSamplePostProcesses.push(postProcess);
  48160. }
  48161. // Create callbacks and add effects
  48162. var lastLuminance = this.luminancePostProcess;
  48163. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  48164. var downSampleOffsets = new Array(18);
  48165. pp.onApply = function (effect) {
  48166. var id = 0;
  48167. for (var x = -1; x < 2; x++) {
  48168. for (var y = -1; y < 2; y++) {
  48169. downSampleOffsets[id] = x / lastLuminance.width;
  48170. downSampleOffsets[id + 1] = y / lastLuminance.height;
  48171. id += 2;
  48172. }
  48173. }
  48174. effect.setArray2("dsOffsets", downSampleOffsets);
  48175. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  48176. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  48177. lastLuminance = _this.luminancePostProcess;
  48178. }
  48179. else {
  48180. lastLuminance = pp;
  48181. }
  48182. };
  48183. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  48184. pp.onAfterRender = function (effect) {
  48185. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  48186. 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);
  48187. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  48188. };
  48189. }
  48190. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  48191. });
  48192. };
  48193. // Create HDR post-process
  48194. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  48195. var _this = this;
  48196. this.hdrPostProcess = new BABYLON.PostProcess("HDR", "standard", ["averageLuminance"], ["textureAdderSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  48197. var outputLiminance = 1;
  48198. var time = 0;
  48199. var lastTime = 0;
  48200. this.hdrPostProcess.onApply = function (effect) {
  48201. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentHDRSource);
  48202. time += scene.getEngine().getDeltaTime();
  48203. if (outputLiminance < 0) {
  48204. outputLiminance = _this._hdrCurrentLuminance;
  48205. }
  48206. else {
  48207. var dt = (lastTime - time) / 1000.0;
  48208. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  48209. outputLiminance += _this.hdrDecreaseRate * dt;
  48210. }
  48211. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  48212. outputLiminance -= _this.hdrIncreaseRate * dt;
  48213. }
  48214. else {
  48215. outputLiminance = _this._hdrCurrentLuminance;
  48216. }
  48217. }
  48218. outputLiminance = BABYLON.MathTools.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  48219. effect.setFloat("averageLuminance", outputLiminance);
  48220. lastTime = time;
  48221. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  48222. };
  48223. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  48224. };
  48225. // Create lens flare post-process
  48226. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  48227. var _this = this;
  48228. this.lensFlarePostProcess = new BABYLON.PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  48229. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  48230. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  48231. this.lensFlareComposePostProcess = new BABYLON.PostProcess("HDRLensFlareCompose", "standard", ["lensStarMatrix"], ["otherSampler", "lensDirtSampler", "lensStarSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE_COMPOSE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  48232. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  48233. var resolution = new BABYLON.Vector2(0, 0);
  48234. // Lens flare
  48235. this.lensFlarePostProcess.onApply = function (effect) {
  48236. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  48237. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  48238. effect.setFloat("strength", _this.lensFlareStrength);
  48239. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  48240. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  48241. // Shift
  48242. resolution.x = _this.lensFlarePostProcess.width;
  48243. resolution.y = _this.lensFlarePostProcess.height;
  48244. effect.setVector2("resolution", resolution);
  48245. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  48246. };
  48247. // Compose
  48248. var scaleBias1 = BABYLON.Matrix.FromValues(2.0, 0.0, -1.0, 0.0, 0.0, 2.0, -1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  48249. var scaleBias2 = BABYLON.Matrix.FromValues(0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  48250. this.lensFlareComposePostProcess.onApply = function (effect) {
  48251. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  48252. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  48253. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  48254. // Lens start rotation matrix
  48255. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  48256. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  48257. var camRot = BABYLON.Vector3.Dot(camerax.toVector3(), new BABYLON.Vector3(1.0, 0.0, 0.0)) + BABYLON.Vector3.Dot(cameraz.toVector3(), new BABYLON.Vector3(0.0, 0.0, 1.0));
  48258. camRot *= 4.0;
  48259. var starRotation = BABYLON.Matrix.FromValues(Math.cos(camRot) * 0.5, -Math.sin(camRot), 0.0, 0.0, Math.sin(camRot), Math.cos(camRot) * 0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  48260. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  48261. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  48262. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  48263. _this._currentHDRSource = _this.lensFlareFinalPostProcess;
  48264. };
  48265. };
  48266. // Create depth-of-field post-process
  48267. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  48268. var _this = this;
  48269. this.depthOfFieldPostProcess = new BABYLON.PostProcess("HDRDepthOfField", "standard", ["distance"], ["otherSampler", "depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DEPTH_OF_FIELD", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  48270. this.depthOfFieldPostProcess.onApply = function (effect) {
  48271. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  48272. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  48273. effect.setFloat("distance", _this.depthOfFieldDistance);
  48274. };
  48275. // Add to pipeline
  48276. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  48277. };
  48278. // Dispose
  48279. StandardRenderingPipeline.prototype.dispose = function () {
  48280. for (var i = 0; i < this._cameras.length; i++) {
  48281. var camera = this._cameras[i];
  48282. this.originalPostProcess.dispose(camera);
  48283. this.downSampleX4PostProcess.dispose(camera);
  48284. this.brightPassPostProcess.dispose(camera);
  48285. this.textureAdderPostProcess.dispose(camera);
  48286. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  48287. this.gaussianBlurHPostProcesses[j].dispose(camera);
  48288. }
  48289. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  48290. this.gaussianBlurVPostProcesses[j].dispose(camera);
  48291. }
  48292. this.textureAdderFinalPostProcess.dispose(camera);
  48293. this.lensFlarePostProcess.dispose(camera);
  48294. this.lensFlareComposePostProcess.dispose(camera);
  48295. this.depthOfFieldPostProcess.dispose(camera);
  48296. }
  48297. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  48298. _super.prototype.dispose.call(this);
  48299. };
  48300. // Serialize rendering pipeline
  48301. StandardRenderingPipeline.prototype.serialize = function () {
  48302. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48303. serializationObject.customType = "StandardRenderingPipeline";
  48304. return serializationObject;
  48305. };
  48306. // Parse serialized pipeline
  48307. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  48308. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  48309. };
  48310. return StandardRenderingPipeline;
  48311. }(BABYLON.PostProcessRenderPipeline));
  48312. // Luminance steps
  48313. StandardRenderingPipeline.LuminanceSteps = 6;
  48314. __decorate([
  48315. BABYLON.serialize()
  48316. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  48317. __decorate([
  48318. BABYLON.serialize()
  48319. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  48320. __decorate([
  48321. BABYLON.serialize()
  48322. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  48323. __decorate([
  48324. BABYLON.serialize()
  48325. ], StandardRenderingPipeline.prototype, "gaussianCoefficient", void 0);
  48326. __decorate([
  48327. BABYLON.serialize()
  48328. ], StandardRenderingPipeline.prototype, "gaussianMean", void 0);
  48329. __decorate([
  48330. BABYLON.serialize()
  48331. ], StandardRenderingPipeline.prototype, "gaussianStandardDeviation", void 0);
  48332. __decorate([
  48333. BABYLON.serialize()
  48334. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  48335. __decorate([
  48336. BABYLON.serializeAsTexture("lensTexture")
  48337. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  48338. __decorate([
  48339. BABYLON.serialize()
  48340. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  48341. __decorate([
  48342. BABYLON.serialize()
  48343. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  48344. __decorate([
  48345. BABYLON.serialize()
  48346. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  48347. __decorate([
  48348. BABYLON.serializeAsTexture("lensColorTexture")
  48349. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  48350. __decorate([
  48351. BABYLON.serialize()
  48352. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  48353. __decorate([
  48354. BABYLON.serialize()
  48355. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  48356. __decorate([
  48357. BABYLON.serialize()
  48358. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  48359. __decorate([
  48360. BABYLON.serialize()
  48361. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  48362. __decorate([
  48363. BABYLON.serializeAsTexture("lensStarTexture")
  48364. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  48365. __decorate([
  48366. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  48367. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  48368. __decorate([
  48369. BABYLON.serialize()
  48370. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  48371. __decorate([
  48372. BABYLON.serialize()
  48373. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  48374. __decorate([
  48375. BABYLON.serialize()
  48376. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  48377. __decorate([
  48378. BABYLON.serialize()
  48379. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  48380. __decorate([
  48381. BABYLON.serialize()
  48382. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  48383. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  48384. })(BABYLON || (BABYLON = {}));
  48385. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  48386. var BABYLON;
  48387. (function (BABYLON) {
  48388. var BlurPostProcess = (function (_super) {
  48389. __extends(BlurPostProcess, _super);
  48390. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  48391. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48392. var _this = _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  48393. _this.direction = direction;
  48394. _this.blurWidth = blurWidth;
  48395. _this.onApplyObservable.add(function (effect) {
  48396. effect.setFloat2("screenSize", _this.width, _this.height);
  48397. effect.setVector2("direction", _this.direction);
  48398. effect.setFloat("blurWidth", _this.blurWidth);
  48399. });
  48400. return _this;
  48401. }
  48402. return BlurPostProcess;
  48403. }(BABYLON.PostProcess));
  48404. BABYLON.BlurPostProcess = BlurPostProcess;
  48405. })(BABYLON || (BABYLON = {}));
  48406. //# sourceMappingURL=babylon.blurPostProcess.js.map
  48407. var BABYLON;
  48408. (function (BABYLON) {
  48409. var RefractionPostProcess = (function (_super) {
  48410. __extends(RefractionPostProcess, _super);
  48411. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  48412. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  48413. _this.color = color;
  48414. _this.depth = depth;
  48415. _this.colorLevel = colorLevel;
  48416. _this.onActivateObservable.add(function (cam) {
  48417. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  48418. });
  48419. _this.onApplyObservable.add(function (effect) {
  48420. effect.setColor3("baseColor", _this.color);
  48421. effect.setFloat("depth", _this.depth);
  48422. effect.setFloat("colorLevel", _this.colorLevel);
  48423. effect.setTexture("refractionSampler", _this._refRexture);
  48424. });
  48425. return _this;
  48426. }
  48427. // Methods
  48428. RefractionPostProcess.prototype.dispose = function (camera) {
  48429. if (this._refRexture) {
  48430. this._refRexture.dispose();
  48431. }
  48432. _super.prototype.dispose.call(this, camera);
  48433. };
  48434. return RefractionPostProcess;
  48435. }(BABYLON.PostProcess));
  48436. BABYLON.RefractionPostProcess = RefractionPostProcess;
  48437. })(BABYLON || (BABYLON = {}));
  48438. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  48439. var BABYLON;
  48440. (function (BABYLON) {
  48441. var BlackAndWhitePostProcess = (function (_super) {
  48442. __extends(BlackAndWhitePostProcess, _super);
  48443. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  48444. return _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable) || this;
  48445. }
  48446. return BlackAndWhitePostProcess;
  48447. }(BABYLON.PostProcess));
  48448. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  48449. })(BABYLON || (BABYLON = {}));
  48450. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  48451. var BABYLON;
  48452. (function (BABYLON) {
  48453. var ConvolutionPostProcess = (function (_super) {
  48454. __extends(ConvolutionPostProcess, _super);
  48455. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  48456. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  48457. _this.kernel = kernel;
  48458. _this.onApply = function (effect) {
  48459. effect.setFloat2("screenSize", _this.width, _this.height);
  48460. effect.setArray("kernel", _this.kernel);
  48461. };
  48462. return _this;
  48463. }
  48464. return ConvolutionPostProcess;
  48465. }(BABYLON.PostProcess));
  48466. // Statics
  48467. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  48468. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  48469. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  48470. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  48471. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  48472. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  48473. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  48474. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  48475. })(BABYLON || (BABYLON = {}));
  48476. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  48477. var BABYLON;
  48478. (function (BABYLON) {
  48479. var FilterPostProcess = (function (_super) {
  48480. __extends(FilterPostProcess, _super);
  48481. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  48482. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  48483. _this.kernelMatrix = kernelMatrix;
  48484. _this.onApply = function (effect) {
  48485. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  48486. };
  48487. return _this;
  48488. }
  48489. return FilterPostProcess;
  48490. }(BABYLON.PostProcess));
  48491. BABYLON.FilterPostProcess = FilterPostProcess;
  48492. })(BABYLON || (BABYLON = {}));
  48493. //# sourceMappingURL=babylon.filterPostProcess.js.map
  48494. var BABYLON;
  48495. (function (BABYLON) {
  48496. var FxaaPostProcess = (function (_super) {
  48497. __extends(FxaaPostProcess, _super);
  48498. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  48499. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable) || this;
  48500. _this.onSizeChangedObservable.add(function () {
  48501. _this.texelWidth = 1.0 / _this.width;
  48502. _this.texelHeight = 1.0 / _this.height;
  48503. });
  48504. _this.onApplyObservable.add(function (effect) {
  48505. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  48506. });
  48507. return _this;
  48508. }
  48509. return FxaaPostProcess;
  48510. }(BABYLON.PostProcess));
  48511. BABYLON.FxaaPostProcess = FxaaPostProcess;
  48512. })(BABYLON || (BABYLON = {}));
  48513. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  48514. var BABYLON;
  48515. (function (BABYLON) {
  48516. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  48517. var VolumetricLightScatteringPostProcess = (function (_super) {
  48518. __extends(VolumetricLightScatteringPostProcess, _super);
  48519. /**
  48520. * @constructor
  48521. * @param {string} name - The post-process name
  48522. * @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)
  48523. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  48524. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  48525. * @param {number} samples - The post-process quality, default 100
  48526. * @param {number} samplingMode - The post-process filtering mode
  48527. * @param {BABYLON.Engine} engine - The babylon engine
  48528. * @param {boolean} reusable - If the post-process is reusable
  48529. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  48530. */
  48531. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  48532. if (samples === void 0) { samples = 100; }
  48533. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48534. var _this = _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples) || this;
  48535. _this._screenCoordinates = BABYLON.Vector2.Zero();
  48536. /**
  48537. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  48538. * @type {Vector3}
  48539. */
  48540. _this.customMeshPosition = BABYLON.Vector3.Zero();
  48541. /**
  48542. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  48543. * @type {boolean}
  48544. */
  48545. _this.useCustomMeshPosition = false;
  48546. /**
  48547. * If the post-process should inverse the light scattering direction
  48548. * @type {boolean}
  48549. */
  48550. _this.invert = true;
  48551. /**
  48552. * Array containing the excluded meshes not rendered in the internal pass
  48553. */
  48554. _this.excludedMeshes = new Array();
  48555. /**
  48556. * Controls the overall intensity of the post-process
  48557. * @type {number}
  48558. */
  48559. _this.exposure = 0.3;
  48560. /**
  48561. * Dissipates each sample's contribution in range [0, 1]
  48562. * @type {number}
  48563. */
  48564. _this.decay = 0.96815;
  48565. /**
  48566. * Controls the overall intensity of each sample
  48567. * @type {number}
  48568. */
  48569. _this.weight = 0.58767;
  48570. /**
  48571. * Controls the density of each sample
  48572. * @type {number}
  48573. */
  48574. _this.density = 0.926;
  48575. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  48576. var engine = scene.getEngine();
  48577. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  48578. // Configure mesh
  48579. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  48580. // Configure
  48581. _this._createPass(scene, ratio.passRatio || ratio);
  48582. _this.onActivate = function (camera) {
  48583. if (!_this.isSupported) {
  48584. _this.dispose(camera);
  48585. }
  48586. _this.onActivate = null;
  48587. };
  48588. _this.onApplyObservable.add(function (effect) {
  48589. _this._updateMeshScreenCoordinates(scene);
  48590. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  48591. effect.setFloat("exposure", _this.exposure);
  48592. effect.setFloat("decay", _this.decay);
  48593. effect.setFloat("weight", _this.weight);
  48594. effect.setFloat("density", _this.density);
  48595. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  48596. });
  48597. return _this;
  48598. }
  48599. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  48600. get: function () {
  48601. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  48602. return false;
  48603. },
  48604. set: function (useDiffuseColor) {
  48605. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  48606. },
  48607. enumerable: true,
  48608. configurable: true
  48609. });
  48610. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  48611. var mesh = subMesh.getMesh();
  48612. // Render this.mesh as default
  48613. if (mesh === this.mesh) {
  48614. return mesh.material.isReady(mesh);
  48615. }
  48616. var defines = [];
  48617. var attribs = [BABYLON.VertexBuffer.PositionKind];
  48618. var material = subMesh.getMaterial();
  48619. var needUV = false;
  48620. // Alpha test
  48621. if (material) {
  48622. if (material.needAlphaTesting()) {
  48623. defines.push("#define ALPHATEST");
  48624. }
  48625. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48626. attribs.push(BABYLON.VertexBuffer.UVKind);
  48627. defines.push("#define UV1");
  48628. }
  48629. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  48630. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  48631. defines.push("#define UV2");
  48632. }
  48633. }
  48634. // Bones
  48635. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48636. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48637. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48638. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48639. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48640. }
  48641. else {
  48642. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48643. }
  48644. // Instances
  48645. if (useInstances) {
  48646. defines.push("#define INSTANCES");
  48647. attribs.push("world0");
  48648. attribs.push("world1");
  48649. attribs.push("world2");
  48650. attribs.push("world3");
  48651. }
  48652. // Get correct effect
  48653. var join = defines.join("\n");
  48654. if (this._cachedDefines !== join) {
  48655. this._cachedDefines = join;
  48656. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  48657. }
  48658. return this._volumetricLightScatteringPass.isReady();
  48659. };
  48660. /**
  48661. * Sets the new light position for light scattering effect
  48662. * @param {BABYLON.Vector3} The new custom light position
  48663. */
  48664. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  48665. this.customMeshPosition = position;
  48666. };
  48667. /**
  48668. * Returns the light position for light scattering effect
  48669. * @return {BABYLON.Vector3} The custom light position
  48670. */
  48671. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  48672. return this.customMeshPosition;
  48673. };
  48674. /**
  48675. * Disposes the internal assets and detaches the post-process from the camera
  48676. */
  48677. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  48678. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  48679. if (rttIndex !== -1) {
  48680. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  48681. }
  48682. this._volumetricLightScatteringRTT.dispose();
  48683. _super.prototype.dispose.call(this, camera);
  48684. };
  48685. /**
  48686. * Returns the render target texture used by the post-process
  48687. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  48688. */
  48689. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  48690. return this._volumetricLightScatteringRTT;
  48691. };
  48692. // Private methods
  48693. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  48694. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  48695. return true;
  48696. }
  48697. return false;
  48698. };
  48699. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  48700. var _this = this;
  48701. var engine = scene.getEngine();
  48702. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  48703. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48704. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48705. this._volumetricLightScatteringRTT.renderList = null;
  48706. this._volumetricLightScatteringRTT.renderParticles = false;
  48707. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  48708. // Custom render function for submeshes
  48709. var renderSubMesh = function (subMesh) {
  48710. var mesh = subMesh.getRenderingMesh();
  48711. if (_this._meshExcluded(mesh)) {
  48712. return;
  48713. }
  48714. var scene = mesh.getScene();
  48715. var engine = scene.getEngine();
  48716. // Culling
  48717. engine.setState(subMesh.getMaterial().backFaceCulling);
  48718. // Managing instances
  48719. var batch = mesh._getInstancesRenderList(subMesh._id);
  48720. if (batch.mustReturn) {
  48721. return;
  48722. }
  48723. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  48724. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  48725. var effect = _this._volumetricLightScatteringPass;
  48726. if (mesh === _this.mesh) {
  48727. if (subMesh.effect) {
  48728. effect = subMesh.effect;
  48729. }
  48730. else {
  48731. effect = subMesh.getMaterial().getEffect();
  48732. }
  48733. }
  48734. engine.enableEffect(effect);
  48735. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  48736. if (mesh === _this.mesh) {
  48737. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  48738. }
  48739. else {
  48740. var material = subMesh.getMaterial();
  48741. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  48742. // Alpha test
  48743. if (material && material.needAlphaTesting()) {
  48744. var alphaTexture = material.getAlphaTestTexture();
  48745. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  48746. if (alphaTexture) {
  48747. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  48748. }
  48749. }
  48750. // Bones
  48751. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48752. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  48753. }
  48754. }
  48755. // Draw
  48756. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  48757. }
  48758. };
  48759. // Render target texture callbacks
  48760. var savedSceneClearColor;
  48761. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  48762. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  48763. savedSceneClearColor = scene.clearColor;
  48764. scene.clearColor = sceneClearColor;
  48765. });
  48766. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  48767. scene.clearColor = savedSceneClearColor;
  48768. });
  48769. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  48770. var engine = scene.getEngine();
  48771. var index;
  48772. for (index = 0; index < opaqueSubMeshes.length; index++) {
  48773. renderSubMesh(opaqueSubMeshes.data[index]);
  48774. }
  48775. engine.setAlphaTesting(true);
  48776. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  48777. renderSubMesh(alphaTestSubMeshes.data[index]);
  48778. }
  48779. engine.setAlphaTesting(false);
  48780. if (transparentSubMeshes.length) {
  48781. // Sort sub meshes
  48782. for (index = 0; index < transparentSubMeshes.length; index++) {
  48783. var submesh = transparentSubMeshes.data[index];
  48784. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  48785. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  48786. }
  48787. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  48788. sortedArray.sort(function (a, b) {
  48789. // Alpha index first
  48790. if (a._alphaIndex > b._alphaIndex) {
  48791. return 1;
  48792. }
  48793. if (a._alphaIndex < b._alphaIndex) {
  48794. return -1;
  48795. }
  48796. // Then distance to camera
  48797. if (a._distanceToCamera < b._distanceToCamera) {
  48798. return 1;
  48799. }
  48800. if (a._distanceToCamera > b._distanceToCamera) {
  48801. return -1;
  48802. }
  48803. return 0;
  48804. });
  48805. // Render sub meshes
  48806. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48807. for (index = 0; index < sortedArray.length; index++) {
  48808. renderSubMesh(sortedArray[index]);
  48809. }
  48810. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48811. }
  48812. };
  48813. };
  48814. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  48815. var transform = scene.getTransformMatrix();
  48816. var meshPosition;
  48817. if (this.useCustomMeshPosition) {
  48818. meshPosition = this.customMeshPosition;
  48819. }
  48820. else if (this.attachedNode) {
  48821. meshPosition = this.attachedNode.position;
  48822. }
  48823. else {
  48824. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  48825. }
  48826. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  48827. this._screenCoordinates.x = pos.x / this._viewPort.width;
  48828. this._screenCoordinates.y = pos.y / this._viewPort.height;
  48829. if (this.invert)
  48830. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  48831. };
  48832. // Static methods
  48833. /**
  48834. * Creates a default mesh for the Volumeric Light Scattering post-process
  48835. * @param {string} The mesh name
  48836. * @param {BABYLON.Scene} The scene where to create the mesh
  48837. * @return {BABYLON.Mesh} the default mesh
  48838. */
  48839. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  48840. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  48841. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  48842. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  48843. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  48844. mesh.material = material;
  48845. return mesh;
  48846. };
  48847. return VolumetricLightScatteringPostProcess;
  48848. }(BABYLON.PostProcess));
  48849. __decorate([
  48850. BABYLON.serializeAsVector3()
  48851. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  48852. __decorate([
  48853. BABYLON.serialize()
  48854. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  48855. __decorate([
  48856. BABYLON.serialize()
  48857. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  48858. __decorate([
  48859. BABYLON.serializeAsMeshReference()
  48860. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  48861. __decorate([
  48862. BABYLON.serialize()
  48863. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  48864. __decorate([
  48865. BABYLON.serialize()
  48866. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  48867. __decorate([
  48868. BABYLON.serialize()
  48869. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  48870. __decorate([
  48871. BABYLON.serialize()
  48872. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  48873. __decorate([
  48874. BABYLON.serialize()
  48875. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  48876. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  48877. })(BABYLON || (BABYLON = {}));
  48878. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  48879. //
  48880. // This post-process allows the modification of rendered colors by using
  48881. // a 'look-up table' (LUT). This effect is also called Color Grading.
  48882. //
  48883. // The object needs to be provided an url to a texture containing the color
  48884. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  48885. // Use an image editing software to tweak the LUT to match your needs.
  48886. //
  48887. // For an example of a color LUT, see here:
  48888. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  48889. // For explanations on color grading, see here:
  48890. // http://udn.epicgames.com/Three/ColorGrading.html
  48891. //
  48892. var BABYLON;
  48893. (function (BABYLON) {
  48894. var ColorCorrectionPostProcess = (function (_super) {
  48895. __extends(ColorCorrectionPostProcess, _super);
  48896. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  48897. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  48898. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  48899. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  48900. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48901. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48902. _this.onApply = function (effect) {
  48903. effect.setTexture("colorTable", _this._colorTableTexture);
  48904. };
  48905. return _this;
  48906. }
  48907. return ColorCorrectionPostProcess;
  48908. }(BABYLON.PostProcess));
  48909. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  48910. })(BABYLON || (BABYLON = {}));
  48911. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  48912. var BABYLON;
  48913. (function (BABYLON) {
  48914. var TonemappingOperator;
  48915. (function (TonemappingOperator) {
  48916. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  48917. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  48918. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  48919. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  48920. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  48921. ;
  48922. var TonemapPostProcess = (function (_super) {
  48923. __extends(TonemapPostProcess, _super);
  48924. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  48925. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48926. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  48927. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  48928. _this._operator = _operator;
  48929. _this.exposureAdjustment = exposureAdjustment;
  48930. var defines = "#define ";
  48931. if (_this._operator === TonemappingOperator.Hable)
  48932. defines += "HABLE_TONEMAPPING";
  48933. else if (_this._operator === TonemappingOperator.Reinhard)
  48934. defines += "REINHARD_TONEMAPPING";
  48935. else if (_this._operator === TonemappingOperator.HejiDawson)
  48936. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  48937. else if (_this._operator === TonemappingOperator.Photographic)
  48938. defines += "PHOTOGRAPHIC_TONEMAPPING";
  48939. //sadly a second call to create the effect.
  48940. _this.updateEffect(defines);
  48941. _this.onApply = function (effect) {
  48942. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  48943. };
  48944. return _this;
  48945. }
  48946. return TonemapPostProcess;
  48947. }(BABYLON.PostProcess));
  48948. BABYLON.TonemapPostProcess = TonemapPostProcess;
  48949. })(BABYLON || (BABYLON = {}));
  48950. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  48951. var BABYLON;
  48952. (function (BABYLON) {
  48953. var DisplayPassPostProcess = (function (_super) {
  48954. __extends(DisplayPassPostProcess, _super);
  48955. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  48956. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  48957. }
  48958. return DisplayPassPostProcess;
  48959. }(BABYLON.PostProcess));
  48960. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  48961. })(BABYLON || (BABYLON = {}));
  48962. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  48963. /// <reference path="..\babylon.node.ts" />
  48964. var BABYLON;
  48965. (function (BABYLON) {
  48966. var Bone = (function (_super) {
  48967. __extends(Bone, _super);
  48968. function Bone(name, skeleton, parentBone, matrix, restPose) {
  48969. var _this = _super.call(this, name, skeleton.getScene()) || this;
  48970. _this.name = name;
  48971. _this.children = new Array();
  48972. _this.animations = new Array();
  48973. _this._worldTransform = new BABYLON.Matrix();
  48974. _this._absoluteTransform = new BABYLON.Matrix();
  48975. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  48976. _this._scaleMatrix = BABYLON.Matrix.Identity();
  48977. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  48978. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  48979. _this._scalingDeterminant = 1;
  48980. _this._skeleton = skeleton;
  48981. _this._localMatrix = matrix;
  48982. _this._baseMatrix = matrix.clone();
  48983. _this._restPose = restPose ? restPose : matrix.clone();
  48984. skeleton.bones.push(_this);
  48985. if (parentBone) {
  48986. _this._parent = parentBone;
  48987. parentBone.children.push(_this);
  48988. }
  48989. else {
  48990. _this._parent = null;
  48991. }
  48992. _this._updateDifferenceMatrix();
  48993. if (_this.getAbsoluteTransform().determinant() < 0) {
  48994. _this._scalingDeterminant *= -1;
  48995. }
  48996. return _this;
  48997. }
  48998. Object.defineProperty(Bone.prototype, "_matrix", {
  48999. get: function () {
  49000. return this._localMatrix;
  49001. },
  49002. set: function (val) {
  49003. if (this._localMatrix) {
  49004. this._localMatrix.copyFrom(val);
  49005. }
  49006. else {
  49007. this._localMatrix = val;
  49008. }
  49009. },
  49010. enumerable: true,
  49011. configurable: true
  49012. });
  49013. // Members
  49014. Bone.prototype.getParent = function () {
  49015. return this._parent;
  49016. };
  49017. Bone.prototype.getLocalMatrix = function () {
  49018. return this._localMatrix;
  49019. };
  49020. Bone.prototype.getBaseMatrix = function () {
  49021. return this._baseMatrix;
  49022. };
  49023. Bone.prototype.getRestPose = function () {
  49024. return this._restPose;
  49025. };
  49026. Bone.prototype.returnToRest = function () {
  49027. this.updateMatrix(this._restPose.clone());
  49028. };
  49029. Bone.prototype.getWorldMatrix = function () {
  49030. return this._worldTransform;
  49031. };
  49032. Bone.prototype.getInvertedAbsoluteTransform = function () {
  49033. return this._invertedAbsoluteTransform;
  49034. };
  49035. Bone.prototype.getAbsoluteTransform = function () {
  49036. return this._absoluteTransform;
  49037. };
  49038. Object.defineProperty(Bone.prototype, "position", {
  49039. // Properties (matches AbstractMesh properties)
  49040. get: function () {
  49041. return this.getPosition();
  49042. },
  49043. set: function (newPosition) {
  49044. this.setPosition(newPosition);
  49045. },
  49046. enumerable: true,
  49047. configurable: true
  49048. });
  49049. Object.defineProperty(Bone.prototype, "rotation", {
  49050. get: function () {
  49051. return this.getRotation();
  49052. },
  49053. set: function (newRotation) {
  49054. this.setRotation(newRotation);
  49055. },
  49056. enumerable: true,
  49057. configurable: true
  49058. });
  49059. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  49060. get: function () {
  49061. return this.getRotationQuaternion();
  49062. },
  49063. set: function (newRotation) {
  49064. this.setRotationQuaternion(newRotation);
  49065. },
  49066. enumerable: true,
  49067. configurable: true
  49068. });
  49069. Object.defineProperty(Bone.prototype, "scaling", {
  49070. get: function () {
  49071. return this.getScale();
  49072. },
  49073. set: function (newScaling) {
  49074. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  49075. },
  49076. enumerable: true,
  49077. configurable: true
  49078. });
  49079. // Methods
  49080. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  49081. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  49082. this._baseMatrix = matrix.clone();
  49083. this._localMatrix = matrix.clone();
  49084. this._skeleton._markAsDirty();
  49085. if (updateDifferenceMatrix) {
  49086. this._updateDifferenceMatrix();
  49087. }
  49088. };
  49089. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  49090. if (!rootMatrix) {
  49091. rootMatrix = this._baseMatrix;
  49092. }
  49093. if (this._parent) {
  49094. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  49095. }
  49096. else {
  49097. this._absoluteTransform.copyFrom(rootMatrix);
  49098. }
  49099. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  49100. for (var index = 0; index < this.children.length; index++) {
  49101. this.children[index]._updateDifferenceMatrix();
  49102. }
  49103. };
  49104. Bone.prototype.markAsDirty = function () {
  49105. this._currentRenderId++;
  49106. this._skeleton._markAsDirty();
  49107. };
  49108. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  49109. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  49110. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  49111. // all animation may be coming from a library skeleton, so may need to create animation
  49112. if (this.animations.length === 0) {
  49113. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  49114. this.animations[0].setKeys([]);
  49115. }
  49116. // get animation info / verify there is such a range from the source bone
  49117. var sourceRange = source.animations[0].getRange(rangeName);
  49118. if (!sourceRange) {
  49119. return false;
  49120. }
  49121. var from = sourceRange.from;
  49122. var to = sourceRange.to;
  49123. var sourceKeys = source.animations[0].getKeys();
  49124. // rescaling prep
  49125. var sourceBoneLength = source.length;
  49126. var sourceParent = source.getParent();
  49127. var parent = this.getParent();
  49128. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  49129. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  49130. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  49131. var destKeys = this.animations[0].getKeys();
  49132. // loop vars declaration
  49133. var orig;
  49134. var origTranslation;
  49135. var mat;
  49136. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  49137. orig = sourceKeys[key];
  49138. if (orig.frame >= from && orig.frame <= to) {
  49139. if (rescaleAsRequired) {
  49140. mat = orig.value.clone();
  49141. // scale based on parent ratio, when bone has parent
  49142. if (parentScalingReqd) {
  49143. origTranslation = mat.getTranslation();
  49144. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  49145. // scale based on skeleton dimension ratio when root bone, and value is passed
  49146. }
  49147. else if (dimensionsScalingReqd) {
  49148. origTranslation = mat.getTranslation();
  49149. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  49150. // use original when root bone, and no data for skelDimensionsRatio
  49151. }
  49152. else {
  49153. mat = orig.value;
  49154. }
  49155. }
  49156. else {
  49157. mat = orig.value;
  49158. }
  49159. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  49160. }
  49161. }
  49162. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  49163. return true;
  49164. };
  49165. /**
  49166. * Translate the bone in local or world space.
  49167. * @param vec The amount to translate the bone.
  49168. * @param space The space that the translation is in.
  49169. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49170. */
  49171. Bone.prototype.translate = function (vec, space, mesh) {
  49172. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49173. var lm = this.getLocalMatrix();
  49174. if (space == BABYLON.Space.LOCAL) {
  49175. lm.m[12] += vec.x;
  49176. lm.m[13] += vec.y;
  49177. lm.m[14] += vec.z;
  49178. }
  49179. else {
  49180. var wm;
  49181. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  49182. if (mesh) {
  49183. wm = mesh.getWorldMatrix();
  49184. }
  49185. this._skeleton.computeAbsoluteTransforms();
  49186. var tmat = Bone._tmpMats[0];
  49187. var tvec = Bone._tmpVecs[0];
  49188. if (mesh) {
  49189. tmat.copyFrom(this._parent.getAbsoluteTransform());
  49190. tmat.multiplyToRef(wm, tmat);
  49191. }
  49192. else {
  49193. tmat.copyFrom(this._parent.getAbsoluteTransform());
  49194. }
  49195. tmat.m[12] = 0;
  49196. tmat.m[13] = 0;
  49197. tmat.m[14] = 0;
  49198. tmat.invert();
  49199. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  49200. lm.m[12] += tvec.x;
  49201. lm.m[13] += tvec.y;
  49202. lm.m[14] += tvec.z;
  49203. }
  49204. this.markAsDirty();
  49205. };
  49206. /**
  49207. * Set the postion of the bone in local or world space.
  49208. * @param position The position to set the bone.
  49209. * @param space The space that the position is in.
  49210. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49211. */
  49212. Bone.prototype.setPosition = function (position, space, mesh) {
  49213. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49214. var lm = this.getLocalMatrix();
  49215. if (space == BABYLON.Space.LOCAL) {
  49216. lm.m[12] = position.x;
  49217. lm.m[13] = position.y;
  49218. lm.m[14] = position.z;
  49219. }
  49220. else {
  49221. var wm;
  49222. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  49223. if (mesh) {
  49224. wm = mesh.getWorldMatrix();
  49225. }
  49226. this._skeleton.computeAbsoluteTransforms();
  49227. var tmat = Bone._tmpMats[0];
  49228. var vec = Bone._tmpVecs[0];
  49229. if (mesh) {
  49230. tmat.copyFrom(this._parent.getAbsoluteTransform());
  49231. tmat.multiplyToRef(wm, tmat);
  49232. }
  49233. else {
  49234. tmat.copyFrom(this._parent.getAbsoluteTransform());
  49235. }
  49236. tmat.invert();
  49237. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  49238. lm.m[12] = vec.x;
  49239. lm.m[13] = vec.y;
  49240. lm.m[14] = vec.z;
  49241. }
  49242. this.markAsDirty();
  49243. };
  49244. /**
  49245. * Set the absolute postion of the bone (world space).
  49246. * @param position The position to set the bone.
  49247. * @param mesh The mesh that this bone is attached to.
  49248. */
  49249. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  49250. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  49251. };
  49252. /**
  49253. * Set the scale of the bone on the x, y and z axes.
  49254. * @param x The scale of the bone on the x axis.
  49255. * @param x The scale of the bone on the y axis.
  49256. * @param z The scale of the bone on the z axis.
  49257. * @param scaleChildren Set this to true if children of the bone should be scaled.
  49258. */
  49259. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  49260. if (scaleChildren === void 0) { scaleChildren = false; }
  49261. if (this.animations[0] && !this.animations[0].isStopped()) {
  49262. if (!scaleChildren) {
  49263. this._negateScaleChildren.x = 1 / x;
  49264. this._negateScaleChildren.y = 1 / y;
  49265. this._negateScaleChildren.z = 1 / z;
  49266. }
  49267. this._syncScaleVector();
  49268. }
  49269. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  49270. };
  49271. /**
  49272. * Scale the bone on the x, y and z axes.
  49273. * @param x The amount to scale the bone on the x axis.
  49274. * @param x The amount to scale the bone on the y axis.
  49275. * @param z The amount to scale the bone on the z axis.
  49276. * @param scaleChildren Set this to true if children of the bone should be scaled.
  49277. */
  49278. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  49279. if (scaleChildren === void 0) { scaleChildren = false; }
  49280. var locMat = this.getLocalMatrix();
  49281. var origLocMat = Bone._tmpMats[0];
  49282. origLocMat.copyFrom(locMat);
  49283. var origLocMatInv = Bone._tmpMats[1];
  49284. origLocMatInv.copyFrom(origLocMat);
  49285. origLocMatInv.invert();
  49286. var scaleMat = Bone._tmpMats[2];
  49287. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  49288. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  49289. this._scaleVector.x *= x;
  49290. this._scaleVector.y *= y;
  49291. this._scaleVector.z *= z;
  49292. locMat.multiplyToRef(origLocMatInv, locMat);
  49293. locMat.multiplyToRef(scaleMat, locMat);
  49294. locMat.multiplyToRef(origLocMat, locMat);
  49295. var parent = this.getParent();
  49296. if (parent) {
  49297. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  49298. }
  49299. else {
  49300. this.getAbsoluteTransform().copyFrom(locMat);
  49301. }
  49302. var len = this.children.length;
  49303. scaleMat.invert();
  49304. for (var i = 0; i < len; i++) {
  49305. var child = this.children[i];
  49306. var cm = child.getLocalMatrix();
  49307. cm.multiplyToRef(scaleMat, cm);
  49308. var lm = child.getLocalMatrix();
  49309. lm.m[12] *= x;
  49310. lm.m[13] *= y;
  49311. lm.m[14] *= z;
  49312. }
  49313. this.computeAbsoluteTransforms();
  49314. if (scaleChildren) {
  49315. for (var i = 0; i < len; i++) {
  49316. this.children[i].scale(x, y, z, scaleChildren);
  49317. }
  49318. }
  49319. this.markAsDirty();
  49320. };
  49321. /**
  49322. * Set the yaw, pitch, and roll of the bone in local or world space.
  49323. * @param yaw The rotation of the bone on the y axis.
  49324. * @param pitch The rotation of the bone on the x axis.
  49325. * @param roll The rotation of the bone on the z axis.
  49326. * @param space The space that the axes of rotation are in.
  49327. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49328. */
  49329. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  49330. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49331. var rotMat = Bone._tmpMats[0];
  49332. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  49333. var rotMatInv = Bone._tmpMats[1];
  49334. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  49335. rotMatInv.multiplyToRef(rotMat, rotMat);
  49336. this._rotateWithMatrix(rotMat, space, mesh);
  49337. };
  49338. /**
  49339. * Rotate the bone on an axis in local or world space.
  49340. * @param axis The axis to rotate the bone on.
  49341. * @param amount The amount to rotate the bone.
  49342. * @param space The space that the axis is in.
  49343. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49344. */
  49345. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  49346. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49347. var rmat = Bone._tmpMats[0];
  49348. rmat.m[12] = 0;
  49349. rmat.m[13] = 0;
  49350. rmat.m[14] = 0;
  49351. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  49352. this._rotateWithMatrix(rmat, space, mesh);
  49353. };
  49354. /**
  49355. * Set the rotation of the bone to a particular axis angle in local or world space.
  49356. * @param axis The axis to rotate the bone on.
  49357. * @param angle The angle that the bone should be rotated to.
  49358. * @param space The space that the axis is in.
  49359. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49360. */
  49361. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  49362. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49363. var rotMat = Bone._tmpMats[0];
  49364. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  49365. var rotMatInv = Bone._tmpMats[1];
  49366. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  49367. rotMatInv.multiplyToRef(rotMat, rotMat);
  49368. this._rotateWithMatrix(rotMat, space, mesh);
  49369. };
  49370. /**
  49371. * Set the euler rotation of the bone in local of world space.
  49372. * @param rotation The euler rotation that the bone should be set to.
  49373. * @param space The space that the rotation is in.
  49374. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49375. */
  49376. Bone.prototype.setRotation = function (rotation, space, mesh) {
  49377. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49378. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  49379. };
  49380. /**
  49381. * Set the quaternion rotation of the bone in local of world space.
  49382. * @param quat The quaternion rotation that the bone should be set to.
  49383. * @param space The space that the rotation is in.
  49384. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49385. */
  49386. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  49387. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49388. var rotMatInv = Bone._tmpMats[0];
  49389. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  49390. var rotMat = Bone._tmpMats[1];
  49391. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  49392. rotMatInv.multiplyToRef(rotMat, rotMat);
  49393. this._rotateWithMatrix(rotMat, space, mesh);
  49394. };
  49395. /**
  49396. * Set the rotation matrix of the bone in local of world space.
  49397. * @param rotMat The rotation matrix that the bone should be set to.
  49398. * @param space The space that the rotation is in.
  49399. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49400. */
  49401. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  49402. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49403. var rotMatInv = Bone._tmpMats[0];
  49404. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  49405. var rotMat2 = Bone._tmpMats[1];
  49406. rotMat2.copyFrom(rotMat);
  49407. rotMatInv.multiplyToRef(rotMat, rotMat2);
  49408. this._rotateWithMatrix(rotMat2, space, mesh);
  49409. };
  49410. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  49411. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49412. var lmat = this.getLocalMatrix();
  49413. var lx = lmat.m[12];
  49414. var ly = lmat.m[13];
  49415. var lz = lmat.m[14];
  49416. var parent = this.getParent();
  49417. var parentScale = Bone._tmpMats[3];
  49418. var parentScaleInv = Bone._tmpMats[4];
  49419. if (parent) {
  49420. if (space == BABYLON.Space.WORLD) {
  49421. if (mesh) {
  49422. parentScale.copyFrom(mesh.getWorldMatrix());
  49423. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  49424. }
  49425. else {
  49426. parentScale.copyFrom(parent.getAbsoluteTransform());
  49427. }
  49428. }
  49429. else {
  49430. parentScale = parent._scaleMatrix;
  49431. }
  49432. parentScaleInv.copyFrom(parentScale);
  49433. parentScaleInv.invert();
  49434. lmat.multiplyToRef(parentScale, lmat);
  49435. lmat.multiplyToRef(rmat, lmat);
  49436. lmat.multiplyToRef(parentScaleInv, lmat);
  49437. }
  49438. else {
  49439. if (space == BABYLON.Space.WORLD && mesh) {
  49440. parentScale.copyFrom(mesh.getWorldMatrix());
  49441. parentScaleInv.copyFrom(parentScale);
  49442. parentScaleInv.invert();
  49443. lmat.multiplyToRef(parentScale, lmat);
  49444. lmat.multiplyToRef(rmat, lmat);
  49445. lmat.multiplyToRef(parentScaleInv, lmat);
  49446. }
  49447. else {
  49448. lmat.multiplyToRef(rmat, lmat);
  49449. }
  49450. }
  49451. lmat.m[12] = lx;
  49452. lmat.m[13] = ly;
  49453. lmat.m[14] = lz;
  49454. this.computeAbsoluteTransforms();
  49455. this.markAsDirty();
  49456. };
  49457. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  49458. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49459. if (space == BABYLON.Space.WORLD) {
  49460. var scaleMatrix = Bone._tmpMats[2];
  49461. scaleMatrix.copyFrom(this._scaleMatrix);
  49462. rotMatInv.copyFrom(this.getAbsoluteTransform());
  49463. if (mesh) {
  49464. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  49465. var meshScale = Bone._tmpMats[3];
  49466. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  49467. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  49468. }
  49469. rotMatInv.invert();
  49470. scaleMatrix.m[0] *= this._scalingDeterminant;
  49471. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  49472. }
  49473. else {
  49474. rotMatInv.copyFrom(this.getLocalMatrix());
  49475. rotMatInv.invert();
  49476. var scaleMatrix = Bone._tmpMats[2];
  49477. scaleMatrix.copyFrom(this._scaleMatrix);
  49478. if (this._parent) {
  49479. var pscaleMatrix = Bone._tmpMats[3];
  49480. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  49481. pscaleMatrix.invert();
  49482. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  49483. }
  49484. else {
  49485. scaleMatrix.m[0] *= this._scalingDeterminant;
  49486. }
  49487. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  49488. }
  49489. };
  49490. /**
  49491. * Get the scale of the bone
  49492. * @returns the scale of the bone
  49493. */
  49494. Bone.prototype.getScale = function () {
  49495. return this._scaleVector.clone();
  49496. };
  49497. /**
  49498. * Copy the scale of the bone to a vector3.
  49499. * @param result The vector3 to copy the scale to
  49500. */
  49501. Bone.prototype.getScaleToRef = function (result) {
  49502. result.copyFrom(this._scaleVector);
  49503. };
  49504. /**
  49505. * Get the position of the bone in local or world space.
  49506. * @param space The space that the returned position is in.
  49507. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49508. * @returns The position of the bone
  49509. */
  49510. Bone.prototype.getPosition = function (space, mesh) {
  49511. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49512. var pos = BABYLON.Vector3.Zero();
  49513. this.getPositionToRef(space, mesh, pos);
  49514. return pos;
  49515. };
  49516. /**
  49517. * Copy the position of the bone to a vector3 in local or world space.
  49518. * @param space The space that the returned position is in.
  49519. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49520. * @param result The vector3 to copy the position to.
  49521. */
  49522. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  49523. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49524. if (space == BABYLON.Space.LOCAL) {
  49525. var lm = this.getLocalMatrix();
  49526. result.x = lm.m[12];
  49527. result.y = lm.m[13];
  49528. result.z = lm.m[14];
  49529. }
  49530. else {
  49531. var wm;
  49532. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  49533. if (mesh) {
  49534. wm = mesh.getWorldMatrix();
  49535. }
  49536. this._skeleton.computeAbsoluteTransforms();
  49537. var tmat = Bone._tmpMats[0];
  49538. if (mesh) {
  49539. tmat.copyFrom(this.getAbsoluteTransform());
  49540. tmat.multiplyToRef(wm, tmat);
  49541. }
  49542. else {
  49543. tmat = this.getAbsoluteTransform();
  49544. }
  49545. result.x = tmat.m[12];
  49546. result.y = tmat.m[13];
  49547. result.z = tmat.m[14];
  49548. }
  49549. };
  49550. /**
  49551. * Get the absolute position of the bone (world space).
  49552. * @param mesh The mesh that this bone is attached to.
  49553. * @returns The absolute position of the bone
  49554. */
  49555. Bone.prototype.getAbsolutePosition = function (mesh) {
  49556. var pos = BABYLON.Vector3.Zero();
  49557. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  49558. return pos;
  49559. };
  49560. /**
  49561. * Copy the absolute position of the bone (world space) to the result param.
  49562. * @param mesh The mesh that this bone is attached to.
  49563. * @param result The vector3 to copy the absolute position to.
  49564. */
  49565. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  49566. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  49567. };
  49568. /**
  49569. * Compute the absolute transforms of this bone and its children.
  49570. */
  49571. Bone.prototype.computeAbsoluteTransforms = function () {
  49572. if (this._parent) {
  49573. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  49574. }
  49575. else {
  49576. this._absoluteTransform.copyFrom(this._localMatrix);
  49577. var poseMatrix = this._skeleton.getPoseMatrix();
  49578. if (poseMatrix) {
  49579. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  49580. }
  49581. }
  49582. var children = this.children;
  49583. var len = children.length;
  49584. for (var i = 0; i < len; i++) {
  49585. children[i].computeAbsoluteTransforms();
  49586. }
  49587. };
  49588. Bone.prototype._syncScaleVector = function () {
  49589. var lm = this.getLocalMatrix();
  49590. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  49591. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  49592. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  49593. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  49594. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  49595. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  49596. this._scaleVector.x = xs * Math.sqrt(xsq);
  49597. this._scaleVector.y = ys * Math.sqrt(ysq);
  49598. this._scaleVector.z = zs * Math.sqrt(zsq);
  49599. if (this._parent) {
  49600. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  49601. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  49602. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  49603. }
  49604. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  49605. };
  49606. /**
  49607. * Get the world direction from an axis that is in the local space of the bone.
  49608. * @param localAxis The local direction that is used to compute the world direction.
  49609. * @param mesh The mesh that this bone is attached to.
  49610. * @returns The world direction
  49611. */
  49612. Bone.prototype.getDirection = function (localAxis, mesh) {
  49613. var result = BABYLON.Vector3.Zero();
  49614. this.getDirectionToRef(localAxis, mesh, result);
  49615. return result;
  49616. };
  49617. /**
  49618. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  49619. * @param localAxis The local direction that is used to compute the world direction.
  49620. * @param mesh The mesh that this bone is attached to.
  49621. * @param result The vector3 that the world direction will be copied to.
  49622. */
  49623. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  49624. var wm;
  49625. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  49626. if (mesh) {
  49627. wm = mesh.getWorldMatrix();
  49628. }
  49629. this._skeleton.computeAbsoluteTransforms();
  49630. var mat = Bone._tmpMats[0];
  49631. mat.copyFrom(this.getAbsoluteTransform());
  49632. if (mesh) {
  49633. mat.multiplyToRef(wm, mat);
  49634. }
  49635. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  49636. result.normalize();
  49637. };
  49638. /**
  49639. * Get the euler rotation of the bone in local or world space.
  49640. * @param space The space that the rotation should be in.
  49641. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49642. * @returns The euler rotation
  49643. */
  49644. Bone.prototype.getRotation = function (space, mesh) {
  49645. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49646. var result = BABYLON.Vector3.Zero();
  49647. this.getRotationToRef(space, mesh, result);
  49648. return result;
  49649. };
  49650. /**
  49651. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  49652. * @param space The space that the rotation should be in.
  49653. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49654. * @param result The vector3 that the rotation should be copied to.
  49655. */
  49656. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  49657. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49658. var quat = Bone._tmpQuat;
  49659. this.getRotationQuaternionToRef(space, mesh, quat);
  49660. quat.toEulerAnglesToRef(result);
  49661. };
  49662. /**
  49663. * Get the quaternion rotation of the bone in either local or world space.
  49664. * @param space The space that the rotation should be in.
  49665. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49666. * @returns The quaternion rotation
  49667. */
  49668. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  49669. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49670. var result = BABYLON.Quaternion.Identity();
  49671. this.getRotationQuaternionToRef(space, mesh, result);
  49672. return result;
  49673. };
  49674. /**
  49675. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  49676. * @param space The space that the rotation should be in.
  49677. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49678. * @param result The quaternion that the rotation should be copied to.
  49679. */
  49680. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  49681. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49682. if (space == BABYLON.Space.LOCAL) {
  49683. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  49684. }
  49685. else {
  49686. var mat = Bone._tmpMats[0];
  49687. var amat = this.getAbsoluteTransform();
  49688. if (mesh) {
  49689. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  49690. }
  49691. else {
  49692. mat.copyFrom(amat);
  49693. }
  49694. mat.m[0] *= this._scalingDeterminant;
  49695. mat.m[1] *= this._scalingDeterminant;
  49696. mat.m[2] *= this._scalingDeterminant;
  49697. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  49698. }
  49699. };
  49700. /**
  49701. * Get the rotation matrix of the bone in local or world space.
  49702. * @param space The space that the rotation should be in.
  49703. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49704. * @returns The rotation matrix
  49705. */
  49706. Bone.prototype.getRotationMatrix = function (space, mesh) {
  49707. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49708. var result = BABYLON.Matrix.Identity();
  49709. this.getRotationMatrixToRef(space, mesh, result);
  49710. return result;
  49711. };
  49712. /**
  49713. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  49714. * @param space The space that the rotation should be in.
  49715. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49716. * @param result The quaternion that the rotation should be copied to.
  49717. */
  49718. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  49719. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49720. if (space == BABYLON.Space.LOCAL) {
  49721. this.getLocalMatrix().getRotationMatrixToRef(result);
  49722. }
  49723. else {
  49724. var mat = Bone._tmpMats[0];
  49725. var amat = this.getAbsoluteTransform();
  49726. if (mesh) {
  49727. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  49728. }
  49729. else {
  49730. mat.copyFrom(amat);
  49731. }
  49732. mat.m[0] *= this._scalingDeterminant;
  49733. mat.m[1] *= this._scalingDeterminant;
  49734. mat.m[2] *= this._scalingDeterminant;
  49735. mat.getRotationMatrixToRef(result);
  49736. }
  49737. };
  49738. /**
  49739. * Get the world position of a point that is in the local space of the bone.
  49740. * @param position The local position
  49741. * @param mesh The mesh that this bone is attached to.
  49742. * @returns The world position
  49743. */
  49744. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  49745. var result = BABYLON.Vector3.Zero();
  49746. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  49747. return result;
  49748. };
  49749. /**
  49750. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  49751. * @param position The local position
  49752. * @param mesh The mesh that this bone is attached to.
  49753. * @param result The vector3 that the world position should be copied to.
  49754. */
  49755. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  49756. var wm;
  49757. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  49758. if (mesh) {
  49759. wm = mesh.getWorldMatrix();
  49760. }
  49761. this._skeleton.computeAbsoluteTransforms();
  49762. var tmat = Bone._tmpMats[0];
  49763. if (mesh) {
  49764. tmat.copyFrom(this.getAbsoluteTransform());
  49765. tmat.multiplyToRef(wm, tmat);
  49766. }
  49767. else {
  49768. tmat = this.getAbsoluteTransform();
  49769. }
  49770. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  49771. };
  49772. /**
  49773. * Get the local position of a point that is in world space.
  49774. * @param position The world position
  49775. * @param mesh The mesh that this bone is attached to.
  49776. * @returns The local position
  49777. */
  49778. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  49779. var result = BABYLON.Vector3.Zero();
  49780. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  49781. return result;
  49782. };
  49783. /**
  49784. * Get the local position of a point that is in world space and copy it to the result param.
  49785. * @param position The world position
  49786. * @param mesh The mesh that this bone is attached to.
  49787. * @param result The vector3 that the local position should be copied to.
  49788. */
  49789. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  49790. var wm;
  49791. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  49792. if (mesh) {
  49793. wm = mesh.getWorldMatrix();
  49794. }
  49795. this._skeleton.computeAbsoluteTransforms();
  49796. var tmat = Bone._tmpMats[0];
  49797. tmat.copyFrom(this.getAbsoluteTransform());
  49798. if (mesh) {
  49799. tmat.multiplyToRef(wm, tmat);
  49800. }
  49801. tmat.invert();
  49802. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  49803. };
  49804. return Bone;
  49805. }(BABYLON.Node));
  49806. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  49807. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  49808. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  49809. BABYLON.Bone = Bone;
  49810. })(BABYLON || (BABYLON = {}));
  49811. //# sourceMappingURL=babylon.bone.js.map
  49812. var BABYLON;
  49813. (function (BABYLON) {
  49814. var BoneIKController = (function () {
  49815. function BoneIKController(mesh, bone, options) {
  49816. this.targetPosition = BABYLON.Vector3.Zero();
  49817. this.poleTargetPosition = BABYLON.Vector3.Zero();
  49818. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  49819. this.poleAngle = 0;
  49820. this.slerpAmount = 1;
  49821. this._bone1Quat = BABYLON.Quaternion.Identity();
  49822. this._bone1Mat = BABYLON.Matrix.Identity();
  49823. this._bone2Ang = Math.PI;
  49824. this._maxAngle = Math.PI;
  49825. this._rightHandedSystem = false;
  49826. this._bendAxis = BABYLON.Vector3.Right();
  49827. this._slerping = false;
  49828. this._adjustRoll = 0;
  49829. this._bone2 = bone;
  49830. this._bone1 = bone.getParent();
  49831. this.mesh = mesh;
  49832. var bonePos = bone.getPosition();
  49833. if (bone.getAbsoluteTransform().determinant() > 0) {
  49834. this._rightHandedSystem = true;
  49835. this._bendAxis.x = 0;
  49836. this._bendAxis.y = 0;
  49837. this._bendAxis.z = -1;
  49838. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  49839. this._adjustRoll = Math.PI * .5;
  49840. this._bendAxis.z = 1;
  49841. }
  49842. }
  49843. if (this._bone1.length) {
  49844. var boneScale1 = this._bone1.getScale();
  49845. var boneScale2 = this._bone2.getScale();
  49846. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  49847. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  49848. }
  49849. else if (this._bone1.children[0]) {
  49850. mesh.computeWorldMatrix(true);
  49851. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  49852. var pos2 = this._bone2.getAbsolutePosition(mesh);
  49853. var pos3 = this._bone1.getAbsolutePosition(mesh);
  49854. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  49855. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  49856. }
  49857. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  49858. this.maxAngle = Math.PI;
  49859. if (options) {
  49860. if (options.targetMesh) {
  49861. this.targetMesh = options.targetMesh;
  49862. this.targetMesh.computeWorldMatrix(true);
  49863. }
  49864. if (options.poleTargetMesh) {
  49865. this.poleTargetMesh = options.poleTargetMesh;
  49866. this.poleTargetMesh.computeWorldMatrix(true);
  49867. }
  49868. else if (options.poleTargetBone) {
  49869. this.poleTargetBone = options.poleTargetBone;
  49870. }
  49871. else if (this._bone1.getParent()) {
  49872. this.poleTargetBone = this._bone1.getParent();
  49873. }
  49874. if (options.poleTargetLocalOffset) {
  49875. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  49876. }
  49877. if (options.poleAngle) {
  49878. this.poleAngle = options.poleAngle;
  49879. }
  49880. if (options.bendAxis) {
  49881. this._bendAxis.copyFrom(options.bendAxis);
  49882. }
  49883. if (options.maxAngle) {
  49884. this.maxAngle = options.maxAngle;
  49885. }
  49886. if (options.slerpAmount) {
  49887. this.slerpAmount = options.slerpAmount;
  49888. }
  49889. }
  49890. }
  49891. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  49892. get: function () {
  49893. return this._maxAngle;
  49894. },
  49895. set: function (value) {
  49896. this._setMaxAngle(value);
  49897. },
  49898. enumerable: true,
  49899. configurable: true
  49900. });
  49901. BoneIKController.prototype._setMaxAngle = function (ang) {
  49902. if (ang < 0) {
  49903. ang = 0;
  49904. }
  49905. if (ang > Math.PI || ang == undefined) {
  49906. ang = Math.PI;
  49907. }
  49908. this._maxAngle = ang;
  49909. var a = this._bone1Length;
  49910. var b = this._bone2Length;
  49911. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  49912. };
  49913. BoneIKController.prototype.update = function () {
  49914. var bone1 = this._bone1;
  49915. var target = this.targetPosition;
  49916. var poleTarget = this.poleTargetPosition;
  49917. var mat1 = BoneIKController._tmpMats[0];
  49918. var mat2 = BoneIKController._tmpMats[1];
  49919. if (this.targetMesh) {
  49920. target.copyFrom(this.targetMesh.getAbsolutePosition());
  49921. }
  49922. if (this.poleTargetBone) {
  49923. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  49924. }
  49925. else if (this.poleTargetMesh) {
  49926. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  49927. }
  49928. var bonePos = BoneIKController._tmpVecs[0];
  49929. var zaxis = BoneIKController._tmpVecs[1];
  49930. var xaxis = BoneIKController._tmpVecs[2];
  49931. var yaxis = BoneIKController._tmpVecs[3];
  49932. var upAxis = BoneIKController._tmpVecs[4];
  49933. var _tmpQuat = BoneIKController._tmpQuat;
  49934. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  49935. poleTarget.subtractToRef(bonePos, upAxis);
  49936. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  49937. upAxis.y = 1;
  49938. }
  49939. else {
  49940. upAxis.normalize();
  49941. }
  49942. target.subtractToRef(bonePos, yaxis);
  49943. yaxis.normalize();
  49944. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  49945. zaxis.normalize();
  49946. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  49947. xaxis.normalize();
  49948. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  49949. var a = this._bone1Length;
  49950. var b = this._bone2Length;
  49951. var c = BABYLON.Vector3.Distance(bonePos, target);
  49952. if (this._maxReach > 0) {
  49953. c = Math.min(this._maxReach, c);
  49954. }
  49955. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  49956. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  49957. if (acosa > 1) {
  49958. acosa = 1;
  49959. }
  49960. if (acosb > 1) {
  49961. acosb = 1;
  49962. }
  49963. if (acosa < -1) {
  49964. acosa = -1;
  49965. }
  49966. if (acosb < -1) {
  49967. acosb = -1;
  49968. }
  49969. var angA = Math.acos(acosa);
  49970. var angB = Math.acos(acosb);
  49971. var angC = -angA - angB;
  49972. if (this._rightHandedSystem) {
  49973. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  49974. mat2.multiplyToRef(mat1, mat1);
  49975. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  49976. mat2.multiplyToRef(mat1, mat1);
  49977. }
  49978. else {
  49979. var _tmpVec = BoneIKController._tmpVecs[5];
  49980. _tmpVec.copyFrom(this._bendAxis);
  49981. _tmpVec.x *= -1;
  49982. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  49983. mat2.multiplyToRef(mat1, mat1);
  49984. }
  49985. if (this.poleAngle) {
  49986. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  49987. mat1.multiplyToRef(mat2, mat1);
  49988. }
  49989. if (this.slerpAmount < 1) {
  49990. if (!this._slerping) {
  49991. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  49992. }
  49993. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  49994. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  49995. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  49996. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  49997. this._slerping = true;
  49998. }
  49999. else {
  50000. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  50001. this._bone1Mat.copyFrom(mat1);
  50002. this._slerping = false;
  50003. }
  50004. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  50005. this._bone2Ang = angC;
  50006. };
  50007. return BoneIKController;
  50008. }());
  50009. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  50010. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  50011. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  50012. BABYLON.BoneIKController = BoneIKController;
  50013. })(BABYLON || (BABYLON = {}));
  50014. //# sourceMappingURL=babylon.boneIKController.js.map
  50015. var BABYLON;
  50016. (function (BABYLON) {
  50017. var BoneLookController = (function () {
  50018. /**
  50019. * Create a BoneLookController
  50020. * @param mesh the mesh that the bone belongs to
  50021. * @param bone the bone that will be looking to the target
  50022. * @param target the target Vector3 to look at
  50023. * @param settings optional settings:
  50024. * - maxYaw: the maximum angle the bone will yaw to
  50025. * - minYaw: the minimum angle the bone will yaw to
  50026. * - maxPitch: the maximum angle the bone will pitch to
  50027. * - minPitch: the minimum angle the bone will yaw to
  50028. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  50029. * - upAxis: the up axis of the coordinate system
  50030. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  50031. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  50032. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  50033. * - adjustYaw: used to make an adjustment to the yaw of the bone
  50034. * - adjustPitch: used to make an adjustment to the pitch of the bone
  50035. * - adjustRoll: used to make an adjustment to the roll of the bone
  50036. **/
  50037. function BoneLookController(mesh, bone, target, options) {
  50038. /**
  50039. * The up axis of the coordinate system that is used when the bone is rotated.
  50040. */
  50041. this.upAxis = BABYLON.Vector3.Up();
  50042. /**
  50043. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  50044. */
  50045. this.upAxisSpace = BABYLON.Space.LOCAL;
  50046. /**
  50047. * Used to make an adjustment to the yaw of the bone.
  50048. */
  50049. this.adjustYaw = 0;
  50050. /**
  50051. * Used to make an adjustment to the pitch of the bone.
  50052. */
  50053. this.adjustPitch = 0;
  50054. /**
  50055. * Used to make an adjustment to the roll of the bone.
  50056. */
  50057. this.adjustRoll = 0;
  50058. /**
  50059. * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp).
  50060. */
  50061. this.slerpAmount = 1;
  50062. this._boneQuat = BABYLON.Quaternion.Identity();
  50063. this._slerping = false;
  50064. this._firstFrameSkipped = false;
  50065. this._fowardAxis = BABYLON.Vector3.Forward();
  50066. this.mesh = mesh;
  50067. this.bone = bone;
  50068. this.target = target;
  50069. if (options) {
  50070. if (options.adjustYaw) {
  50071. this.adjustYaw = options.adjustYaw;
  50072. }
  50073. if (options.adjustPitch) {
  50074. this.adjustPitch = options.adjustPitch;
  50075. }
  50076. if (options.adjustRoll) {
  50077. this.adjustRoll = options.adjustRoll;
  50078. }
  50079. if (options.maxYaw != null) {
  50080. this.maxYaw = options.maxYaw;
  50081. }
  50082. else {
  50083. this.maxYaw = Math.PI;
  50084. }
  50085. if (options.minYaw != null) {
  50086. this.minYaw = options.minYaw;
  50087. }
  50088. else {
  50089. this.minYaw = -Math.PI;
  50090. }
  50091. if (options.maxPitch != null) {
  50092. this.maxPitch = options.maxPitch;
  50093. }
  50094. else {
  50095. this.maxPitch = Math.PI;
  50096. }
  50097. if (options.minPitch != null) {
  50098. this.minPitch = options.minPitch;
  50099. }
  50100. else {
  50101. this.minPitch = -Math.PI;
  50102. }
  50103. if (options.slerpAmount != null) {
  50104. this.slerpAmount = options.slerpAmount;
  50105. }
  50106. if (options.upAxis != null) {
  50107. this.upAxis = options.upAxis;
  50108. }
  50109. if (options.upAxisSpace != null) {
  50110. this.upAxisSpace = options.upAxisSpace;
  50111. }
  50112. if (options.yawAxis != null || options.pitchAxis != null) {
  50113. var newYawAxis = BABYLON.Axis.Y;
  50114. var newPitchAxis = BABYLON.Axis.X;
  50115. if (options.yawAxis != null) {
  50116. newYawAxis = options.yawAxis.clone();
  50117. newYawAxis.normalize();
  50118. }
  50119. if (options.pitchAxis != null) {
  50120. newPitchAxis = options.pitchAxis.clone();
  50121. newPitchAxis.normalize();
  50122. }
  50123. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  50124. this._transformYawPitch = BABYLON.Matrix.Identity();
  50125. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  50126. this._transformYawPitchInv = this._transformYawPitch.clone();
  50127. this._transformYawPitch.invert();
  50128. }
  50129. }
  50130. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  50131. this.upAxisSpace = BABYLON.Space.LOCAL;
  50132. }
  50133. }
  50134. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  50135. /**
  50136. * Get/set the minimum yaw angle that the bone can look to.
  50137. */
  50138. get: function () {
  50139. return this._minYaw;
  50140. },
  50141. set: function (value) {
  50142. this._minYaw = value;
  50143. this._minYawSin = Math.sin(value);
  50144. this._minYawCos = Math.cos(value);
  50145. if (this._maxYaw != null) {
  50146. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  50147. this._yawRange = this._maxYaw - this._minYaw;
  50148. }
  50149. },
  50150. enumerable: true,
  50151. configurable: true
  50152. });
  50153. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  50154. /**
  50155. * Get/set the maximum yaw angle that the bone can look to.
  50156. */
  50157. get: function () {
  50158. return this._maxYaw;
  50159. },
  50160. set: function (value) {
  50161. this._maxYaw = value;
  50162. this._maxYawSin = Math.sin(value);
  50163. this._maxYawCos = Math.cos(value);
  50164. if (this._minYaw != null) {
  50165. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  50166. this._yawRange = this._maxYaw - this._minYaw;
  50167. }
  50168. },
  50169. enumerable: true,
  50170. configurable: true
  50171. });
  50172. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  50173. /**
  50174. * Get/set the minimum pitch angle that the bone can look to.
  50175. */
  50176. get: function () {
  50177. return this._minPitch;
  50178. },
  50179. set: function (value) {
  50180. this._minPitch = value;
  50181. this._minPitchTan = Math.tan(value);
  50182. },
  50183. enumerable: true,
  50184. configurable: true
  50185. });
  50186. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  50187. /**
  50188. * Get/set the maximum pitch angle that the bone can look to.
  50189. */
  50190. get: function () {
  50191. return this._maxPitch;
  50192. },
  50193. set: function (value) {
  50194. this._maxPitch = value;
  50195. this._maxPitchTan = Math.tan(value);
  50196. },
  50197. enumerable: true,
  50198. configurable: true
  50199. });
  50200. /**
  50201. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  50202. */
  50203. BoneLookController.prototype.update = function () {
  50204. //skip the first frame when slerping so that the mesh rotation is correct
  50205. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  50206. this._firstFrameSkipped = true;
  50207. return;
  50208. }
  50209. var bone = this.bone;
  50210. var bonePos = BoneLookController._tmpVecs[0];
  50211. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  50212. var target = this.target;
  50213. var _tmpMat1 = BoneLookController._tmpMats[0];
  50214. var _tmpMat2 = BoneLookController._tmpMats[1];
  50215. var mesh = this.mesh;
  50216. var parentBone = bone.getParent();
  50217. var upAxis = BoneLookController._tmpVecs[1];
  50218. upAxis.copyFrom(this.upAxis);
  50219. if (this.upAxisSpace == BABYLON.Space.BONE) {
  50220. if (this._transformYawPitch) {
  50221. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  50222. }
  50223. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  50224. }
  50225. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  50226. mesh.getDirectionToRef(upAxis, upAxis);
  50227. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  50228. upAxis.normalize();
  50229. }
  50230. }
  50231. var checkYaw = false;
  50232. var checkPitch = false;
  50233. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  50234. checkYaw = true;
  50235. }
  50236. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  50237. checkPitch = true;
  50238. }
  50239. if (checkYaw || checkPitch) {
  50240. var spaceMat = BoneLookController._tmpMats[2];
  50241. var spaceMatInv = BoneLookController._tmpMats[3];
  50242. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  50243. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  50244. }
  50245. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  50246. spaceMat.copyFrom(mesh.getWorldMatrix());
  50247. }
  50248. else {
  50249. var forwardAxis = BoneLookController._tmpVecs[2];
  50250. forwardAxis.copyFrom(this._fowardAxis);
  50251. if (this._transformYawPitch) {
  50252. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  50253. }
  50254. if (parentBone) {
  50255. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  50256. }
  50257. else {
  50258. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  50259. }
  50260. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  50261. rightAxis.normalize();
  50262. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  50263. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  50264. }
  50265. spaceMat.invertToRef(spaceMatInv);
  50266. var xzlen;
  50267. if (checkPitch) {
  50268. var localTarget = BoneLookController._tmpVecs[3];
  50269. target.subtractToRef(bonePos, localTarget);
  50270. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  50271. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  50272. var pitch = Math.atan2(localTarget.y, xzlen);
  50273. var newPitch = pitch;
  50274. if (pitch > this._maxPitch) {
  50275. localTarget.y = this._maxPitchTan * xzlen;
  50276. newPitch = this._maxPitch;
  50277. }
  50278. else if (pitch < this._minPitch) {
  50279. localTarget.y = this._minPitchTan * xzlen;
  50280. newPitch = this._minPitch;
  50281. }
  50282. if (pitch != newPitch) {
  50283. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  50284. localTarget.addInPlace(bonePos);
  50285. target = localTarget;
  50286. }
  50287. }
  50288. if (checkYaw) {
  50289. var localTarget = BoneLookController._tmpVecs[4];
  50290. target.subtractToRef(bonePos, localTarget);
  50291. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  50292. var yaw = Math.atan2(localTarget.x, localTarget.z);
  50293. var newYaw = yaw;
  50294. if (yaw > this._maxYaw || yaw < this._minYaw) {
  50295. if (xzlen == null) {
  50296. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  50297. }
  50298. if (this._yawRange > Math.PI) {
  50299. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  50300. localTarget.z = this._maxYawCos * xzlen;
  50301. localTarget.x = this._maxYawSin * xzlen;
  50302. newYaw = this._maxYaw;
  50303. }
  50304. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  50305. localTarget.z = this._minYawCos * xzlen;
  50306. localTarget.x = this._minYawSin * xzlen;
  50307. newYaw = this._minYaw;
  50308. }
  50309. }
  50310. else {
  50311. if (yaw > this._maxYaw) {
  50312. localTarget.z = this._maxYawCos * xzlen;
  50313. localTarget.x = this._maxYawSin * xzlen;
  50314. newYaw = this._maxYaw;
  50315. }
  50316. else if (yaw < this._minYaw) {
  50317. localTarget.z = this._minYawCos * xzlen;
  50318. localTarget.x = this._minYawSin * xzlen;
  50319. newYaw = this._minYaw;
  50320. }
  50321. }
  50322. }
  50323. if (this._slerping && this._yawRange > Math.PI) {
  50324. //are we going to be crossing into the min/max region?
  50325. var boneFwd = BoneLookController._tmpVecs[8];
  50326. boneFwd.copyFrom(BABYLON.Axis.Z);
  50327. if (this._transformYawPitch) {
  50328. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  50329. }
  50330. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  50331. this._boneQuat.toRotationMatrix(boneRotMat);
  50332. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  50333. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  50334. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  50335. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  50336. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  50337. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  50338. if (angBtwTar > angBtwMidYaw) {
  50339. if (xzlen == null) {
  50340. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  50341. }
  50342. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  50343. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  50344. if (angBtwMin < angBtwMax) {
  50345. newYaw = boneYaw + Math.PI * .75;
  50346. localTarget.z = Math.cos(newYaw) * xzlen;
  50347. localTarget.x = Math.sin(newYaw) * xzlen;
  50348. }
  50349. else {
  50350. newYaw = boneYaw - Math.PI * .75;
  50351. localTarget.z = Math.cos(newYaw) * xzlen;
  50352. localTarget.x = Math.sin(newYaw) * xzlen;
  50353. }
  50354. }
  50355. }
  50356. if (yaw != newYaw) {
  50357. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  50358. localTarget.addInPlace(bonePos);
  50359. target = localTarget;
  50360. }
  50361. }
  50362. }
  50363. var zaxis = BoneLookController._tmpVecs[5];
  50364. var xaxis = BoneLookController._tmpVecs[6];
  50365. var yaxis = BoneLookController._tmpVecs[7];
  50366. var _tmpQuat = BoneLookController._tmpQuat;
  50367. target.subtractToRef(bonePos, zaxis);
  50368. zaxis.normalize();
  50369. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  50370. xaxis.normalize();
  50371. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  50372. yaxis.normalize();
  50373. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  50374. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  50375. return;
  50376. }
  50377. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  50378. return;
  50379. }
  50380. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  50381. return;
  50382. }
  50383. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  50384. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  50385. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  50386. }
  50387. if (this.slerpAmount < 1) {
  50388. if (!this._slerping) {
  50389. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  50390. }
  50391. if (this._transformYawPitch) {
  50392. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  50393. }
  50394. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  50395. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  50396. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  50397. this._slerping = true;
  50398. }
  50399. else {
  50400. if (this._transformYawPitch) {
  50401. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  50402. }
  50403. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  50404. this._slerping = false;
  50405. }
  50406. };
  50407. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  50408. var angDiff = ang2 - ang1;
  50409. angDiff %= Math.PI * 2;
  50410. if (angDiff > Math.PI) {
  50411. angDiff -= Math.PI * 2;
  50412. }
  50413. else if (angDiff < -Math.PI) {
  50414. angDiff += Math.PI * 2;
  50415. }
  50416. return angDiff;
  50417. };
  50418. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  50419. ang1 %= (2 * Math.PI);
  50420. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  50421. ang2 %= (2 * Math.PI);
  50422. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  50423. var ab = 0;
  50424. if (ang1 < ang2) {
  50425. ab = ang2 - ang1;
  50426. }
  50427. else {
  50428. ab = ang1 - ang2;
  50429. }
  50430. if (ab > Math.PI) {
  50431. ab = Math.PI * 2 - ab;
  50432. }
  50433. return ab;
  50434. };
  50435. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  50436. ang %= (2 * Math.PI);
  50437. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  50438. ang1 %= (2 * Math.PI);
  50439. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  50440. ang2 %= (2 * Math.PI);
  50441. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  50442. if (ang1 < ang2) {
  50443. if (ang > ang1 && ang < ang2) {
  50444. return true;
  50445. }
  50446. }
  50447. else {
  50448. if (ang > ang2 && ang < ang1) {
  50449. return true;
  50450. }
  50451. }
  50452. return false;
  50453. };
  50454. return BoneLookController;
  50455. }());
  50456. BoneLookController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  50457. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  50458. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  50459. BABYLON.BoneLookController = BoneLookController;
  50460. })(BABYLON || (BABYLON = {}));
  50461. //# sourceMappingURL=babylon.boneLookController.js.map
  50462. var BABYLON;
  50463. (function (BABYLON) {
  50464. var Skeleton = (function () {
  50465. function Skeleton(name, id, scene) {
  50466. this.name = name;
  50467. this.id = id;
  50468. this.bones = new Array();
  50469. this.needInitialSkinMatrix = false;
  50470. this._isDirty = true;
  50471. this._meshesWithPoseMatrix = new Array();
  50472. this._identity = BABYLON.Matrix.Identity();
  50473. this._ranges = {};
  50474. this._lastAbsoluteTransformsUpdateId = -1;
  50475. // Events
  50476. /**
  50477. * An event triggered before computing the skeleton's matrices
  50478. * @type {BABYLON.Observable}
  50479. */
  50480. this.onBeforeComputeObservable = new BABYLON.Observable();
  50481. this.bones = [];
  50482. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50483. scene.skeletons.push(this);
  50484. //make sure it will recalculate the matrix next time prepare is called.
  50485. this._isDirty = true;
  50486. }
  50487. // Members
  50488. Skeleton.prototype.getTransformMatrices = function (mesh) {
  50489. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  50490. return mesh._bonesTransformMatrices;
  50491. }
  50492. if (!this._transformMatrices) {
  50493. this.prepare();
  50494. }
  50495. return this._transformMatrices;
  50496. };
  50497. Skeleton.prototype.getScene = function () {
  50498. return this._scene;
  50499. };
  50500. // Methods
  50501. /**
  50502. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  50503. */
  50504. Skeleton.prototype.toString = function (fullDetails) {
  50505. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  50506. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50507. if (fullDetails) {
  50508. ret += ", Ranges: {";
  50509. var first = true;
  50510. for (var name_1 in this._ranges) {
  50511. if (first) {
  50512. ret += ", ";
  50513. first = false;
  50514. }
  50515. ret += name_1;
  50516. }
  50517. ret += "}";
  50518. }
  50519. return ret;
  50520. };
  50521. /**
  50522. * Get bone's index searching by name
  50523. * @param {string} name is bone's name to search for
  50524. * @return {number} Indice of the bone. Returns -1 if not found
  50525. */
  50526. Skeleton.prototype.getBoneIndexByName = function (name) {
  50527. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  50528. if (this.bones[boneIndex].name === name) {
  50529. return boneIndex;
  50530. }
  50531. }
  50532. return -1;
  50533. };
  50534. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  50535. // check name not already in use
  50536. if (!this._ranges[name]) {
  50537. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  50538. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  50539. if (this.bones[i].animations[0]) {
  50540. this.bones[i].animations[0].createRange(name, from, to);
  50541. }
  50542. }
  50543. }
  50544. };
  50545. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  50546. if (deleteFrames === void 0) { deleteFrames = true; }
  50547. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  50548. if (this.bones[i].animations[0]) {
  50549. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  50550. }
  50551. }
  50552. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  50553. };
  50554. Skeleton.prototype.getAnimationRange = function (name) {
  50555. return this._ranges[name];
  50556. };
  50557. /**
  50558. * Returns as an Array, all AnimationRanges defined on this skeleton
  50559. */
  50560. Skeleton.prototype.getAnimationRanges = function () {
  50561. var animationRanges = [];
  50562. var name;
  50563. var i = 0;
  50564. for (name in this._ranges) {
  50565. animationRanges[i] = this._ranges[name];
  50566. i++;
  50567. }
  50568. return animationRanges;
  50569. };
  50570. /**
  50571. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  50572. */
  50573. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  50574. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  50575. if (this._ranges[name] || !source.getAnimationRange(name)) {
  50576. return false;
  50577. }
  50578. var ret = true;
  50579. var frameOffset = this._getHighestAnimationFrame() + 1;
  50580. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  50581. var boneDict = {};
  50582. var sourceBones = source.bones;
  50583. var nBones;
  50584. var i;
  50585. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  50586. boneDict[sourceBones[i].name] = sourceBones[i];
  50587. }
  50588. if (this.bones.length !== sourceBones.length) {
  50589. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  50590. ret = false;
  50591. }
  50592. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  50593. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  50594. var boneName = this.bones[i].name;
  50595. var sourceBone = boneDict[boneName];
  50596. if (sourceBone) {
  50597. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  50598. }
  50599. else {
  50600. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  50601. ret = false;
  50602. }
  50603. }
  50604. // do not call createAnimationRange(), since it also is done to bones, which was already done
  50605. var range = source.getAnimationRange(name);
  50606. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  50607. return ret;
  50608. };
  50609. Skeleton.prototype.returnToRest = function () {
  50610. for (var index = 0; index < this.bones.length; index++) {
  50611. this.bones[index].returnToRest();
  50612. }
  50613. };
  50614. Skeleton.prototype._getHighestAnimationFrame = function () {
  50615. var ret = 0;
  50616. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  50617. if (this.bones[i].animations[0]) {
  50618. var highest = this.bones[i].animations[0].getHighestFrame();
  50619. if (ret < highest) {
  50620. ret = highest;
  50621. }
  50622. }
  50623. }
  50624. return ret;
  50625. };
  50626. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  50627. var range = this.getAnimationRange(name);
  50628. if (!range) {
  50629. return null;
  50630. }
  50631. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  50632. };
  50633. Skeleton.prototype._markAsDirty = function () {
  50634. this._isDirty = true;
  50635. };
  50636. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  50637. this._meshesWithPoseMatrix.push(mesh);
  50638. };
  50639. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  50640. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  50641. if (index > -1) {
  50642. this._meshesWithPoseMatrix.splice(index, 1);
  50643. }
  50644. };
  50645. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  50646. this.onBeforeComputeObservable.notifyObservers(this);
  50647. for (var index = 0; index < this.bones.length; index++) {
  50648. var bone = this.bones[index];
  50649. var parentBone = bone.getParent();
  50650. if (parentBone) {
  50651. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  50652. }
  50653. else {
  50654. if (initialSkinMatrix) {
  50655. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  50656. }
  50657. else {
  50658. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  50659. }
  50660. }
  50661. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  50662. }
  50663. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  50664. };
  50665. Skeleton.prototype.prepare = function () {
  50666. if (!this._isDirty) {
  50667. return;
  50668. }
  50669. if (this.needInitialSkinMatrix) {
  50670. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  50671. var mesh = this._meshesWithPoseMatrix[index];
  50672. var poseMatrix = mesh.getPoseMatrix();
  50673. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  50674. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  50675. }
  50676. if (this._synchronizedWithMesh !== mesh) {
  50677. this._synchronizedWithMesh = mesh;
  50678. // Prepare bones
  50679. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  50680. var bone = this.bones[boneIndex];
  50681. if (!bone.getParent()) {
  50682. var matrix = bone.getBaseMatrix();
  50683. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  50684. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  50685. }
  50686. }
  50687. }
  50688. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  50689. }
  50690. }
  50691. else {
  50692. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  50693. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  50694. }
  50695. this._computeTransformMatrices(this._transformMatrices, null);
  50696. }
  50697. this._isDirty = false;
  50698. this._scene._activeBones.addCount(this.bones.length, false);
  50699. };
  50700. Skeleton.prototype.getAnimatables = function () {
  50701. if (!this._animatables || this._animatables.length !== this.bones.length) {
  50702. this._animatables = [];
  50703. for (var index = 0; index < this.bones.length; index++) {
  50704. this._animatables.push(this.bones[index]);
  50705. }
  50706. }
  50707. return this._animatables;
  50708. };
  50709. Skeleton.prototype.clone = function (name, id) {
  50710. var result = new Skeleton(name, id || name, this._scene);
  50711. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  50712. for (var index = 0; index < this.bones.length; index++) {
  50713. var source = this.bones[index];
  50714. var parentBone = null;
  50715. if (source.getParent()) {
  50716. var parentIndex = this.bones.indexOf(source.getParent());
  50717. parentBone = result.bones[parentIndex];
  50718. }
  50719. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  50720. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  50721. }
  50722. if (this._ranges) {
  50723. result._ranges = {};
  50724. for (var rangeName in this._ranges) {
  50725. result._ranges[rangeName] = this._ranges[rangeName].clone();
  50726. }
  50727. }
  50728. this._isDirty = true;
  50729. return result;
  50730. };
  50731. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  50732. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  50733. this.bones.forEach(function (bone) {
  50734. bone.animations.forEach(function (animation) {
  50735. animation.enableBlending = true;
  50736. animation.blendingSpeed = blendingSpeed;
  50737. });
  50738. });
  50739. };
  50740. Skeleton.prototype.dispose = function () {
  50741. this._meshesWithPoseMatrix = [];
  50742. // Animations
  50743. this.getScene().stopAnimation(this);
  50744. // Remove from scene
  50745. this.getScene().removeSkeleton(this);
  50746. };
  50747. Skeleton.prototype.serialize = function () {
  50748. var serializationObject = {};
  50749. serializationObject.name = this.name;
  50750. serializationObject.id = this.id;
  50751. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  50752. serializationObject.bones = [];
  50753. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  50754. for (var index = 0; index < this.bones.length; index++) {
  50755. var bone = this.bones[index];
  50756. var serializedBone = {
  50757. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  50758. name: bone.name,
  50759. matrix: bone.getBaseMatrix().toArray(),
  50760. rest: bone.getRestPose().toArray()
  50761. };
  50762. serializationObject.bones.push(serializedBone);
  50763. if (bone.length) {
  50764. serializedBone.length = bone.length;
  50765. }
  50766. if (bone.animations && bone.animations.length > 0) {
  50767. serializedBone.animation = bone.animations[0].serialize();
  50768. }
  50769. serializationObject.ranges = [];
  50770. for (var name in this._ranges) {
  50771. var range = {};
  50772. range.name = name;
  50773. range.from = this._ranges[name].from;
  50774. range.to = this._ranges[name].to;
  50775. serializationObject.ranges.push(range);
  50776. }
  50777. }
  50778. return serializationObject;
  50779. };
  50780. Skeleton.Parse = function (parsedSkeleton, scene) {
  50781. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  50782. if (parsedSkeleton.dimensionsAtRest) {
  50783. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  50784. }
  50785. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  50786. var index;
  50787. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  50788. var parsedBone = parsedSkeleton.bones[index];
  50789. var parentBone = null;
  50790. if (parsedBone.parentBoneIndex > -1) {
  50791. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  50792. }
  50793. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  50794. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  50795. if (parsedBone.length) {
  50796. bone.length = parsedBone.length;
  50797. }
  50798. if (parsedBone.animation) {
  50799. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  50800. }
  50801. }
  50802. // placed after bones, so createAnimationRange can cascade down
  50803. if (parsedSkeleton.ranges) {
  50804. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  50805. var data = parsedSkeleton.ranges[index];
  50806. skeleton.createAnimationRange(data.name, data.from, data.to);
  50807. }
  50808. }
  50809. return skeleton;
  50810. };
  50811. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  50812. if (forceUpdate === void 0) { forceUpdate = false; }
  50813. var renderId = this._scene.getRenderId();
  50814. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  50815. this.bones[0].computeAbsoluteTransforms();
  50816. this._lastAbsoluteTransformsUpdateId = renderId;
  50817. }
  50818. };
  50819. Skeleton.prototype.getPoseMatrix = function () {
  50820. var poseMatrix;
  50821. if (this._meshesWithPoseMatrix.length > 0) {
  50822. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  50823. }
  50824. return poseMatrix;
  50825. };
  50826. return Skeleton;
  50827. }());
  50828. BABYLON.Skeleton = Skeleton;
  50829. })(BABYLON || (BABYLON = {}));
  50830. //# sourceMappingURL=babylon.skeleton.js.map
  50831. var BABYLON;
  50832. (function (BABYLON) {
  50833. var Internals;
  50834. (function (Internals) {
  50835. var FileFaceOrientation = (function () {
  50836. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  50837. this.name = name;
  50838. this.worldAxisForNormal = worldAxisForNormal;
  50839. this.worldAxisForFileX = worldAxisForFileX;
  50840. this.worldAxisForFileY = worldAxisForFileY;
  50841. }
  50842. return FileFaceOrientation;
  50843. }());
  50844. ;
  50845. /**
  50846. * Helper class dealing with the extraction of spherical polynomial dataArray
  50847. * from a cube map.
  50848. */
  50849. var CubeMapToSphericalPolynomialTools = (function () {
  50850. function CubeMapToSphericalPolynomialTools() {
  50851. }
  50852. /**
  50853. * Converts a cubemap to the according Spherical Polynomial data.
  50854. * This extracts the first 3 orders only as they are the only one used in the lighting.
  50855. *
  50856. * @param cubeInfo The Cube map to extract the information from.
  50857. * @return The Spherical Polynomial data.
  50858. */
  50859. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  50860. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  50861. var totalSolidAngle = 0.0;
  50862. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  50863. var du = 2.0 / cubeInfo.size;
  50864. var dv = du;
  50865. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  50866. var minUV = du * 0.5 - 1.0;
  50867. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50868. var fileFace = this.FileFaces[faceIndex];
  50869. var dataArray = cubeInfo[fileFace.name];
  50870. var v = minUV;
  50871. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  50872. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  50873. // Because SP is still linear, so summation is fine in that basis.
  50874. for (var y = 0; y < cubeInfo.size; y++) {
  50875. var u = minUV;
  50876. for (var x = 0; x < cubeInfo.size; x++) {
  50877. // World direction (not normalised)
  50878. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  50879. worldDirection.normalize();
  50880. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  50881. if (1) {
  50882. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  50883. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  50884. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  50885. var color = new BABYLON.Color3(r, g, b);
  50886. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  50887. }
  50888. else {
  50889. if (faceIndex == 0) {
  50890. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50891. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50892. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50893. }
  50894. else if (faceIndex == 1) {
  50895. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50896. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50897. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50898. }
  50899. else if (faceIndex == 2) {
  50900. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50901. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50902. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50903. }
  50904. else if (faceIndex == 3) {
  50905. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50906. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50907. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50908. }
  50909. else if (faceIndex == 4) {
  50910. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50911. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50912. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50913. }
  50914. else if (faceIndex == 5) {
  50915. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50916. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50917. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50918. }
  50919. 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]);
  50920. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  50921. }
  50922. totalSolidAngle += deltaSolidAngle;
  50923. u += du;
  50924. }
  50925. v += dv;
  50926. }
  50927. }
  50928. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  50929. var correction = correctSolidAngle / totalSolidAngle;
  50930. sphericalHarmonics.scale(correction);
  50931. // Additionally scale by pi -- audit needed
  50932. sphericalHarmonics.scale(1.0 / Math.PI);
  50933. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  50934. };
  50935. return CubeMapToSphericalPolynomialTools;
  50936. }());
  50937. CubeMapToSphericalPolynomialTools.FileFaces = [
  50938. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  50939. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  50940. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  50941. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  50942. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  50943. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  50944. ];
  50945. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  50946. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50947. })(BABYLON || (BABYLON = {}));
  50948. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  50949. var BABYLON;
  50950. (function (BABYLON) {
  50951. var Internals;
  50952. (function (Internals) {
  50953. /**
  50954. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  50955. */
  50956. var PanoramaToCubeMapTools = (function () {
  50957. function PanoramaToCubeMapTools() {
  50958. }
  50959. /**
  50960. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  50961. *
  50962. * @param float32Array The source data.
  50963. * @param inputWidth The width of the input panorama.
  50964. * @param inputhHeight The height of the input panorama.
  50965. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  50966. * @return The cubemap data
  50967. */
  50968. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  50969. if (!float32Array) {
  50970. throw "ConvertPanoramaToCubemap: input cannot be null";
  50971. }
  50972. if (float32Array.length != inputWidth * inputHeight * 3) {
  50973. throw "ConvertPanoramaToCubemap: input size is wrong";
  50974. }
  50975. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  50976. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  50977. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  50978. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  50979. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  50980. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  50981. return {
  50982. front: textureFront,
  50983. back: textureBack,
  50984. left: textureLeft,
  50985. right: textureRight,
  50986. up: textureUp,
  50987. down: textureDown,
  50988. size: size
  50989. };
  50990. };
  50991. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  50992. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  50993. var textureArray = new Float32Array(buffer);
  50994. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  50995. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  50996. var dy = 1 / texSize;
  50997. var fy = 0;
  50998. for (var y = 0; y < texSize; y++) {
  50999. var xv1 = faceData[0];
  51000. var xv2 = faceData[2];
  51001. for (var x = 0; x < texSize; x++) {
  51002. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  51003. v.normalize();
  51004. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  51005. // 3 channels per pixels
  51006. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  51007. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  51008. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  51009. xv1 = xv1.add(rotDX1);
  51010. xv2 = xv2.add(rotDX2);
  51011. }
  51012. fy += dy;
  51013. }
  51014. return textureArray;
  51015. };
  51016. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  51017. var theta = Math.atan2(vDir.z, vDir.x);
  51018. var phi = Math.acos(vDir.y);
  51019. while (theta < -Math.PI)
  51020. theta += 2 * Math.PI;
  51021. while (theta > Math.PI)
  51022. theta -= 2 * Math.PI;
  51023. var dx = theta / Math.PI;
  51024. var dy = phi / Math.PI;
  51025. // recenter.
  51026. dx = dx * 0.5 + 0.5;
  51027. var px = Math.round(dx * inputWidth);
  51028. if (px < 0)
  51029. px = 0;
  51030. else if (px >= inputWidth)
  51031. px = inputWidth - 1;
  51032. var py = Math.round(dy * inputHeight);
  51033. if (py < 0)
  51034. py = 0;
  51035. else if (py >= inputHeight)
  51036. py = inputHeight - 1;
  51037. var inputY = (inputHeight - py - 1);
  51038. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  51039. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  51040. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  51041. return {
  51042. r: r,
  51043. g: g,
  51044. b: b
  51045. };
  51046. };
  51047. return PanoramaToCubeMapTools;
  51048. }());
  51049. PanoramaToCubeMapTools.FACE_FRONT = [
  51050. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  51051. new BABYLON.Vector3(1.0, -1.0, -1.0),
  51052. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  51053. new BABYLON.Vector3(1.0, 1.0, -1.0)
  51054. ];
  51055. PanoramaToCubeMapTools.FACE_BACK = [
  51056. new BABYLON.Vector3(1.0, -1.0, 1.0),
  51057. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  51058. new BABYLON.Vector3(1.0, 1.0, 1.0),
  51059. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  51060. ];
  51061. PanoramaToCubeMapTools.FACE_RIGHT = [
  51062. new BABYLON.Vector3(1.0, -1.0, -1.0),
  51063. new BABYLON.Vector3(1.0, -1.0, 1.0),
  51064. new BABYLON.Vector3(1.0, 1.0, -1.0),
  51065. new BABYLON.Vector3(1.0, 1.0, 1.0)
  51066. ];
  51067. PanoramaToCubeMapTools.FACE_LEFT = [
  51068. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  51069. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  51070. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  51071. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  51072. ];
  51073. PanoramaToCubeMapTools.FACE_DOWN = [
  51074. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  51075. new BABYLON.Vector3(1.0, 1.0, -1.0),
  51076. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  51077. new BABYLON.Vector3(1.0, 1.0, 1.0)
  51078. ];
  51079. PanoramaToCubeMapTools.FACE_UP = [
  51080. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  51081. new BABYLON.Vector3(1.0, -1.0, 1.0),
  51082. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  51083. new BABYLON.Vector3(1.0, -1.0, -1.0)
  51084. ];
  51085. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  51086. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51087. })(BABYLON || (BABYLON = {}));
  51088. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  51089. var BABYLON;
  51090. (function (BABYLON) {
  51091. var Internals;
  51092. (function (Internals) {
  51093. ;
  51094. /**
  51095. * This groups tools to convert HDR texture to native colors array.
  51096. */
  51097. var HDRTools = (function () {
  51098. function HDRTools() {
  51099. }
  51100. HDRTools.Ldexp = function (mantissa, exponent) {
  51101. if (exponent > 1023) {
  51102. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  51103. }
  51104. if (exponent < -1074) {
  51105. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  51106. }
  51107. return mantissa * Math.pow(2, exponent);
  51108. };
  51109. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  51110. if (exponent > 0) {
  51111. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  51112. float32array[index + 0] = red * exponent;
  51113. float32array[index + 1] = green * exponent;
  51114. float32array[index + 2] = blue * exponent;
  51115. }
  51116. else {
  51117. float32array[index + 0] = 0;
  51118. float32array[index + 1] = 0;
  51119. float32array[index + 2] = 0;
  51120. }
  51121. };
  51122. HDRTools.readStringLine = function (uint8array, startIndex) {
  51123. var line = "";
  51124. var character = "";
  51125. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  51126. character = String.fromCharCode(uint8array[i]);
  51127. if (character == "\n") {
  51128. break;
  51129. }
  51130. line += character;
  51131. }
  51132. return line;
  51133. };
  51134. /**
  51135. * Reads header information from an RGBE texture stored in a native array.
  51136. * More information on this format are available here:
  51137. * https://en.wikipedia.org/wiki/RGBE_image_format
  51138. *
  51139. * @param uint8array The binary file stored in native array.
  51140. * @return The header information.
  51141. */
  51142. HDRTools.RGBE_ReadHeader = function (uint8array) {
  51143. var height = 0;
  51144. var width = 0;
  51145. var line = this.readStringLine(uint8array, 0);
  51146. if (line[0] != '#' || line[1] != '?') {
  51147. throw "Bad HDR Format.";
  51148. }
  51149. var endOfHeader = false;
  51150. var findFormat = false;
  51151. var lineIndex = 0;
  51152. do {
  51153. lineIndex += (line.length + 1);
  51154. line = this.readStringLine(uint8array, lineIndex);
  51155. if (line == "FORMAT=32-bit_rle_rgbe") {
  51156. findFormat = true;
  51157. }
  51158. else if (line.length == 0) {
  51159. endOfHeader = true;
  51160. }
  51161. } while (!endOfHeader);
  51162. if (!findFormat) {
  51163. throw "HDR Bad header format, unsupported FORMAT";
  51164. }
  51165. lineIndex += (line.length + 1);
  51166. line = this.readStringLine(uint8array, lineIndex);
  51167. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  51168. var match = sizeRegexp.exec(line);
  51169. // TODO. Support +Y and -X if needed.
  51170. if (match.length < 3) {
  51171. throw "HDR Bad header format, no size";
  51172. }
  51173. width = parseInt(match[2]);
  51174. height = parseInt(match[1]);
  51175. if (width < 8 || width > 0x7fff) {
  51176. throw "HDR Bad header format, unsupported size";
  51177. }
  51178. lineIndex += (line.length + 1);
  51179. return {
  51180. height: height,
  51181. width: width,
  51182. dataPosition: lineIndex
  51183. };
  51184. };
  51185. /**
  51186. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  51187. * This RGBE texture needs to store the information as a panorama.
  51188. *
  51189. * More information on this format are available here:
  51190. * https://en.wikipedia.org/wiki/RGBE_image_format
  51191. *
  51192. * @param buffer The binary file stored in an array buffer.
  51193. * @param size The expected size of the extracted cubemap.
  51194. * @return The Cube Map information.
  51195. */
  51196. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  51197. var uint8array = new Uint8Array(buffer);
  51198. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  51199. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  51200. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  51201. return cubeMapData;
  51202. };
  51203. /**
  51204. * Returns the pixels data extracted from an RGBE texture.
  51205. * This pixels will be stored left to right up to down in the R G B order in one array.
  51206. *
  51207. * More information on this format are available here:
  51208. * https://en.wikipedia.org/wiki/RGBE_image_format
  51209. *
  51210. * @param uint8array The binary file stored in an array buffer.
  51211. * @param hdrInfo The header information of the file.
  51212. * @return The pixels data in RGB right to left up to down order.
  51213. */
  51214. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  51215. // Keep for multi format supports.
  51216. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  51217. };
  51218. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  51219. var num_scanlines = hdrInfo.height;
  51220. var scanline_width = hdrInfo.width;
  51221. var a, b, c, d, count;
  51222. var dataIndex = hdrInfo.dataPosition;
  51223. var index = 0, endIndex = 0, i = 0;
  51224. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  51225. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  51226. // 3 channels of 4 bytes per pixel in float.
  51227. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  51228. var resultArray = new Float32Array(resultBuffer);
  51229. // read in each successive scanline
  51230. while (num_scanlines > 0) {
  51231. a = uint8array[dataIndex++];
  51232. b = uint8array[dataIndex++];
  51233. c = uint8array[dataIndex++];
  51234. d = uint8array[dataIndex++];
  51235. if (a != 2 || b != 2 || (c & 0x80)) {
  51236. // this file is not run length encoded
  51237. throw "HDR Bad header format, not RLE";
  51238. }
  51239. if (((c << 8) | d) != scanline_width) {
  51240. throw "HDR Bad header format, wrong scan line width";
  51241. }
  51242. index = 0;
  51243. // read each of the four channels for the scanline into the buffer
  51244. for (i = 0; i < 4; i++) {
  51245. endIndex = (i + 1) * scanline_width;
  51246. while (index < endIndex) {
  51247. a = uint8array[dataIndex++];
  51248. b = uint8array[dataIndex++];
  51249. if (a > 128) {
  51250. // a run of the same value
  51251. count = a - 128;
  51252. if ((count == 0) || (count > endIndex - index)) {
  51253. throw "HDR Bad Format, bad scanline data (run)";
  51254. }
  51255. while (count-- > 0) {
  51256. scanLineArray[index++] = b;
  51257. }
  51258. }
  51259. else {
  51260. // a non-run
  51261. count = a;
  51262. if ((count == 0) || (count > endIndex - index)) {
  51263. throw "HDR Bad Format, bad scanline data (non-run)";
  51264. }
  51265. scanLineArray[index++] = b;
  51266. if (--count > 0) {
  51267. for (var j = 0; j < count; j++) {
  51268. scanLineArray[index++] = uint8array[dataIndex++];
  51269. }
  51270. }
  51271. }
  51272. }
  51273. }
  51274. // now convert data from buffer into floats
  51275. for (i = 0; i < scanline_width; i++) {
  51276. a = scanLineArray[i];
  51277. b = scanLineArray[i + scanline_width];
  51278. c = scanLineArray[i + 2 * scanline_width];
  51279. d = scanLineArray[i + 3 * scanline_width];
  51280. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  51281. }
  51282. num_scanlines--;
  51283. }
  51284. return resultArray;
  51285. };
  51286. return HDRTools;
  51287. }());
  51288. Internals.HDRTools = HDRTools;
  51289. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51290. })(BABYLON || (BABYLON = {}));
  51291. //# sourceMappingURL=babylon.hdr.js.map
  51292. //_______________________________________________________________
  51293. // Extracted from CubeMapGen:
  51294. // https://code.google.com/archive/p/cubemapgen/
  51295. //
  51296. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  51297. //_______________________________________________________________
  51298. var BABYLON;
  51299. (function (BABYLON) {
  51300. var Internals;
  51301. (function (Internals) {
  51302. /**
  51303. * The bounding box information used during the conversion process.
  51304. */
  51305. var CMGBoundinBox = (function () {
  51306. function CMGBoundinBox() {
  51307. this.min = new BABYLON.Vector3(0, 0, 0);
  51308. this.max = new BABYLON.Vector3(0, 0, 0);
  51309. this.clear();
  51310. }
  51311. CMGBoundinBox.prototype.clear = function () {
  51312. this.min.x = CMGBoundinBox.MAX;
  51313. this.min.y = CMGBoundinBox.MAX;
  51314. this.min.z = CMGBoundinBox.MAX;
  51315. this.max.x = CMGBoundinBox.MIN;
  51316. this.max.y = CMGBoundinBox.MIN;
  51317. this.max.z = CMGBoundinBox.MIN;
  51318. };
  51319. CMGBoundinBox.prototype.augment = function (x, y, z) {
  51320. this.min.x = Math.min(this.min.x, x);
  51321. this.min.y = Math.min(this.min.y, y);
  51322. this.min.z = Math.min(this.min.z, z);
  51323. this.max.x = Math.max(this.max.x, x);
  51324. this.max.y = Math.max(this.max.y, y);
  51325. this.max.z = Math.max(this.max.z, z);
  51326. };
  51327. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  51328. this.min.x = Math.max(this.min.x, x);
  51329. this.min.y = Math.max(this.min.y, y);
  51330. this.min.z = Math.max(this.min.z, z);
  51331. };
  51332. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  51333. this.max.x = Math.min(this.max.x, x);
  51334. this.max.y = Math.min(this.max.y, y);
  51335. this.max.z = Math.min(this.max.z, z);
  51336. };
  51337. CMGBoundinBox.prototype.empty = function () {
  51338. if ((this.min.x > this.max.y) ||
  51339. (this.min.y > this.max.y) ||
  51340. (this.min.z > this.max.y)) {
  51341. return true;
  51342. }
  51343. else {
  51344. return false;
  51345. }
  51346. };
  51347. return CMGBoundinBox;
  51348. }());
  51349. CMGBoundinBox.MAX = Number.MAX_VALUE;
  51350. CMGBoundinBox.MIN = Number.MIN_VALUE;
  51351. /**
  51352. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  51353. * required by the glossinees of a material.
  51354. *
  51355. * This only supports the cosine drop power as well as Warp fixup generation method.
  51356. *
  51357. * This is using the process from CubeMapGen described here:
  51358. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  51359. */
  51360. var PMREMGenerator = (function () {
  51361. /**
  51362. * Constructor of the generator.
  51363. *
  51364. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  51365. * @param inputSize The size of the cubemap faces
  51366. * @param outputSize The size of the output cubemap faces
  51367. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  51368. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  51369. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  51370. * @param specularPower The max specular level of the desired cubemap
  51371. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  51372. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  51373. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  51374. */
  51375. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  51376. this.input = input;
  51377. this.inputSize = inputSize;
  51378. this.outputSize = outputSize;
  51379. this.maxNumMipLevels = maxNumMipLevels;
  51380. this.numChannels = numChannels;
  51381. this.isFloat = isFloat;
  51382. this.specularPower = specularPower;
  51383. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  51384. this.excludeBase = excludeBase;
  51385. this.fixup = fixup;
  51386. this._outputSurface = [];
  51387. this._numMipLevels = 0;
  51388. }
  51389. /**
  51390. * Launches the filter process and return the result.
  51391. *
  51392. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  51393. */
  51394. PMREMGenerator.prototype.filterCubeMap = function () {
  51395. // Init cubemap processor
  51396. this.init();
  51397. // Filters the cubemap
  51398. this.filterCubeMapMipChain();
  51399. // Returns the filtered mips.
  51400. return this._outputSurface;
  51401. };
  51402. PMREMGenerator.prototype.init = function () {
  51403. var i;
  51404. var j;
  51405. var mipLevelSize;
  51406. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  51407. if (this.maxNumMipLevels == 0) {
  51408. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  51409. }
  51410. //first miplevel size
  51411. mipLevelSize = this.outputSize;
  51412. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  51413. for (j = 0; j < this.maxNumMipLevels; j++) {
  51414. this._outputSurface.length++;
  51415. this._outputSurface[j] = [];
  51416. //Iterate over faces for output images
  51417. for (i = 0; i < 6; i++) {
  51418. this._outputSurface[j].length++;
  51419. // Initializes a new array for the output.
  51420. if (this.isFloat) {
  51421. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  51422. }
  51423. else {
  51424. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  51425. }
  51426. }
  51427. //next mip level is half size
  51428. mipLevelSize >>= 1;
  51429. this._numMipLevels++;
  51430. //terminate if mip chain becomes too small
  51431. if (mipLevelSize == 0) {
  51432. this.maxNumMipLevels = j;
  51433. return;
  51434. }
  51435. }
  51436. };
  51437. //--------------------------------------------------------------------------------------
  51438. //Cube map filtering and mip chain generation.
  51439. // the cube map filtereing is specified using a number of parameters:
  51440. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  51441. // indicates the region of the hemisphere to filter over for each tap.
  51442. //
  51443. // Note that the top mip level is also a filtered version of the original input images
  51444. // as well in order to create mip chains for diffuse environment illumination.
  51445. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  51446. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  51447. //
  51448. // Then the mip angle used to genreate the next level of the mip chain from the first level
  51449. // is a_InitialMipAngle
  51450. //
  51451. // The angle for the subsequent levels of the mip chain are specified by their parents
  51452. // filtering angle and a per-level scale and bias
  51453. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  51454. //
  51455. //--------------------------------------------------------------------------------------
  51456. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  51457. // First, take count of the lighting model to modify SpecularPower
  51458. // 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;
  51459. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  51460. //Cone angle start (for generating subsequent mip levels)
  51461. var currentSpecularPower = this.specularPower;
  51462. //Build filter lookup tables based on the source miplevel size
  51463. this.precomputeFilterLookupTables(this.inputSize);
  51464. // Note that we need to filter the first level before generating mipmap
  51465. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  51466. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  51467. // TODO : Write a function to copy and scale the base mipmap in output
  51468. // I am just lazy here and just put a high specular power value, and do some if.
  51469. if (this.excludeBase && (levelIndex == 0)) {
  51470. // 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).
  51471. currentSpecularPower = 100000.0;
  51472. }
  51473. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  51474. var srcCubeImage = this.input;
  51475. var dstCubeImage = this._outputSurface[levelIndex];
  51476. var dstSize = this.outputSize >> levelIndex;
  51477. // Compute required angle.
  51478. var angle = this.getBaseFilterAngle(currentSpecularPower);
  51479. // filter cube surfaces
  51480. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  51481. // fix seams
  51482. if (this.fixup) {
  51483. this.fixupCubeEdges(dstCubeImage, dstSize);
  51484. }
  51485. // Decrease the specular power to generate the mipmap chain
  51486. // TODO : Use another method for Exclude (see first comment at start of the function
  51487. if (this.excludeBase && (levelIndex == 0)) {
  51488. currentSpecularPower = this.specularPower;
  51489. }
  51490. currentSpecularPower *= this.cosinePowerDropPerMip;
  51491. }
  51492. };
  51493. //--------------------------------------------------------------------------------------
  51494. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  51495. // It allow to optimize the texel to access base on the specular power.
  51496. //--------------------------------------------------------------------------------------
  51497. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  51498. // We want to find the alpha such that:
  51499. // cos(alpha)^cosinePower = epsilon
  51500. // That's: acos(epsilon^(1/cosinePower))
  51501. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  51502. var angle = 180.0;
  51503. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  51504. angle *= 180.0 / Math.PI; // Convert to degree
  51505. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  51506. return angle;
  51507. };
  51508. //--------------------------------------------------------------------------------------
  51509. //Builds the following lookup tables prior to filtering:
  51510. // -normalizer cube map
  51511. // -tap weight lookup table
  51512. //
  51513. //--------------------------------------------------------------------------------------
  51514. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  51515. var srcTexelAngle;
  51516. var iCubeFace;
  51517. //clear pre-existing normalizer cube map
  51518. this._normCubeMap = [];
  51519. //Normalized vectors per cubeface and per-texel solid angle
  51520. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  51521. };
  51522. //--------------------------------------------------------------------------------------
  51523. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  51524. //
  51525. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  51526. //
  51527. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  51528. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  51529. // below
  51530. //--------------------------------------------------------------------------------------
  51531. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  51532. var iCubeFace;
  51533. var u;
  51534. var v;
  51535. //iterate over cube faces
  51536. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51537. //First three channels for norm cube, and last channel for solid angle
  51538. this._normCubeMap.push(new Float32Array(size * size * 4));
  51539. //fast texture walk, build normalizer cube map
  51540. var facesData = this.input[iCubeFace];
  51541. for (v = 0; v < size; v++) {
  51542. for (u = 0; u < size; u++) {
  51543. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  51544. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  51545. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  51546. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  51547. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  51548. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  51549. }
  51550. }
  51551. }
  51552. };
  51553. //--------------------------------------------------------------------------------------
  51554. // Convert cubemap face texel coordinates and face idx to 3D vector
  51555. // note the U and V coords are integer coords and range from 0 to size-1
  51556. // this routine can be used to generate a normalizer cube map
  51557. //--------------------------------------------------------------------------------------
  51558. // SL BEGIN
  51559. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  51560. var nvcU;
  51561. var nvcV;
  51562. var tempVec;
  51563. // Change from original AMD code
  51564. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  51565. // + 0.5f is for texel center addressing
  51566. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  51567. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  51568. // warp fixup
  51569. if (fixup && size > 1) {
  51570. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  51571. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  51572. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  51573. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  51574. }
  51575. // Get current vector
  51576. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  51577. // U contribution
  51578. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  51579. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  51580. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  51581. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  51582. // V contribution and Sum
  51583. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  51584. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  51585. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  51586. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  51587. //add face axis
  51588. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  51589. PMREMGenerator._vectorTemp.x += faceAxis[0];
  51590. PMREMGenerator._vectorTemp.y += faceAxis[1];
  51591. PMREMGenerator._vectorTemp.z += faceAxis[2];
  51592. //normalize vector
  51593. PMREMGenerator._vectorTemp.normalize();
  51594. return PMREMGenerator._vectorTemp;
  51595. };
  51596. //--------------------------------------------------------------------------------------
  51597. // Convert 3D vector to cubemap face texel coordinates and face idx
  51598. // note the U and V coords are integer coords and range from 0 to size-1
  51599. // this routine can be used to generate a normalizer cube map
  51600. //
  51601. // returns face IDX and texel coords
  51602. //--------------------------------------------------------------------------------------
  51603. // SL BEGIN
  51604. /*
  51605. Mapping Texture Coordinates to Cube Map Faces
  51606. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  51607. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  51608. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  51609. map arrangement in Pixar's RenderMan package.
  51610. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  51611. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  51612. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  51613. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  51614. the major axis direction). The target column in the table below explains how the major axis direction
  51615. maps to the 2D image of a particular cube map target.
  51616. major axis
  51617. direction target sc tc ma
  51618. ---------- --------------------------------- --- --- ---
  51619. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  51620. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  51621. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  51622. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  51623. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  51624. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  51625. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  51626. an updated (s,t) is calculated as follows
  51627. s = ( sc/|ma| + 1 ) / 2
  51628. t = ( tc/|ma| + 1 ) / 2
  51629. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  51630. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  51631. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  51632. */
  51633. // Note this method return U and V in range from 0 to size-1
  51634. // SL END
  51635. // Store the information in vector3 for convenience (faceindex, u, v)
  51636. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  51637. var maxCoord;
  51638. var faceIdx;
  51639. //absolute value 3
  51640. var absX = Math.abs(x);
  51641. var absY = Math.abs(y);
  51642. var absZ = Math.abs(z);
  51643. if (absX >= absY && absX >= absZ) {
  51644. maxCoord = absX;
  51645. if (x >= 0) {
  51646. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  51647. }
  51648. else {
  51649. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  51650. }
  51651. }
  51652. else if (absY >= absX && absY >= absZ) {
  51653. maxCoord = absY;
  51654. if (y >= 0) {
  51655. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  51656. }
  51657. else {
  51658. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  51659. }
  51660. }
  51661. else {
  51662. maxCoord = absZ;
  51663. if (z >= 0) {
  51664. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  51665. }
  51666. else {
  51667. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  51668. }
  51669. }
  51670. //divide through by max coord so face vector lies on cube face
  51671. var scale = 1 / maxCoord;
  51672. x *= scale;
  51673. y *= scale;
  51674. z *= scale;
  51675. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  51676. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  51677. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  51678. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  51679. // Modify original AMD code to return value from 0 to Size - 1
  51680. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  51681. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  51682. PMREMGenerator._vectorTemp.x = faceIdx;
  51683. PMREMGenerator._vectorTemp.y = u;
  51684. PMREMGenerator._vectorTemp.z = v;
  51685. return PMREMGenerator._vectorTemp;
  51686. };
  51687. //--------------------------------------------------------------------------------------
  51688. //Original code from Ignacio CastaÒo
  51689. // This formula is from Manne ÷hrstrˆm's thesis.
  51690. // Take two coordiantes in the range [-1, 1] that define a portion of a
  51691. // cube face and return the area of the projection of that portion on the
  51692. // surface of the sphere.
  51693. //--------------------------------------------------------------------------------------
  51694. PMREMGenerator.prototype.areaElement = function (x, y) {
  51695. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  51696. };
  51697. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  51698. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  51699. // (+ 0.5f is for texel center addressing)
  51700. u = (2.0 * (u + 0.5) / size) - 1.0;
  51701. v = (2.0 * (v + 0.5) / size) - 1.0;
  51702. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  51703. var invResolution = 1.0 / size;
  51704. // U and V are the -1..1 texture coordinate on the current face.
  51705. // Get projected area for this texel
  51706. var x0 = u - invResolution;
  51707. var y0 = v - invResolution;
  51708. var x1 = u + invResolution;
  51709. var y1 = v + invResolution;
  51710. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  51711. return solidAngle;
  51712. };
  51713. //--------------------------------------------------------------------------------------
  51714. //The key to the speed of these filtering routines is to quickly define a per-face
  51715. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  51716. // Later these pixels are selectively processed based on their dot products to see if
  51717. // they reside within the filtering cone.
  51718. //
  51719. //This is done by computing the smallest per-texel angle to get a conservative estimate
  51720. // of the number of texels needed to be covered in width and height order to filter the
  51721. // region. the bounding box for the center taps face is defined first, and if the
  51722. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  51723. // defined next
  51724. //--------------------------------------------------------------------------------------
  51725. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  51726. // note that pixels within these regions may be rejected
  51727. // based on the anlge
  51728. var iCubeFace;
  51729. var u;
  51730. var v;
  51731. // bounding box per face to specify region to process
  51732. var filterExtents = [];
  51733. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51734. filterExtents.push(new CMGBoundinBox());
  51735. }
  51736. // min angle a src texel can cover (in degrees)
  51737. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  51738. // angle about center tap to define filter cone
  51739. // filter angle is 1/2 the cone angle
  51740. var filterAngle = filterConeAngle / 2.0;
  51741. //ensure filter angle is larger than a texel
  51742. if (filterAngle < srcTexelAngle) {
  51743. filterAngle = srcTexelAngle;
  51744. }
  51745. //ensure filter cone is always smaller than the hemisphere
  51746. if (filterAngle > 90.0) {
  51747. filterAngle = 90.0;
  51748. }
  51749. // the maximum number of texels in 1D the filter cone angle will cover
  51750. // used to determine bounding box size for filter extents
  51751. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  51752. // ensure conservative region always covers at least one texel
  51753. if (filterSize < 1) {
  51754. filterSize = 1;
  51755. }
  51756. // dotProdThresh threshold based on cone angle to determine whether or not taps
  51757. // reside within the cone angle
  51758. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  51759. // process required faces
  51760. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51761. //iterate over dst cube map face texel
  51762. for (v = 0; v < dstSize; v++) {
  51763. for (u = 0; u < dstSize; u++) {
  51764. //get center tap direction
  51765. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  51766. //clear old per-face filter extents
  51767. this.clearFilterExtents(filterExtents);
  51768. //define per-face filter extents
  51769. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  51770. //perform filtering of src faces using filter extents
  51771. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  51772. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  51773. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  51774. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  51775. }
  51776. }
  51777. }
  51778. };
  51779. //--------------------------------------------------------------------------------------
  51780. //Clear filter extents for the 6 cube map faces
  51781. //--------------------------------------------------------------------------------------
  51782. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  51783. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  51784. filterExtents[iCubeFaces].clear();
  51785. }
  51786. };
  51787. //--------------------------------------------------------------------------------------
  51788. //Define per-face bounding box filter extents
  51789. //
  51790. // These define conservative texel regions in each of the faces the filter can possibly
  51791. // process. When the pixels in the regions are actually processed, the dot product
  51792. // between the tap vector and the center tap vector is used to determine the weight of
  51793. // the tap and whether or not the tap is within the cone.
  51794. //
  51795. //--------------------------------------------------------------------------------------
  51796. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  51797. //neighboring face and bleed over amount, and width of BBOX for
  51798. // left, right, top, and bottom edges of this face
  51799. var bleedOverAmount = [0, 0, 0, 0];
  51800. var bleedOverBBoxMin = [0, 0, 0, 0];
  51801. var bleedOverBBoxMax = [0, 0, 0, 0];
  51802. var neighborFace;
  51803. var neighborEdge;
  51804. var oppositeFaceIdx;
  51805. //get face idx, and u, v info from center tap dir
  51806. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  51807. var faceIdx = result.x;
  51808. var u = result.y;
  51809. var v = result.z;
  51810. //define bbox size within face
  51811. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  51812. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  51813. filterExtents[faceIdx].clampMin(0, 0, 0);
  51814. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  51815. //u and v extent in face corresponding to center tap
  51816. var minU = filterExtents[faceIdx].min.x;
  51817. var minV = filterExtents[faceIdx].min.y;
  51818. var maxU = filterExtents[faceIdx].max.x;
  51819. var maxV = filterExtents[faceIdx].max.y;
  51820. //bleed over amounts for face across u=0 edge (left)
  51821. bleedOverAmount[0] = (bboxSize - u);
  51822. bleedOverBBoxMin[0] = minV;
  51823. bleedOverBBoxMax[0] = maxV;
  51824. //bleed over amounts for face across u=1 edge (right)
  51825. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  51826. bleedOverBBoxMin[1] = minV;
  51827. bleedOverBBoxMax[1] = maxV;
  51828. //bleed over to face across v=0 edge (up)
  51829. bleedOverAmount[2] = (bboxSize - v);
  51830. bleedOverBBoxMin[2] = minU;
  51831. bleedOverBBoxMax[2] = maxU;
  51832. //bleed over to face across v=1 edge (down)
  51833. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  51834. bleedOverBBoxMin[3] = minU;
  51835. bleedOverBBoxMax[3] = maxU;
  51836. //compute bleed over regions in neighboring faces
  51837. for (var i = 0; i < 4; i++) {
  51838. if (bleedOverAmount[i] > 0) {
  51839. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  51840. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  51841. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  51842. // be flipped: the cases are
  51843. // if a left edge mates with a left or bottom edge on the neighbor
  51844. // if a top edge mates with a top or right edge on the neighbor
  51845. // if a right edge mates with a right or top edge on the neighbor
  51846. // if a bottom edge mates with a bottom or left edge on the neighbor
  51847. //Seeing as the edges are enumerated as follows
  51848. // left =0
  51849. // right =1
  51850. // top =2
  51851. // bottom =3
  51852. //
  51853. // so if the edge enums are the same, or the sum of the enums == 3,
  51854. // the bbox needs to be flipped
  51855. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  51856. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  51857. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  51858. }
  51859. //The way the bounding box is extended onto the neighboring face
  51860. // depends on which edge of neighboring face abuts with this one
  51861. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  51862. case PMREMGenerator.CP_EDGE_LEFT:
  51863. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  51864. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51865. break;
  51866. case PMREMGenerator.CP_EDGE_RIGHT:
  51867. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  51868. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51869. break;
  51870. case PMREMGenerator.CP_EDGE_TOP:
  51871. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  51872. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  51873. break;
  51874. case PMREMGenerator.CP_EDGE_BOTTOM:
  51875. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  51876. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  51877. break;
  51878. }
  51879. //clamp filter extents in non-center tap faces to remain within surface
  51880. filterExtents[neighborFace].clampMin(0, 0, 0);
  51881. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  51882. }
  51883. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  51884. // from the center tap face, then process the opposite face entirely for now.
  51885. //Note that the cases in which this happens, what usually happens is that
  51886. // more than one edge bleeds onto the opposite face, and the bounding box
  51887. // encompasses the entire cube map face.
  51888. if (bleedOverAmount[i] > srcSize) {
  51889. //determine opposite face
  51890. switch (faceIdx) {
  51891. case PMREMGenerator.CP_FACE_X_POS:
  51892. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  51893. break;
  51894. case PMREMGenerator.CP_FACE_X_NEG:
  51895. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  51896. break;
  51897. case PMREMGenerator.CP_FACE_Y_POS:
  51898. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  51899. break;
  51900. case PMREMGenerator.CP_FACE_Y_NEG:
  51901. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  51902. break;
  51903. case PMREMGenerator.CP_FACE_Z_POS:
  51904. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  51905. break;
  51906. case PMREMGenerator.CP_FACE_Z_NEG:
  51907. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  51908. break;
  51909. default:
  51910. break;
  51911. }
  51912. //just encompass entire face for now
  51913. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  51914. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  51915. }
  51916. }
  51917. };
  51918. //--------------------------------------------------------------------------------------
  51919. //ProcessFilterExtents
  51920. // Process bounding box in each cube face
  51921. //
  51922. //--------------------------------------------------------------------------------------
  51923. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  51924. //accumulators are 64-bit floats in order to have the precision needed
  51925. // over a summation of a large number of pixels
  51926. var dstAccum = [0, 0, 0, 0];
  51927. var weightAccum = 0;
  51928. var k = 0;
  51929. var nSrcChannels = this.numChannels;
  51930. // norm cube map and srcCubeMap have same face width
  51931. var faceWidth = srcSize;
  51932. //amount to add to pointer to move to next scanline in images
  51933. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  51934. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  51935. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  51936. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  51937. // iterate over cubefaces
  51938. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  51939. //if bbox is non empty
  51940. if (!filterExtents[iFaceIdx].empty()) {
  51941. var uStart = filterExtents[iFaceIdx].min.x;
  51942. var vStart = filterExtents[iFaceIdx].min.y;
  51943. var uEnd = filterExtents[iFaceIdx].max.x;
  51944. var vEnd = filterExtents[iFaceIdx].max.y;
  51945. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  51946. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  51947. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  51948. for (var v = vStart; v <= vEnd; v++) {
  51949. var normCubeRowWalk = 0;
  51950. var srcCubeRowWalk = 0;
  51951. for (var u = uStart; u <= uEnd; u++) {
  51952. //pointer to direction in cube map associated with texel
  51953. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  51954. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  51955. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  51956. //check dot product to see if texel is within cone
  51957. var tapDotProd = texelVectX * centerTapDir.x +
  51958. texelVectY * centerTapDir.y +
  51959. texelVectZ * centerTapDir.z;
  51960. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  51961. //solid angle stored in 4th channel of normalizer/solid angle cube map
  51962. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  51963. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  51964. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  51965. // so just adding one to specularpower do the trick.
  51966. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  51967. //iterate over channels
  51968. for (k = 0; k < nSrcChannels; k++) {
  51969. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  51970. srcCubeRowWalk++;
  51971. }
  51972. weightAccum += weight; //accumulate weight
  51973. }
  51974. else {
  51975. //step across source pixel
  51976. srcCubeRowWalk += nSrcChannels;
  51977. }
  51978. normCubeRowWalk += 4; // 4 channels per norm cube map.
  51979. }
  51980. startIndexNormCubeMap += normCubePitch;
  51981. startIndexSrcCubeMap += srcCubePitch;
  51982. }
  51983. }
  51984. }
  51985. //divide through by weights if weight is non zero
  51986. if (weightAccum != 0.0) {
  51987. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  51988. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  51989. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  51990. if (this.numChannels > 3) {
  51991. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  51992. }
  51993. }
  51994. else {
  51995. // otherwise sample nearest
  51996. // get face idx and u, v texel coordinate in face
  51997. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  51998. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  51999. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  52000. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  52001. if (this.numChannels > 3) {
  52002. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  52003. }
  52004. }
  52005. return PMREMGenerator._vectorTemp;
  52006. };
  52007. //--------------------------------------------------------------------------------------
  52008. // Fixup cube edges
  52009. //
  52010. // average texels on cube map faces across the edges
  52011. // WARP/BENT Method Only.
  52012. //--------------------------------------------------------------------------------------
  52013. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  52014. var k;
  52015. var j;
  52016. var i;
  52017. var iFace;
  52018. var iCorner = 0;
  52019. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  52020. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  52021. // note that if functionality to filter across the three texels for each corner, then
  52022. //indexed by corner and face idx. the array contains the face the start points belongs to.
  52023. var cornerPtr = [
  52024. [[], [], []],
  52025. [[], [], []],
  52026. [[], [], []],
  52027. [[], [], []],
  52028. [[], [], []],
  52029. [[], [], []],
  52030. [[], [], []],
  52031. [[], [], []]
  52032. ];
  52033. //if there is no fixup, or fixup width = 0, do nothing
  52034. if (cubeMapSize < 1) {
  52035. return;
  52036. }
  52037. //special case 1x1 cubemap, average face colors
  52038. if (cubeMapSize == 1) {
  52039. //iterate over channels
  52040. for (k = 0; k < this.numChannels; k++) {
  52041. var accum = 0.0;
  52042. //iterate over faces to accumulate face colors
  52043. for (iFace = 0; iFace < 6; iFace++) {
  52044. accum += cubeMap[iFace][k];
  52045. }
  52046. //compute average over 6 face colors
  52047. accum /= 6.0;
  52048. //iterate over faces to distribute face colors
  52049. for (iFace = 0; iFace < 6; iFace++) {
  52050. cubeMap[iFace][k] = accum;
  52051. }
  52052. }
  52053. return;
  52054. }
  52055. //iterate over faces to collect list of corner texel pointers
  52056. for (iFace = 0; iFace < 6; iFace++) {
  52057. //the 4 corner pointers for this face
  52058. faceCornerStartIndicies[0] = [iFace, 0];
  52059. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  52060. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  52061. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  52062. //iterate over face corners to collect cube corner pointers
  52063. for (iCorner = 0; iCorner < 4; iCorner++) {
  52064. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  52065. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  52066. cornerNumPtrs[corner]++;
  52067. }
  52068. }
  52069. //iterate over corners to average across corner tap values
  52070. for (iCorner = 0; iCorner < 8; iCorner++) {
  52071. for (k = 0; k < this.numChannels; k++) {
  52072. var cornerTapAccum = 0.0;
  52073. //iterate over corner texels and average results
  52074. for (i = 0; i < 3; i++) {
  52075. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  52076. }
  52077. //divide by 3 to compute average of corner tap values
  52078. cornerTapAccum *= (1.0 / 3.0);
  52079. //iterate over corner texels and average results
  52080. for (i = 0; i < 3; i++) {
  52081. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  52082. }
  52083. }
  52084. }
  52085. //iterate over the twelve edges of the cube to average across edges
  52086. for (i = 0; i < 12; i++) {
  52087. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  52088. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  52089. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  52090. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  52091. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  52092. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  52093. var edgeWalk = 0;
  52094. var neighborEdgeWalk = 0;
  52095. //Determine walking pointers based on edge type
  52096. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  52097. switch (edge) {
  52098. case PMREMGenerator.CP_EDGE_LEFT:
  52099. // no change to faceEdgeStartPtr
  52100. edgeWalk = this.numChannels * cubeMapSize;
  52101. break;
  52102. case PMREMGenerator.CP_EDGE_RIGHT:
  52103. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  52104. edgeWalk = this.numChannels * cubeMapSize;
  52105. break;
  52106. case PMREMGenerator.CP_EDGE_TOP:
  52107. // no change to faceEdgeStartPtr
  52108. edgeWalk = this.numChannels;
  52109. break;
  52110. case PMREMGenerator.CP_EDGE_BOTTOM:
  52111. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  52112. edgeWalk = this.numChannels;
  52113. break;
  52114. }
  52115. //For certain types of edge abutments, the neighbor edge walk needs to
  52116. // be flipped: the cases are
  52117. // if a left edge mates with a left or bottom edge on the neighbor
  52118. // if a top edge mates with a top or right edge on the neighbor
  52119. // if a right edge mates with a right or top edge on the neighbor
  52120. // if a bottom edge mates with a bottom or left edge on the neighbor
  52121. //Seeing as the edges are enumerated as follows
  52122. // left =0
  52123. // right =1
  52124. // top =2
  52125. // bottom =3
  52126. //
  52127. //If the edge enums are the same, or the sum of the enums == 3,
  52128. // the neighbor edge walk needs to be flipped
  52129. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  52130. switch (neighborEdge) {
  52131. case PMREMGenerator.CP_EDGE_LEFT:
  52132. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  52133. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  52134. break;
  52135. case PMREMGenerator.CP_EDGE_RIGHT:
  52136. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  52137. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  52138. break;
  52139. case PMREMGenerator.CP_EDGE_TOP:
  52140. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  52141. neighborEdgeWalk = -this.numChannels;
  52142. break;
  52143. case PMREMGenerator.CP_EDGE_BOTTOM:
  52144. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  52145. neighborEdgeWalk = -this.numChannels;
  52146. break;
  52147. }
  52148. }
  52149. else {
  52150. //swapped direction neighbor edge walk
  52151. switch (neighborEdge) {
  52152. case PMREMGenerator.CP_EDGE_LEFT:
  52153. //no change to neighborEdgeStartPtr for this case since it points
  52154. // to the upper left corner already
  52155. neighborEdgeWalk = this.numChannels * cubeMapSize;
  52156. break;
  52157. case PMREMGenerator.CP_EDGE_RIGHT:
  52158. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  52159. neighborEdgeWalk = this.numChannels * cubeMapSize;
  52160. break;
  52161. case PMREMGenerator.CP_EDGE_TOP:
  52162. //no change to neighborEdgeStartPtr for this case since it points
  52163. // to the upper left corner already
  52164. neighborEdgeWalk = this.numChannels;
  52165. break;
  52166. case PMREMGenerator.CP_EDGE_BOTTOM:
  52167. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  52168. neighborEdgeWalk = this.numChannels;
  52169. break;
  52170. }
  52171. }
  52172. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  52173. //nearby neighborhood
  52174. //step ahead one texel on edge
  52175. edgeStartIndex += edgeWalk;
  52176. neighborEdgeStartIndex += neighborEdgeWalk;
  52177. // note that this loop does not process the corner texels, since they have already been
  52178. // averaged across faces across earlier
  52179. for (j = 1; j < (cubeMapSize - 1); j++) {
  52180. //for each set of taps along edge, average them
  52181. // and rewrite the results into the edges
  52182. for (k = 0; k < this.numChannels; k++) {
  52183. var edgeTap = cubeMap[face][edgeStartIndex + k];
  52184. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  52185. //compute average of tap intensity values
  52186. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  52187. //propagate average of taps to edge taps
  52188. cubeMap[face][edgeStartIndex + k] = avgTap;
  52189. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  52190. }
  52191. edgeStartIndex += edgeWalk;
  52192. neighborEdgeStartIndex += neighborEdgeWalk;
  52193. }
  52194. }
  52195. };
  52196. return PMREMGenerator;
  52197. }());
  52198. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  52199. PMREMGenerator.CP_UDIR = 0;
  52200. PMREMGenerator.CP_VDIR = 1;
  52201. PMREMGenerator.CP_FACEAXIS = 2;
  52202. //used to index cube faces
  52203. PMREMGenerator.CP_FACE_X_POS = 0;
  52204. PMREMGenerator.CP_FACE_X_NEG = 1;
  52205. PMREMGenerator.CP_FACE_Y_POS = 2;
  52206. PMREMGenerator.CP_FACE_Y_NEG = 3;
  52207. PMREMGenerator.CP_FACE_Z_POS = 4;
  52208. PMREMGenerator.CP_FACE_Z_NEG = 5;
  52209. //used to index image edges
  52210. // NOTE.. the actual number corresponding to the edge is important
  52211. // do not change these, or the code will break
  52212. //
  52213. // CP_EDGE_LEFT is u = 0
  52214. // CP_EDGE_RIGHT is u = width-1
  52215. // CP_EDGE_TOP is v = 0
  52216. // CP_EDGE_BOTTOM is v = height-1
  52217. PMREMGenerator.CP_EDGE_LEFT = 0;
  52218. PMREMGenerator.CP_EDGE_RIGHT = 1;
  52219. PMREMGenerator.CP_EDGE_TOP = 2;
  52220. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  52221. //corners of CUBE map (P or N specifys if it corresponds to the
  52222. // positive or negative direction each of X, Y, and Z
  52223. PMREMGenerator.CP_CORNER_NNN = 0;
  52224. PMREMGenerator.CP_CORNER_NNP = 1;
  52225. PMREMGenerator.CP_CORNER_NPN = 2;
  52226. PMREMGenerator.CP_CORNER_NPP = 3;
  52227. PMREMGenerator.CP_CORNER_PNN = 4;
  52228. PMREMGenerator.CP_CORNER_PNP = 5;
  52229. PMREMGenerator.CP_CORNER_PPN = 6;
  52230. PMREMGenerator.CP_CORNER_PPP = 7;
  52231. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  52232. //3x2 matrices that map cube map indexing vectors in 3d
  52233. // (after face selection and divide through by the
  52234. // _ABSOLUTE VALUE_ of the max coord)
  52235. // into NVC space
  52236. //Note this currently assumes the D3D cube face ordering and orientation
  52237. PMREMGenerator._sgFace2DMapping = [
  52238. //XPOS face
  52239. [[0, 0, -1],
  52240. [0, -1, 0],
  52241. [1, 0, 0]],
  52242. //XNEG face
  52243. [[0, 0, 1],
  52244. [0, -1, 0],
  52245. [-1, 0, 0]],
  52246. //YPOS face
  52247. [[1, 0, 0],
  52248. [0, 0, 1],
  52249. [0, 1, 0]],
  52250. //YNEG face
  52251. [[1, 0, 0],
  52252. [0, 0, -1],
  52253. [0, -1, 0]],
  52254. //ZPOS face
  52255. [[1, 0, 0],
  52256. [0, -1, 0],
  52257. [0, 0, 1]],
  52258. //ZNEG face
  52259. [[-1, 0, 0],
  52260. [0, -1, 0],
  52261. [0, 0, -1]],
  52262. ];
  52263. //------------------------------------------------------------------------------
  52264. // D3D cube map face specification
  52265. // mapping from 3D x,y,z cube map lookup coordinates
  52266. // to 2D within face u,v coordinates
  52267. //
  52268. // --------------------> U direction
  52269. // | (within-face texture space)
  52270. // | _____
  52271. // | | |
  52272. // | | +Y |
  52273. // | _____|_____|_____ _____
  52274. // | | | | | |
  52275. // | | -X | +Z | +X | -Z |
  52276. // | |_____|_____|_____|_____|
  52277. // | | |
  52278. // | | -Y |
  52279. // | |_____|
  52280. // |
  52281. // v V direction
  52282. // (within-face texture space)
  52283. //------------------------------------------------------------------------------
  52284. //Information about neighbors and how texture coorrdinates change across faces
  52285. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  52286. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  52287. //Note this currently assumes the D3D cube face ordering and orientation
  52288. PMREMGenerator._sgCubeNgh = [
  52289. //XPOS face
  52290. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52291. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  52292. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52293. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  52294. //XNEG face
  52295. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  52296. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  52297. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  52298. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  52299. //YPOS face
  52300. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  52301. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  52302. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  52303. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  52304. //YNEG face
  52305. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  52306. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52307. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52308. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  52309. //ZPOS face
  52310. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  52311. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  52312. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52313. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  52314. //ZNEG face
  52315. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52316. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  52317. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  52318. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  52319. ];
  52320. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  52321. // this table is used to average over the edges.
  52322. PMREMGenerator._sgCubeEdgeList = [
  52323. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  52324. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52325. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  52326. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52327. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  52328. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  52329. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  52330. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  52331. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  52332. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52333. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  52334. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  52335. ];
  52336. //Information about which of the 8 cube corners are correspond to the
  52337. // the 4 corners in each cube face
  52338. // the order is upper left, upper right, lower left, lower right
  52339. PMREMGenerator._sgCubeCornerList = [
  52340. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  52341. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  52342. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  52343. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  52344. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  52345. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  52346. ];
  52347. Internals.PMREMGenerator = PMREMGenerator;
  52348. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  52349. })(BABYLON || (BABYLON = {}));
  52350. //# sourceMappingURL=babylon.pmremgenerator.js.map
  52351. var BABYLON;
  52352. (function (BABYLON) {
  52353. /**
  52354. * This represents a texture coming from an HDR input.
  52355. *
  52356. * The only supported format is currently panorama picture stored in RGBE format.
  52357. * Example of such files can be found on HDRLib: http://hdrlib.com/
  52358. */
  52359. var HDRCubeTexture = (function (_super) {
  52360. __extends(HDRCubeTexture, _super);
  52361. /**
  52362. * Instantiates an HDRTexture from the following parameters.
  52363. *
  52364. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  52365. * @param scene The scene the texture will be used in
  52366. * @param size The cubemap desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  52367. * @param noMipmap Forces to not generate the mipmap if true
  52368. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  52369. * @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)
  52370. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  52371. */
  52372. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  52373. if (noMipmap === void 0) { noMipmap = false; }
  52374. if (generateHarmonics === void 0) { generateHarmonics = true; }
  52375. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  52376. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  52377. if (onLoad === void 0) { onLoad = null; }
  52378. if (onError === void 0) { onError = null; }
  52379. var _this = _super.call(this, scene) || this;
  52380. _this._useInGammaSpace = false;
  52381. _this._generateHarmonics = true;
  52382. _this._isBABYLONPreprocessed = false;
  52383. _this._onLoad = null;
  52384. _this._onError = null;
  52385. /**
  52386. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  52387. */
  52388. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  52389. /**
  52390. * The spherical polynomial data extracted from the texture.
  52391. */
  52392. _this.sphericalPolynomial = null;
  52393. /**
  52394. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  52395. * This is usefull at run time to apply the good shader.
  52396. */
  52397. _this.isPMREM = false;
  52398. if (!url) {
  52399. return _this;
  52400. }
  52401. _this.name = url;
  52402. _this.url = url;
  52403. _this.hasAlpha = false;
  52404. _this.isCube = true;
  52405. _this._textureMatrix = BABYLON.Matrix.Identity();
  52406. _this._onLoad = onLoad;
  52407. _this._onError = onError;
  52408. if (size) {
  52409. _this._isBABYLONPreprocessed = false;
  52410. _this._noMipmap = noMipmap;
  52411. _this._size = size;
  52412. _this._useInGammaSpace = useInGammaSpace;
  52413. _this._usePMREMGenerator = usePMREMGenerator &&
  52414. scene.getEngine().getCaps().textureLOD &&
  52415. _this.getScene().getEngine().getCaps().textureFloat &&
  52416. !_this._useInGammaSpace;
  52417. }
  52418. else {
  52419. _this._isBABYLONPreprocessed = true;
  52420. _this._noMipmap = false;
  52421. _this._useInGammaSpace = false;
  52422. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  52423. _this.getScene().getEngine().getCaps().textureFloat &&
  52424. !_this._useInGammaSpace;
  52425. }
  52426. _this.isPMREM = _this._usePMREMGenerator;
  52427. _this._texture = _this._getFromCache(url, _this._noMipmap);
  52428. if (!_this._texture) {
  52429. if (!scene.useDelayedTextureLoading) {
  52430. _this.loadTexture();
  52431. }
  52432. else {
  52433. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  52434. }
  52435. }
  52436. return _this;
  52437. }
  52438. /**
  52439. * Occurs when the file is a preprocessed .babylon.hdr file.
  52440. */
  52441. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  52442. var _this = this;
  52443. var mipLevels = 0;
  52444. var floatArrayView = null;
  52445. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  52446. var mips = [];
  52447. var startIndex = 30;
  52448. for (var level = 0; level < mipLevels; level++) {
  52449. mips.push([]);
  52450. // Fill each pixel of the mip level.
  52451. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  52452. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52453. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  52454. mips[level].push(faceData);
  52455. startIndex += faceSize;
  52456. }
  52457. }
  52458. return mips;
  52459. } : null;
  52460. var callback = function (buffer) {
  52461. // Create Native Array Views
  52462. var intArrayView = new Int32Array(buffer);
  52463. floatArrayView = new Float32Array(buffer);
  52464. // Fill header.
  52465. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  52466. _this._size = intArrayView[1]; // CubeMap max mip face size.
  52467. // Update Texture Information.
  52468. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  52469. // Fill polynomial information.
  52470. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  52471. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  52472. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  52473. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  52474. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  52475. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  52476. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  52477. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  52478. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  52479. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  52480. // Fill pixel data.
  52481. mipLevels = intArrayView[29]; // Number of mip levels.
  52482. var startIndex = 30;
  52483. var data = [];
  52484. var faceSize = Math.pow(_this._size, 2) * 3;
  52485. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52486. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  52487. startIndex += faceSize;
  52488. }
  52489. var results = [];
  52490. var byteArray = null;
  52491. // Push each faces.
  52492. for (var k = 0; k < 6; k++) {
  52493. var dataFace = null;
  52494. // If special cases.
  52495. if (!mipmapGenerator) {
  52496. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  52497. dataFace = data[j];
  52498. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  52499. // 3 channels of 1 bytes per pixel in bytes.
  52500. var byteBuffer = new ArrayBuffer(faceSize);
  52501. byteArray = new Uint8Array(byteBuffer);
  52502. }
  52503. for (var i = 0; i < _this._size * _this._size; i++) {
  52504. // Put in gamma space if requested.
  52505. if (_this._useInGammaSpace) {
  52506. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  52507. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  52508. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  52509. }
  52510. // Convert to int texture for fallback.
  52511. if (byteArray) {
  52512. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  52513. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  52514. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  52515. // May use luminance instead if the result is not accurate.
  52516. var max = Math.max(Math.max(r, g), b);
  52517. if (max > 255) {
  52518. var scale = 255 / max;
  52519. r *= scale;
  52520. g *= scale;
  52521. b *= scale;
  52522. }
  52523. byteArray[(i * 3) + 0] = r;
  52524. byteArray[(i * 3) + 1] = g;
  52525. byteArray[(i * 3) + 2] = b;
  52526. }
  52527. }
  52528. }
  52529. else {
  52530. dataFace = data[k];
  52531. }
  52532. // Fill the array accordingly.
  52533. if (byteArray) {
  52534. results.push(byteArray);
  52535. }
  52536. else {
  52537. results.push(dataFace);
  52538. }
  52539. }
  52540. return results;
  52541. };
  52542. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  52543. };
  52544. /**
  52545. * Occurs when the file is raw .hdr file.
  52546. */
  52547. HDRCubeTexture.prototype.loadHDRTexture = function () {
  52548. var _this = this;
  52549. var callback = function (buffer) {
  52550. // Extract the raw linear data.
  52551. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  52552. // Generate harmonics if needed.
  52553. if (_this._generateHarmonics) {
  52554. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  52555. }
  52556. var results = [];
  52557. var byteArray = null;
  52558. // Push each faces.
  52559. for (var j = 0; j < 6; j++) {
  52560. // Create uintarray fallback.
  52561. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  52562. // 3 channels of 1 bytes per pixel in bytes.
  52563. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  52564. byteArray = new Uint8Array(byteBuffer);
  52565. }
  52566. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  52567. // If special cases.
  52568. if (_this._useInGammaSpace || byteArray) {
  52569. for (var i = 0; i < _this._size * _this._size; i++) {
  52570. // Put in gamma space if requested.
  52571. if (_this._useInGammaSpace) {
  52572. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  52573. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  52574. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  52575. }
  52576. // Convert to int texture for fallback.
  52577. if (byteArray) {
  52578. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  52579. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  52580. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  52581. // May use luminance instead if the result is not accurate.
  52582. var max = Math.max(Math.max(r, g), b);
  52583. if (max > 255) {
  52584. var scale = 255 / max;
  52585. r *= scale;
  52586. g *= scale;
  52587. b *= scale;
  52588. }
  52589. byteArray[(i * 3) + 0] = r;
  52590. byteArray[(i * 3) + 1] = g;
  52591. byteArray[(i * 3) + 2] = b;
  52592. }
  52593. }
  52594. }
  52595. if (byteArray) {
  52596. results.push(byteArray);
  52597. }
  52598. else {
  52599. results.push(dataFace);
  52600. }
  52601. }
  52602. return results;
  52603. };
  52604. var mipmapGenerator = null;
  52605. if (!this._noMipmap &&
  52606. this._usePMREMGenerator) {
  52607. mipmapGenerator = function (data) {
  52608. // Custom setup of the generator matching with the PBR shader values.
  52609. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  52610. return generator.filterCubeMap();
  52611. };
  52612. }
  52613. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  52614. };
  52615. /**
  52616. * Starts the loading process of the texture.
  52617. */
  52618. HDRCubeTexture.prototype.loadTexture = function () {
  52619. if (this._isBABYLONPreprocessed) {
  52620. this.loadBabylonTexture();
  52621. }
  52622. else {
  52623. this.loadHDRTexture();
  52624. }
  52625. };
  52626. HDRCubeTexture.prototype.clone = function () {
  52627. var size = this._isBABYLONPreprocessed ? null : this._size;
  52628. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  52629. // Base texture
  52630. newTexture.level = this.level;
  52631. newTexture.wrapU = this.wrapU;
  52632. newTexture.wrapV = this.wrapV;
  52633. newTexture.coordinatesIndex = this.coordinatesIndex;
  52634. newTexture.coordinatesMode = this.coordinatesMode;
  52635. return newTexture;
  52636. };
  52637. // Methods
  52638. HDRCubeTexture.prototype.delayLoad = function () {
  52639. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  52640. return;
  52641. }
  52642. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  52643. this._texture = this._getFromCache(this.url, this._noMipmap);
  52644. if (!this._texture) {
  52645. this.loadTexture();
  52646. }
  52647. };
  52648. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  52649. return this._textureMatrix;
  52650. };
  52651. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  52652. var texture = null;
  52653. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  52654. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  52655. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  52656. texture.name = parsedTexture.name;
  52657. texture.hasAlpha = parsedTexture.hasAlpha;
  52658. texture.level = parsedTexture.level;
  52659. texture.coordinatesMode = parsedTexture.coordinatesMode;
  52660. }
  52661. return texture;
  52662. };
  52663. HDRCubeTexture.prototype.serialize = function () {
  52664. if (!this.name) {
  52665. return null;
  52666. }
  52667. var serializationObject = {};
  52668. serializationObject.name = this.name;
  52669. serializationObject.hasAlpha = this.hasAlpha;
  52670. serializationObject.isCube = true;
  52671. serializationObject.level = this.level;
  52672. serializationObject.size = this._size;
  52673. serializationObject.coordinatesMode = this.coordinatesMode;
  52674. serializationObject.useInGammaSpace = this._useInGammaSpace;
  52675. serializationObject.generateHarmonics = this._generateHarmonics;
  52676. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  52677. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  52678. serializationObject.customType = "BABYLON.HDRCubeTexture";
  52679. serializationObject.noMipmap = this._noMipmap;
  52680. return serializationObject;
  52681. };
  52682. /**
  52683. * Saves as a file the data contained in the texture in a binary format.
  52684. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  52685. * as the spherical used in the lighting.
  52686. * @param url The HDR file url.
  52687. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  52688. * @param onError Method called if any error happens during download.
  52689. * @return The packed binary data.
  52690. */
  52691. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  52692. if (onError === void 0) { onError = null; }
  52693. var callback = function (buffer) {
  52694. var data = new Blob([buffer], { type: 'application/octet-stream' });
  52695. // Returns a URL you can use as a href.
  52696. var objUrl = window.URL.createObjectURL(data);
  52697. // Simulates a link to it and click to dowload.
  52698. var a = document.createElement("a");
  52699. document.body.appendChild(a);
  52700. a.style.display = "none";
  52701. a.href = objUrl;
  52702. a.download = "envmap.babylon.hdr";
  52703. a.click();
  52704. };
  52705. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  52706. };
  52707. /**
  52708. * Serializes the data contained in the texture in a binary format.
  52709. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  52710. * as the spherical used in the lighting.
  52711. * @param url The HDR file url.
  52712. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  52713. * @param onError Method called if any error happens during download.
  52714. * @return The packed binary data.
  52715. */
  52716. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  52717. if (onError === void 0) { onError = null; }
  52718. // Needs the url tho create the texture.
  52719. if (!url) {
  52720. return null;
  52721. }
  52722. // Check Power of two size.
  52723. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  52724. return null;
  52725. }
  52726. var getDataCallback = function (dataBuffer) {
  52727. // Extract the raw linear data.
  52728. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  52729. // Generate harmonics if needed.
  52730. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  52731. // Generate seamless faces
  52732. var mipGeneratorArray = [];
  52733. // Data are known to be in +X +Y +Z -X -Y -Z
  52734. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  52735. mipGeneratorArray.push(cubeData.right); // +X
  52736. mipGeneratorArray.push(cubeData.left); // -X
  52737. mipGeneratorArray.push(cubeData.up); // +Y
  52738. mipGeneratorArray.push(cubeData.down); // -Y
  52739. mipGeneratorArray.push(cubeData.front); // +Z
  52740. mipGeneratorArray.push(cubeData.back); // -Z
  52741. // Custom setup of the generator matching with the PBR shader values.
  52742. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  52743. var mippedData = generator.filterCubeMap();
  52744. // Compute required byte length.
  52745. var byteLength = 1 * 4; // Raw Data Version int32.
  52746. byteLength += 4; // CubeMap max mip face size int32.
  52747. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  52748. // Add data size.
  52749. byteLength += 4; // Number of mip levels int32.
  52750. for (var level = 0; level < mippedData.length; level++) {
  52751. var mipSize = size >> level;
  52752. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  52753. }
  52754. // Prepare binary structure.
  52755. var buffer = new ArrayBuffer(byteLength);
  52756. var intArrayView = new Int32Array(buffer);
  52757. var floatArrayView = new Float32Array(buffer);
  52758. // Fill header.
  52759. intArrayView[0] = 1; // Version 1.
  52760. intArrayView[1] = size; // CubeMap max mip face size.
  52761. // Fill polynomial information.
  52762. sphericalPolynomial.x.toArray(floatArrayView, 2);
  52763. sphericalPolynomial.y.toArray(floatArrayView, 5);
  52764. sphericalPolynomial.z.toArray(floatArrayView, 8);
  52765. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  52766. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  52767. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  52768. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  52769. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  52770. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  52771. // Fill pixel data.
  52772. intArrayView[29] = mippedData.length; // Number of mip levels.
  52773. var startIndex = 30;
  52774. for (var level = 0; level < mippedData.length; level++) {
  52775. // Fill each pixel of the mip level.
  52776. var faceSize = Math.pow(size >> level, 2) * 3;
  52777. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52778. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  52779. startIndex += faceSize;
  52780. }
  52781. }
  52782. // Callback.
  52783. callback(buffer);
  52784. };
  52785. // Download and process.
  52786. BABYLON.Tools.LoadFile(url, function (data) {
  52787. getDataCallback(data);
  52788. }, null, null, true, onError);
  52789. };
  52790. return HDRCubeTexture;
  52791. }(BABYLON.BaseTexture));
  52792. HDRCubeTexture._facesMapping = [
  52793. "right",
  52794. "up",
  52795. "front",
  52796. "left",
  52797. "down",
  52798. "back"
  52799. ];
  52800. BABYLON.HDRCubeTexture = HDRCubeTexture;
  52801. })(BABYLON || (BABYLON = {}));
  52802. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  52803. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  52804. // Huge respect for a such great lib.
  52805. // Earcut license:
  52806. // Copyright (c) 2016, Mapbox
  52807. //
  52808. // Permission to use, copy, modify, and/or distribute this software for any purpose
  52809. // with or without fee is hereby granted, provided that the above copyright notice
  52810. // and this permission notice appear in all copies.
  52811. //
  52812. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  52813. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  52814. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  52815. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  52816. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  52817. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  52818. // THIS SOFTWARE.
  52819. var Earcut;
  52820. (function (Earcut) {
  52821. /**
  52822. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  52823. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  52824. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  52825. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  52826. */
  52827. function earcut(data, holeIndices, dim) {
  52828. dim = dim || 2;
  52829. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  52830. if (!outerNode)
  52831. return triangles;
  52832. var minX, minY, maxX, maxY, x, y, size;
  52833. if (hasHoles)
  52834. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  52835. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  52836. if (data.length > 80 * dim) {
  52837. minX = maxX = data[0];
  52838. minY = maxY = data[1];
  52839. for (var i = dim; i < outerLen; i += dim) {
  52840. x = data[i];
  52841. y = data[i + 1];
  52842. if (x < minX)
  52843. minX = x;
  52844. if (y < minY)
  52845. minY = y;
  52846. if (x > maxX)
  52847. maxX = x;
  52848. if (y > maxY)
  52849. maxY = y;
  52850. }
  52851. // minX, minY and size are later used to transform coords into integers for z-order calculation
  52852. size = Math.max(maxX - minX, maxY - minY);
  52853. }
  52854. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  52855. return triangles;
  52856. }
  52857. Earcut.earcut = earcut;
  52858. // create a circular doubly linked list from polygon points in the specified winding order
  52859. function linkedList(data, start, end, dim, clockwise) {
  52860. var i, last;
  52861. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  52862. for (i = start; i < end; i += dim)
  52863. last = insertNode(i, data[i], data[i + 1], last);
  52864. }
  52865. else {
  52866. for (i = end - dim; i >= start; i -= dim)
  52867. last = insertNode(i, data[i], data[i + 1], last);
  52868. }
  52869. if (last && equals(last, last.next)) {
  52870. removeNode(last);
  52871. last = last.next;
  52872. }
  52873. return last;
  52874. }
  52875. // eliminate colinear or duplicate points
  52876. function filterPoints(start, end) {
  52877. if (!start)
  52878. return start;
  52879. if (!end)
  52880. end = start;
  52881. var p = start, again;
  52882. do {
  52883. again = false;
  52884. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  52885. removeNode(p);
  52886. p = end = p.prev;
  52887. if (p === p.next)
  52888. return null;
  52889. again = true;
  52890. }
  52891. else {
  52892. p = p.next;
  52893. }
  52894. } while (again || p !== end);
  52895. return end;
  52896. }
  52897. // main ear slicing loop which triangulates a polygon (given as a linked list)
  52898. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  52899. if (!ear)
  52900. return;
  52901. // interlink polygon nodes in z-order
  52902. if (!pass && size)
  52903. indexCurve(ear, minX, minY, size);
  52904. var stop = ear, prev, next;
  52905. // iterate through ears, slicing them one by one
  52906. while (ear.prev !== ear.next) {
  52907. prev = ear.prev;
  52908. next = ear.next;
  52909. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  52910. // cut off the triangle
  52911. triangles.push(prev.i / dim);
  52912. triangles.push(ear.i / dim);
  52913. triangles.push(next.i / dim);
  52914. removeNode(ear);
  52915. // skipping the next vertice leads to less sliver triangles
  52916. ear = next.next;
  52917. stop = next.next;
  52918. continue;
  52919. }
  52920. ear = next;
  52921. // if we looped through the whole remaining polygon and can't find any more ears
  52922. if (ear === stop) {
  52923. // try filtering points and slicing again
  52924. if (!pass) {
  52925. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  52926. // if this didn't work, try curing all small self-intersections locally
  52927. }
  52928. else if (pass === 1) {
  52929. ear = cureLocalIntersections(ear, triangles, dim);
  52930. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  52931. // as a last resort, try splitting the remaining polygon into two
  52932. }
  52933. else if (pass === 2) {
  52934. splitEarcut(ear, triangles, dim, minX, minY, size);
  52935. }
  52936. break;
  52937. }
  52938. }
  52939. }
  52940. // check whether a polygon node forms a valid ear with adjacent nodes
  52941. function isEar(ear) {
  52942. var a = ear.prev, b = ear, c = ear.next;
  52943. if (area(a, b, c) >= 0)
  52944. return false; // reflex, can't be an ear
  52945. // now make sure we don't have other points inside the potential ear
  52946. var p = ear.next.next;
  52947. while (p !== ear.prev) {
  52948. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  52949. area(p.prev, p, p.next) >= 0)
  52950. return false;
  52951. p = p.next;
  52952. }
  52953. return true;
  52954. }
  52955. function isEarHashed(ear, minX, minY, size) {
  52956. var a = ear.prev, b = ear, c = ear.next;
  52957. if (area(a, b, c) >= 0)
  52958. return false; // reflex, can't be an ear
  52959. // triangle bbox; min & max are calculated like this for speed
  52960. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  52961. // z-order range for the current triangle bbox;
  52962. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  52963. // first look for points inside the triangle in increasing z-order
  52964. var p = ear.nextZ;
  52965. while (p && p.z <= maxZ) {
  52966. if (p !== ear.prev &&
  52967. p !== ear.next &&
  52968. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  52969. area(p.prev, p, p.next) >= 0)
  52970. return false;
  52971. p = p.nextZ;
  52972. }
  52973. // then look for points in decreasing z-order
  52974. p = ear.prevZ;
  52975. while (p && p.z >= minZ) {
  52976. if (p !== ear.prev &&
  52977. p !== ear.next &&
  52978. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  52979. area(p.prev, p, p.next) >= 0)
  52980. return false;
  52981. p = p.prevZ;
  52982. }
  52983. return true;
  52984. }
  52985. // go through all polygon nodes and cure small local self-intersections
  52986. function cureLocalIntersections(start, triangles, dim) {
  52987. var p = start;
  52988. do {
  52989. var a = p.prev, b = p.next.next;
  52990. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  52991. triangles.push(a.i / dim);
  52992. triangles.push(p.i / dim);
  52993. triangles.push(b.i / dim);
  52994. // remove two nodes involved
  52995. removeNode(p);
  52996. removeNode(p.next);
  52997. p = start = b;
  52998. }
  52999. p = p.next;
  53000. } while (p !== start);
  53001. return p;
  53002. }
  53003. // try splitting polygon into two and triangulate them independently
  53004. function splitEarcut(start, triangles, dim, minX, minY, size) {
  53005. // look for a valid diagonal that divides the polygon into two
  53006. var a = start;
  53007. do {
  53008. var b = a.next.next;
  53009. while (b !== a.prev) {
  53010. if (a.i !== b.i && isValidDiagonal(a, b)) {
  53011. // split the polygon in two by the diagonal
  53012. var c = splitPolygon(a, b);
  53013. // filter colinear points around the cuts
  53014. a = filterPoints(a, a.next);
  53015. c = filterPoints(c, c.next);
  53016. // run earcut on each half
  53017. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  53018. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  53019. return;
  53020. }
  53021. b = b.next;
  53022. }
  53023. a = a.next;
  53024. } while (a !== start);
  53025. }
  53026. // link every hole into the outer loop, producing a single-ring polygon without holes
  53027. function eliminateHoles(data, holeIndices, outerNode, dim) {
  53028. var queue = [], i, len, start, end, list;
  53029. for (i = 0, len = holeIndices.length; i < len; i++) {
  53030. start = holeIndices[i] * dim;
  53031. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  53032. list = linkedList(data, start, end, dim, false);
  53033. if (list === list.next)
  53034. list.steiner = true;
  53035. queue.push(getLeftmost(list));
  53036. }
  53037. queue.sort(compareX);
  53038. // process holes from left to right
  53039. for (i = 0; i < queue.length; i++) {
  53040. eliminateHole(queue[i], outerNode);
  53041. outerNode = filterPoints(outerNode, outerNode.next);
  53042. }
  53043. return outerNode;
  53044. }
  53045. function compareX(a, b) {
  53046. return a.x - b.x;
  53047. }
  53048. // find a bridge between vertices that connects hole with an outer ring and and link it
  53049. function eliminateHole(hole, outerNode) {
  53050. outerNode = findHoleBridge(hole, outerNode);
  53051. if (outerNode) {
  53052. var b = splitPolygon(outerNode, hole);
  53053. filterPoints(b, b.next);
  53054. }
  53055. }
  53056. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  53057. function findHoleBridge(hole, outerNode) {
  53058. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  53059. // find a segment intersected by a ray from the hole's leftmost point to the left;
  53060. // segment's endpoint with lesser x will be potential connection point
  53061. do {
  53062. if (hy <= p.y && hy >= p.next.y) {
  53063. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  53064. if (x <= hx && x > qx) {
  53065. qx = x;
  53066. if (x === hx) {
  53067. if (hy === p.y)
  53068. return p;
  53069. if (hy === p.next.y)
  53070. return p.next;
  53071. }
  53072. m = p.x < p.next.x ? p : p.next;
  53073. }
  53074. }
  53075. p = p.next;
  53076. } while (p !== outerNode);
  53077. if (!m)
  53078. return null;
  53079. if (hx === qx)
  53080. return m.prev; // hole touches outer segment; pick lower endpoint
  53081. // look for points inside the triangle of hole point, segment intersection and endpoint;
  53082. // if there are no points found, we have a valid connection;
  53083. // otherwise choose the point of the minimum angle with the ray as connection point
  53084. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  53085. p = m.next;
  53086. while (p !== stop) {
  53087. if (hx >= p.x &&
  53088. p.x >= mx &&
  53089. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  53090. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  53091. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  53092. m = p;
  53093. tanMin = tan;
  53094. }
  53095. }
  53096. p = p.next;
  53097. }
  53098. return m;
  53099. }
  53100. // interlink polygon nodes in z-order
  53101. function indexCurve(start, minX, minY, size) {
  53102. var p = start;
  53103. do {
  53104. if (p.z === null)
  53105. p.z = zOrder(p.x, p.y, minX, minY, size);
  53106. p.prevZ = p.prev;
  53107. p.nextZ = p.next;
  53108. p = p.next;
  53109. } while (p !== start);
  53110. p.prevZ.nextZ = null;
  53111. p.prevZ = null;
  53112. sortLinked(p);
  53113. }
  53114. // Simon Tatham's linked list merge sort algorithm
  53115. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  53116. function sortLinked(list) {
  53117. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  53118. do {
  53119. p = list;
  53120. list = null;
  53121. tail = null;
  53122. numMerges = 0;
  53123. while (p) {
  53124. numMerges++;
  53125. q = p;
  53126. pSize = 0;
  53127. for (i = 0; i < inSize; i++) {
  53128. pSize++;
  53129. q = q.nextZ;
  53130. if (!q)
  53131. break;
  53132. }
  53133. qSize = inSize;
  53134. while (pSize > 0 || (qSize > 0 && q)) {
  53135. if (pSize === 0) {
  53136. e = q;
  53137. q = q.nextZ;
  53138. qSize--;
  53139. }
  53140. else if (qSize === 0 || !q) {
  53141. e = p;
  53142. p = p.nextZ;
  53143. pSize--;
  53144. }
  53145. else if (p.z <= q.z) {
  53146. e = p;
  53147. p = p.nextZ;
  53148. pSize--;
  53149. }
  53150. else {
  53151. e = q;
  53152. q = q.nextZ;
  53153. qSize--;
  53154. }
  53155. if (tail)
  53156. tail.nextZ = e;
  53157. else
  53158. list = e;
  53159. e.prevZ = tail;
  53160. tail = e;
  53161. }
  53162. p = q;
  53163. }
  53164. tail.nextZ = null;
  53165. inSize *= 2;
  53166. } while (numMerges > 1);
  53167. return list;
  53168. }
  53169. // z-order of a point given coords and size of the data bounding box
  53170. function zOrder(x, y, minX, minY, size) {
  53171. // coords are transformed into non-negative 15-bit integer range
  53172. x = 32767 * (x - minX) / size;
  53173. y = 32767 * (y - minY) / size;
  53174. x = (x | (x << 8)) & 0x00FF00FF;
  53175. x = (x | (x << 4)) & 0x0F0F0F0F;
  53176. x = (x | (x << 2)) & 0x33333333;
  53177. x = (x | (x << 1)) & 0x55555555;
  53178. y = (y | (y << 8)) & 0x00FF00FF;
  53179. y = (y | (y << 4)) & 0x0F0F0F0F;
  53180. y = (y | (y << 2)) & 0x33333333;
  53181. y = (y | (y << 1)) & 0x55555555;
  53182. return x | (y << 1);
  53183. }
  53184. // find the leftmost node of a polygon ring
  53185. function getLeftmost(start) {
  53186. var p = start, leftmost = start;
  53187. do {
  53188. if (p.x < leftmost.x)
  53189. leftmost = p;
  53190. p = p.next;
  53191. } while (p !== start);
  53192. return leftmost;
  53193. }
  53194. // check if a point lies within a convex triangle
  53195. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  53196. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  53197. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  53198. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  53199. }
  53200. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  53201. function isValidDiagonal(a, b) {
  53202. return a.next.i !== b.i &&
  53203. a.prev.i !== b.i &&
  53204. !intersectsPolygon(a, b) &&
  53205. locallyInside(a, b) &&
  53206. locallyInside(b, a) &&
  53207. middleInside(a, b);
  53208. }
  53209. // signed area of a triangle
  53210. function area(p, q, r) {
  53211. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  53212. }
  53213. // check if two points are equal
  53214. function equals(p1, p2) {
  53215. return p1.x === p2.x && p1.y === p2.y;
  53216. }
  53217. // check if two segments intersect
  53218. function intersects(p1, q1, p2, q2) {
  53219. if ((equals(p1, q1) && equals(p2, q2)) ||
  53220. (equals(p1, q2) && equals(p2, q1)))
  53221. return true;
  53222. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  53223. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  53224. }
  53225. // check if a polygon diagonal intersects any polygon segments
  53226. function intersectsPolygon(a, b) {
  53227. var p = a;
  53228. do {
  53229. if (p.i !== a.i &&
  53230. p.next.i !== a.i &&
  53231. p.i !== b.i &&
  53232. p.next.i !== b.i &&
  53233. intersects(p, p.next, a, b))
  53234. return true;
  53235. p = p.next;
  53236. } while (p !== a);
  53237. return false;
  53238. }
  53239. // check if a polygon diagonal is locally inside the polygon
  53240. function locallyInside(a, b) {
  53241. return area(a.prev, a, a.next) < 0
  53242. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  53243. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  53244. }
  53245. // check if the middle point of a polygon diagonal is inside the polygon
  53246. function middleInside(a, b) {
  53247. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  53248. do {
  53249. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  53250. inside = !inside;
  53251. p = p.next;
  53252. } while (p !== a);
  53253. return inside;
  53254. }
  53255. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  53256. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  53257. function splitPolygon(a, b) {
  53258. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  53259. a.next = b;
  53260. b.prev = a;
  53261. a2.next = an;
  53262. an.prev = a2;
  53263. b2.next = a2;
  53264. a2.prev = b2;
  53265. bp.next = b2;
  53266. b2.prev = bp;
  53267. return b2;
  53268. }
  53269. // create a node and optionally link it with previous one (in a circular doubly linked list)
  53270. function insertNode(i, x, y, last) {
  53271. var p = new Node(i, x, y);
  53272. if (!last) {
  53273. p.prev = p;
  53274. p.next = p;
  53275. }
  53276. else {
  53277. p.next = last.next;
  53278. p.prev = last;
  53279. last.next.prev = p;
  53280. last.next = p;
  53281. }
  53282. return p;
  53283. }
  53284. function removeNode(p) {
  53285. p.next.prev = p.prev;
  53286. p.prev.next = p.next;
  53287. if (p.prevZ)
  53288. p.prevZ.nextZ = p.nextZ;
  53289. if (p.nextZ)
  53290. p.nextZ.prevZ = p.prevZ;
  53291. }
  53292. function Node(i, x, y) {
  53293. // vertice index in coordinates array
  53294. this.i = i;
  53295. // vertex coordinates
  53296. this.x = x;
  53297. this.y = y;
  53298. // previous and next vertice nodes in a polygon ring
  53299. this.prev = null;
  53300. this.next = null;
  53301. // z-order curve value
  53302. this.z = null;
  53303. // previous and next nodes in z-order
  53304. this.prevZ = null;
  53305. this.nextZ = null;
  53306. // indicates whether this is a steiner point
  53307. this.steiner = false;
  53308. }
  53309. /**
  53310. * return a percentage difference between the polygon area and its triangulation area;
  53311. * used to verify correctness of triangulation
  53312. */
  53313. function deviation(data, holeIndices, dim, triangles) {
  53314. var hasHoles = holeIndices && holeIndices.length;
  53315. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  53316. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  53317. if (hasHoles) {
  53318. for (var i = 0, len = holeIndices.length; i < len; i++) {
  53319. var start = holeIndices[i] * dim;
  53320. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  53321. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  53322. }
  53323. }
  53324. var trianglesArea = 0;
  53325. for (i = 0; i < triangles.length; i += 3) {
  53326. var a = triangles[i] * dim;
  53327. var b = triangles[i + 1] * dim;
  53328. var c = triangles[i + 2] * dim;
  53329. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  53330. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  53331. }
  53332. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  53333. }
  53334. Earcut.deviation = deviation;
  53335. ;
  53336. function signedArea(data, start, end, dim) {
  53337. var sum = 0;
  53338. for (var i = start, j = end - dim; i < end; i += dim) {
  53339. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  53340. j = i;
  53341. }
  53342. return sum;
  53343. }
  53344. /**
  53345. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  53346. */
  53347. function flatten(data) {
  53348. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  53349. for (var i = 0; i < data.length; i++) {
  53350. for (var j = 0; j < data[i].length; j++) {
  53351. for (var d = 0; d < dim; d++)
  53352. result.vertices.push(data[i][j][d]);
  53353. }
  53354. if (i > 0) {
  53355. holeIndex += data[i - 1].length;
  53356. result.holes.push(holeIndex);
  53357. }
  53358. }
  53359. return result;
  53360. }
  53361. Earcut.flatten = flatten;
  53362. ;
  53363. })(Earcut || (Earcut = {}));
  53364. //# sourceMappingURL=babylon.earcut.js.map
  53365. /// <reference path="..\Math\babylon.math.ts" />
  53366. var BABYLON;
  53367. (function (BABYLON) {
  53368. var IndexedVector2 = (function (_super) {
  53369. __extends(IndexedVector2, _super);
  53370. function IndexedVector2(original, index) {
  53371. var _this = _super.call(this, original.x, original.y) || this;
  53372. _this.index = index;
  53373. return _this;
  53374. }
  53375. return IndexedVector2;
  53376. }(BABYLON.Vector2));
  53377. var PolygonPoints = (function () {
  53378. function PolygonPoints() {
  53379. this.elements = new Array();
  53380. }
  53381. PolygonPoints.prototype.add = function (originalPoints) {
  53382. var _this = this;
  53383. var result = new Array();
  53384. originalPoints.forEach(function (point) {
  53385. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  53386. var newPoint = new IndexedVector2(point, _this.elements.length);
  53387. result.push(newPoint);
  53388. _this.elements.push(newPoint);
  53389. }
  53390. });
  53391. return result;
  53392. };
  53393. PolygonPoints.prototype.computeBounds = function () {
  53394. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  53395. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  53396. this.elements.forEach(function (point) {
  53397. // x
  53398. if (point.x < lmin.x) {
  53399. lmin.x = point.x;
  53400. }
  53401. else if (point.x > lmax.x) {
  53402. lmax.x = point.x;
  53403. }
  53404. // y
  53405. if (point.y < lmin.y) {
  53406. lmin.y = point.y;
  53407. }
  53408. else if (point.y > lmax.y) {
  53409. lmax.y = point.y;
  53410. }
  53411. });
  53412. return {
  53413. min: lmin,
  53414. max: lmax,
  53415. width: lmax.x - lmin.x,
  53416. height: lmax.y - lmin.y
  53417. };
  53418. };
  53419. return PolygonPoints;
  53420. }());
  53421. var Polygon = (function () {
  53422. function Polygon() {
  53423. }
  53424. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  53425. return [
  53426. new BABYLON.Vector2(xmin, ymin),
  53427. new BABYLON.Vector2(xmax, ymin),
  53428. new BABYLON.Vector2(xmax, ymax),
  53429. new BABYLON.Vector2(xmin, ymax)
  53430. ];
  53431. };
  53432. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  53433. if (cx === void 0) { cx = 0; }
  53434. if (cy === void 0) { cy = 0; }
  53435. if (numberOfSides === void 0) { numberOfSides = 32; }
  53436. var result = new Array();
  53437. var angle = 0;
  53438. var increment = (Math.PI * 2) / numberOfSides;
  53439. for (var i = 0; i < numberOfSides; i++) {
  53440. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  53441. angle -= increment;
  53442. }
  53443. return result;
  53444. };
  53445. Polygon.Parse = function (input) {
  53446. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  53447. var i, result = [];
  53448. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  53449. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  53450. }
  53451. return result;
  53452. };
  53453. Polygon.StartingAt = function (x, y) {
  53454. return BABYLON.Path2.StartingAt(x, y);
  53455. };
  53456. return Polygon;
  53457. }());
  53458. BABYLON.Polygon = Polygon;
  53459. var PolygonMeshBuilder = (function () {
  53460. function PolygonMeshBuilder(name, contours, scene) {
  53461. this._points = new PolygonPoints();
  53462. this._outlinepoints = new PolygonPoints();
  53463. this._holes = [];
  53464. this._epoints = new Array();
  53465. this._eholes = new Array();
  53466. this._name = name;
  53467. this._scene = scene;
  53468. var points;
  53469. if (contours instanceof BABYLON.Path2) {
  53470. points = contours.getPoints();
  53471. }
  53472. else {
  53473. points = contours;
  53474. }
  53475. this._addToepoint(points);
  53476. this._points.add(points);
  53477. this._outlinepoints.add(points);
  53478. }
  53479. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  53480. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  53481. var p = points_1[_i];
  53482. this._epoints.push(p.x, p.y);
  53483. }
  53484. };
  53485. PolygonMeshBuilder.prototype.addHole = function (hole) {
  53486. this._points.add(hole);
  53487. var holepoints = new PolygonPoints();
  53488. holepoints.add(hole);
  53489. this._holes.push(holepoints);
  53490. this._eholes.push(this._epoints.length / 2);
  53491. this._addToepoint(hole);
  53492. return this;
  53493. };
  53494. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  53495. var _this = this;
  53496. if (updatable === void 0) { updatable = false; }
  53497. var result = new BABYLON.Mesh(this._name, this._scene);
  53498. var normals = [];
  53499. var positions = [];
  53500. var uvs = [];
  53501. var bounds = this._points.computeBounds();
  53502. this._points.elements.forEach(function (p) {
  53503. normals.push(0, 1.0, 0);
  53504. positions.push(p.x, 0, p.y);
  53505. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  53506. });
  53507. var indices = [];
  53508. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  53509. for (var i = 0; i < res.length; i++) {
  53510. indices.push(res[i]);
  53511. }
  53512. if (depth > 0) {
  53513. var positionscount = (positions.length / 3); //get the current pointcount
  53514. this._points.elements.forEach(function (p) {
  53515. normals.push(0, -1.0, 0);
  53516. positions.push(p.x, -depth, p.y);
  53517. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  53518. });
  53519. var totalCount = indices.length;
  53520. for (var i = 0; i < totalCount; i += 3) {
  53521. var i0 = indices[i + 0];
  53522. var i1 = indices[i + 1];
  53523. var i2 = indices[i + 2];
  53524. indices.push(i2 + positionscount);
  53525. indices.push(i1 + positionscount);
  53526. indices.push(i0 + positionscount);
  53527. }
  53528. //Add the sides
  53529. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  53530. this._holes.forEach(function (hole) {
  53531. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  53532. });
  53533. }
  53534. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  53535. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  53536. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  53537. result.setIndices(indices);
  53538. return result;
  53539. };
  53540. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  53541. var StartIndex = positions.length / 3;
  53542. var ulength = 0;
  53543. for (var i = 0; i < points.elements.length; i++) {
  53544. var p = points.elements[i];
  53545. var p1;
  53546. if ((i + 1) > points.elements.length - 1) {
  53547. p1 = points.elements[0];
  53548. }
  53549. else {
  53550. p1 = points.elements[i + 1];
  53551. }
  53552. positions.push(p.x, 0, p.y);
  53553. positions.push(p.x, -depth, p.y);
  53554. positions.push(p1.x, 0, p1.y);
  53555. positions.push(p1.x, -depth, p1.y);
  53556. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  53557. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  53558. var v3 = v2.subtract(v1);
  53559. var v4 = new BABYLON.Vector3(0, 1, 0);
  53560. var vn = BABYLON.Vector3.Cross(v3, v4);
  53561. vn = vn.normalize();
  53562. uvs.push(ulength / bounds.width, 0);
  53563. uvs.push(ulength / bounds.width, 1);
  53564. ulength += v3.length();
  53565. uvs.push((ulength / bounds.width), 0);
  53566. uvs.push((ulength / bounds.width), 1);
  53567. if (!flip) {
  53568. normals.push(-vn.x, -vn.y, -vn.z);
  53569. normals.push(-vn.x, -vn.y, -vn.z);
  53570. normals.push(-vn.x, -vn.y, -vn.z);
  53571. normals.push(-vn.x, -vn.y, -vn.z);
  53572. indices.push(StartIndex);
  53573. indices.push(StartIndex + 1);
  53574. indices.push(StartIndex + 2);
  53575. indices.push(StartIndex + 1);
  53576. indices.push(StartIndex + 3);
  53577. indices.push(StartIndex + 2);
  53578. }
  53579. else {
  53580. normals.push(vn.x, vn.y, vn.z);
  53581. normals.push(vn.x, vn.y, vn.z);
  53582. normals.push(vn.x, vn.y, vn.z);
  53583. normals.push(vn.x, vn.y, vn.z);
  53584. indices.push(StartIndex);
  53585. indices.push(StartIndex + 2);
  53586. indices.push(StartIndex + 1);
  53587. indices.push(StartIndex + 1);
  53588. indices.push(StartIndex + 2);
  53589. indices.push(StartIndex + 3);
  53590. }
  53591. StartIndex += 4;
  53592. }
  53593. ;
  53594. };
  53595. return PolygonMeshBuilder;
  53596. }());
  53597. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  53598. })(BABYLON || (BABYLON = {}));
  53599. //# sourceMappingURL=babylon.polygonMesh.js.map
  53600. var BABYLON;
  53601. (function (BABYLON) {
  53602. // Unique ID when we import meshes from Babylon to CSG
  53603. var currentCSGMeshId = 0;
  53604. // # class Vertex
  53605. // Represents a vertex of a polygon. Use your own vertex class instead of this
  53606. // one to provide additional features like texture coordinates and vertex
  53607. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  53608. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  53609. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  53610. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  53611. // is not used anywhere else.
  53612. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  53613. var Vertex = (function () {
  53614. function Vertex(pos, normal, uv) {
  53615. this.pos = pos;
  53616. this.normal = normal;
  53617. this.uv = uv;
  53618. }
  53619. Vertex.prototype.clone = function () {
  53620. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  53621. };
  53622. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  53623. // orientation of a polygon is flipped.
  53624. Vertex.prototype.flip = function () {
  53625. this.normal = this.normal.scale(-1);
  53626. };
  53627. // Create a new vertex between this vertex and `other` by linearly
  53628. // interpolating all properties using a parameter of `t`. Subclasses should
  53629. // override this to interpolate additional properties.
  53630. Vertex.prototype.interpolate = function (other, t) {
  53631. 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));
  53632. };
  53633. return Vertex;
  53634. }());
  53635. // # class Plane
  53636. // Represents a plane in 3D space.
  53637. var Plane = (function () {
  53638. function Plane(normal, w) {
  53639. this.normal = normal;
  53640. this.w = w;
  53641. }
  53642. Plane.FromPoints = function (a, b, c) {
  53643. var v0 = c.subtract(a);
  53644. var v1 = b.subtract(a);
  53645. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  53646. return null;
  53647. }
  53648. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  53649. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  53650. };
  53651. Plane.prototype.clone = function () {
  53652. return new Plane(this.normal.clone(), this.w);
  53653. };
  53654. Plane.prototype.flip = function () {
  53655. this.normal.scaleInPlace(-1);
  53656. this.w = -this.w;
  53657. };
  53658. // Split `polygon` by this plane if needed, then put the polygon or polygon
  53659. // fragments in the appropriate lists. Coplanar polygons go into either
  53660. // `coplanarFront` or `coplanarBack` depending on their orientation with
  53661. // respect to this plane. Polygons in front or in back of this plane go into
  53662. // either `front` or `back`.
  53663. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  53664. var COPLANAR = 0;
  53665. var FRONT = 1;
  53666. var BACK = 2;
  53667. var SPANNING = 3;
  53668. // Classify each point as well as the entire polygon into one of the above
  53669. // four classes.
  53670. var polygonType = 0;
  53671. var types = [];
  53672. var i;
  53673. var t;
  53674. for (i = 0; i < polygon.vertices.length; i++) {
  53675. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  53676. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  53677. polygonType |= type;
  53678. types.push(type);
  53679. }
  53680. // Put the polygon in the correct list, splitting it when necessary.
  53681. switch (polygonType) {
  53682. case COPLANAR:
  53683. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  53684. break;
  53685. case FRONT:
  53686. front.push(polygon);
  53687. break;
  53688. case BACK:
  53689. back.push(polygon);
  53690. break;
  53691. case SPANNING:
  53692. var f = [], b = [];
  53693. for (i = 0; i < polygon.vertices.length; i++) {
  53694. var j = (i + 1) % polygon.vertices.length;
  53695. var ti = types[i], tj = types[j];
  53696. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  53697. if (ti !== BACK)
  53698. f.push(vi);
  53699. if (ti !== FRONT)
  53700. b.push(ti !== BACK ? vi.clone() : vi);
  53701. if ((ti | tj) === SPANNING) {
  53702. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  53703. var v = vi.interpolate(vj, t);
  53704. f.push(v);
  53705. b.push(v.clone());
  53706. }
  53707. }
  53708. var poly;
  53709. if (f.length >= 3) {
  53710. poly = new Polygon(f, polygon.shared);
  53711. if (poly.plane)
  53712. front.push(poly);
  53713. }
  53714. if (b.length >= 3) {
  53715. poly = new Polygon(b, polygon.shared);
  53716. if (poly.plane)
  53717. back.push(poly);
  53718. }
  53719. break;
  53720. }
  53721. };
  53722. return Plane;
  53723. }());
  53724. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  53725. // point is on the plane.
  53726. Plane.EPSILON = 1e-5;
  53727. // # class Polygon
  53728. // Represents a convex polygon. The vertices used to initialize a polygon must
  53729. // be coplanar and form a convex loop.
  53730. //
  53731. // Each convex polygon has a `shared` property, which is shared between all
  53732. // polygons that are clones of each other or were split from the same polygon.
  53733. // This can be used to define per-polygon properties (such as surface color).
  53734. var Polygon = (function () {
  53735. function Polygon(vertices, shared) {
  53736. this.vertices = vertices;
  53737. this.shared = shared;
  53738. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  53739. }
  53740. Polygon.prototype.clone = function () {
  53741. var vertices = this.vertices.map(function (v) { return v.clone(); });
  53742. return new Polygon(vertices, this.shared);
  53743. };
  53744. Polygon.prototype.flip = function () {
  53745. this.vertices.reverse().map(function (v) { v.flip(); });
  53746. this.plane.flip();
  53747. };
  53748. return Polygon;
  53749. }());
  53750. // # class Node
  53751. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  53752. // by picking a polygon to split along. That polygon (and all other coplanar
  53753. // polygons) are added directly to that node and the other polygons are added to
  53754. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  53755. // no distinction between internal and leaf nodes.
  53756. var Node = (function () {
  53757. function Node(polygons) {
  53758. this.plane = null;
  53759. this.front = null;
  53760. this.back = null;
  53761. this.polygons = [];
  53762. if (polygons) {
  53763. this.build(polygons);
  53764. }
  53765. }
  53766. Node.prototype.clone = function () {
  53767. var node = new Node();
  53768. node.plane = this.plane && this.plane.clone();
  53769. node.front = this.front && this.front.clone();
  53770. node.back = this.back && this.back.clone();
  53771. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  53772. return node;
  53773. };
  53774. // Convert solid space to empty space and empty space to solid space.
  53775. Node.prototype.invert = function () {
  53776. for (var i = 0; i < this.polygons.length; i++) {
  53777. this.polygons[i].flip();
  53778. }
  53779. if (this.plane) {
  53780. this.plane.flip();
  53781. }
  53782. if (this.front) {
  53783. this.front.invert();
  53784. }
  53785. if (this.back) {
  53786. this.back.invert();
  53787. }
  53788. var temp = this.front;
  53789. this.front = this.back;
  53790. this.back = temp;
  53791. };
  53792. // Recursively remove all polygons in `polygons` that are inside this BSP
  53793. // tree.
  53794. Node.prototype.clipPolygons = function (polygons) {
  53795. if (!this.plane)
  53796. return polygons.slice();
  53797. var front = [], back = [];
  53798. for (var i = 0; i < polygons.length; i++) {
  53799. this.plane.splitPolygon(polygons[i], front, back, front, back);
  53800. }
  53801. if (this.front) {
  53802. front = this.front.clipPolygons(front);
  53803. }
  53804. if (this.back) {
  53805. back = this.back.clipPolygons(back);
  53806. }
  53807. else {
  53808. back = [];
  53809. }
  53810. return front.concat(back);
  53811. };
  53812. // Remove all polygons in this BSP tree that are inside the other BSP tree
  53813. // `bsp`.
  53814. Node.prototype.clipTo = function (bsp) {
  53815. this.polygons = bsp.clipPolygons(this.polygons);
  53816. if (this.front)
  53817. this.front.clipTo(bsp);
  53818. if (this.back)
  53819. this.back.clipTo(bsp);
  53820. };
  53821. // Return a list of all polygons in this BSP tree.
  53822. Node.prototype.allPolygons = function () {
  53823. var polygons = this.polygons.slice();
  53824. if (this.front)
  53825. polygons = polygons.concat(this.front.allPolygons());
  53826. if (this.back)
  53827. polygons = polygons.concat(this.back.allPolygons());
  53828. return polygons;
  53829. };
  53830. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  53831. // new polygons are filtered down to the bottom of the tree and become new
  53832. // nodes there. Each set of polygons is partitioned using the first polygon
  53833. // (no heuristic is used to pick a good split).
  53834. Node.prototype.build = function (polygons) {
  53835. if (!polygons.length)
  53836. return;
  53837. if (!this.plane)
  53838. this.plane = polygons[0].plane.clone();
  53839. var front = [], back = [];
  53840. for (var i = 0; i < polygons.length; i++) {
  53841. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  53842. }
  53843. if (front.length) {
  53844. if (!this.front)
  53845. this.front = new Node();
  53846. this.front.build(front);
  53847. }
  53848. if (back.length) {
  53849. if (!this.back)
  53850. this.back = new Node();
  53851. this.back.build(back);
  53852. }
  53853. };
  53854. return Node;
  53855. }());
  53856. var CSG = (function () {
  53857. function CSG() {
  53858. this.polygons = new Array();
  53859. }
  53860. // Convert BABYLON.Mesh to BABYLON.CSG
  53861. CSG.FromMesh = function (mesh) {
  53862. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  53863. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  53864. if (mesh instanceof BABYLON.Mesh) {
  53865. mesh.computeWorldMatrix(true);
  53866. matrix = mesh.getWorldMatrix();
  53867. meshPosition = mesh.position.clone();
  53868. meshRotation = mesh.rotation.clone();
  53869. if (mesh.rotationQuaternion) {
  53870. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  53871. }
  53872. meshScaling = mesh.scaling.clone();
  53873. }
  53874. else {
  53875. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  53876. }
  53877. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53878. var subMeshes = mesh.subMeshes;
  53879. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  53880. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  53881. vertices = [];
  53882. for (var j = 0; j < 3; j++) {
  53883. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  53884. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  53885. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  53886. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  53887. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  53888. vertex = new Vertex(position, normal, uv);
  53889. vertices.push(vertex);
  53890. }
  53891. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  53892. // To handle the case of degenerated triangle
  53893. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  53894. if (polygon.plane)
  53895. polygons.push(polygon);
  53896. }
  53897. }
  53898. var csg = CSG.FromPolygons(polygons);
  53899. csg.matrix = matrix;
  53900. csg.position = meshPosition;
  53901. csg.rotation = meshRotation;
  53902. csg.scaling = meshScaling;
  53903. csg.rotationQuaternion = meshRotationQuaternion;
  53904. currentCSGMeshId++;
  53905. return csg;
  53906. };
  53907. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  53908. CSG.FromPolygons = function (polygons) {
  53909. var csg = new CSG();
  53910. csg.polygons = polygons;
  53911. return csg;
  53912. };
  53913. CSG.prototype.clone = function () {
  53914. var csg = new CSG();
  53915. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  53916. csg.copyTransformAttributes(this);
  53917. return csg;
  53918. };
  53919. CSG.prototype.toPolygons = function () {
  53920. return this.polygons;
  53921. };
  53922. CSG.prototype.union = function (csg) {
  53923. var a = new Node(this.clone().polygons);
  53924. var b = new Node(csg.clone().polygons);
  53925. a.clipTo(b);
  53926. b.clipTo(a);
  53927. b.invert();
  53928. b.clipTo(a);
  53929. b.invert();
  53930. a.build(b.allPolygons());
  53931. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  53932. };
  53933. CSG.prototype.unionInPlace = function (csg) {
  53934. var a = new Node(this.polygons);
  53935. var b = new Node(csg.polygons);
  53936. a.clipTo(b);
  53937. b.clipTo(a);
  53938. b.invert();
  53939. b.clipTo(a);
  53940. b.invert();
  53941. a.build(b.allPolygons());
  53942. this.polygons = a.allPolygons();
  53943. };
  53944. CSG.prototype.subtract = function (csg) {
  53945. var a = new Node(this.clone().polygons);
  53946. var b = new Node(csg.clone().polygons);
  53947. a.invert();
  53948. a.clipTo(b);
  53949. b.clipTo(a);
  53950. b.invert();
  53951. b.clipTo(a);
  53952. b.invert();
  53953. a.build(b.allPolygons());
  53954. a.invert();
  53955. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  53956. };
  53957. CSG.prototype.subtractInPlace = function (csg) {
  53958. var a = new Node(this.polygons);
  53959. var b = new Node(csg.polygons);
  53960. a.invert();
  53961. a.clipTo(b);
  53962. b.clipTo(a);
  53963. b.invert();
  53964. b.clipTo(a);
  53965. b.invert();
  53966. a.build(b.allPolygons());
  53967. a.invert();
  53968. this.polygons = a.allPolygons();
  53969. };
  53970. CSG.prototype.intersect = function (csg) {
  53971. var a = new Node(this.clone().polygons);
  53972. var b = new Node(csg.clone().polygons);
  53973. a.invert();
  53974. b.clipTo(a);
  53975. b.invert();
  53976. a.clipTo(b);
  53977. b.clipTo(a);
  53978. a.build(b.allPolygons());
  53979. a.invert();
  53980. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  53981. };
  53982. CSG.prototype.intersectInPlace = function (csg) {
  53983. var a = new Node(this.polygons);
  53984. var b = new Node(csg.polygons);
  53985. a.invert();
  53986. b.clipTo(a);
  53987. b.invert();
  53988. a.clipTo(b);
  53989. b.clipTo(a);
  53990. a.build(b.allPolygons());
  53991. a.invert();
  53992. this.polygons = a.allPolygons();
  53993. };
  53994. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  53995. // not modified.
  53996. CSG.prototype.inverse = function () {
  53997. var csg = this.clone();
  53998. csg.inverseInPlace();
  53999. return csg;
  54000. };
  54001. CSG.prototype.inverseInPlace = function () {
  54002. this.polygons.map(function (p) { p.flip(); });
  54003. };
  54004. // This is used to keep meshes transformations so they can be restored
  54005. // when we build back a Babylon Mesh
  54006. // NB : All CSG operations are performed in world coordinates
  54007. CSG.prototype.copyTransformAttributes = function (csg) {
  54008. this.matrix = csg.matrix;
  54009. this.position = csg.position;
  54010. this.rotation = csg.rotation;
  54011. this.scaling = csg.scaling;
  54012. this.rotationQuaternion = csg.rotationQuaternion;
  54013. return this;
  54014. };
  54015. // Build Raw mesh from CSG
  54016. // Coordinates here are in world space
  54017. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  54018. var matrix = this.matrix.clone();
  54019. matrix.invert();
  54020. 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;
  54021. if (keepSubMeshes) {
  54022. // Sort Polygons, since subMeshes are indices range
  54023. polygons.sort(function (a, b) {
  54024. if (a.shared.meshId === b.shared.meshId) {
  54025. return a.shared.subMeshId - b.shared.subMeshId;
  54026. }
  54027. else {
  54028. return a.shared.meshId - b.shared.meshId;
  54029. }
  54030. });
  54031. }
  54032. for (var i = 0, il = polygons.length; i < il; i++) {
  54033. polygon = polygons[i];
  54034. // Building SubMeshes
  54035. if (!subMesh_dict[polygon.shared.meshId]) {
  54036. subMesh_dict[polygon.shared.meshId] = {};
  54037. }
  54038. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  54039. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  54040. indexStart: +Infinity,
  54041. indexEnd: -Infinity,
  54042. materialIndex: polygon.shared.materialIndex
  54043. };
  54044. }
  54045. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  54046. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  54047. polygonIndices[0] = 0;
  54048. polygonIndices[1] = j - 1;
  54049. polygonIndices[2] = j;
  54050. for (var k = 0; k < 3; k++) {
  54051. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  54052. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  54053. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  54054. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  54055. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  54056. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  54057. // Check if 2 points can be merged
  54058. if (!(typeof vertex_idx !== 'undefined' &&
  54059. normals[vertex_idx * 3] === localNormal.x &&
  54060. normals[vertex_idx * 3 + 1] === localNormal.y &&
  54061. normals[vertex_idx * 3 + 2] === localNormal.z &&
  54062. uvs[vertex_idx * 2] === uv.x &&
  54063. uvs[vertex_idx * 2 + 1] === uv.y)) {
  54064. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  54065. uvs.push(uv.x, uv.y);
  54066. normals.push(normal.x, normal.y, normal.z);
  54067. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  54068. }
  54069. indices.push(vertex_idx);
  54070. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  54071. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  54072. currentIndex++;
  54073. }
  54074. }
  54075. }
  54076. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  54077. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  54078. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  54079. mesh.setIndices(indices);
  54080. if (keepSubMeshes) {
  54081. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  54082. var materialIndexOffset = 0, materialMaxIndex;
  54083. mesh.subMeshes = new Array();
  54084. for (var m in subMesh_dict) {
  54085. materialMaxIndex = -1;
  54086. for (var sm in subMesh_dict[m]) {
  54087. subMesh_obj = subMesh_dict[m][sm];
  54088. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  54089. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  54090. }
  54091. materialIndexOffset += ++materialMaxIndex;
  54092. }
  54093. }
  54094. return mesh;
  54095. };
  54096. // Build Mesh from CSG taking material and transforms into account
  54097. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  54098. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  54099. mesh.material = material;
  54100. mesh.position.copyFrom(this.position);
  54101. mesh.rotation.copyFrom(this.rotation);
  54102. if (this.rotationQuaternion) {
  54103. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  54104. }
  54105. mesh.scaling.copyFrom(this.scaling);
  54106. mesh.computeWorldMatrix(true);
  54107. return mesh;
  54108. };
  54109. return CSG;
  54110. }());
  54111. BABYLON.CSG = CSG;
  54112. })(BABYLON || (BABYLON = {}));
  54113. //# sourceMappingURL=babylon.csg.js.map
  54114. var BABYLON;
  54115. (function (BABYLON) {
  54116. var LensFlare = (function () {
  54117. function LensFlare(size, position, color, imgUrl, system) {
  54118. this.size = size;
  54119. this.position = position;
  54120. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  54121. this.dispose = function () {
  54122. if (this.texture) {
  54123. this.texture.dispose();
  54124. }
  54125. // Remove from scene
  54126. var index = this._system.lensFlares.indexOf(this);
  54127. this._system.lensFlares.splice(index, 1);
  54128. };
  54129. this.color = color || new BABYLON.Color3(1, 1, 1);
  54130. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  54131. this._system = system;
  54132. system.lensFlares.push(this);
  54133. }
  54134. return LensFlare;
  54135. }());
  54136. BABYLON.LensFlare = LensFlare;
  54137. })(BABYLON || (BABYLON = {}));
  54138. //# sourceMappingURL=babylon.lensFlare.js.map
  54139. var BABYLON;
  54140. (function (BABYLON) {
  54141. var LensFlareSystem = (function () {
  54142. function LensFlareSystem(name, emitter, scene) {
  54143. this.name = name;
  54144. this.lensFlares = new Array();
  54145. this.borderLimit = 300;
  54146. this.viewportBorder = 0;
  54147. this.layerMask = 0x0FFFFFFF;
  54148. this._vertexBuffers = {};
  54149. this._isEnabled = true;
  54150. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54151. this._emitter = emitter;
  54152. this.id = name;
  54153. scene.lensFlareSystems.push(this);
  54154. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  54155. var engine = scene.getEngine();
  54156. // VBO
  54157. var vertices = [];
  54158. vertices.push(1, 1);
  54159. vertices.push(-1, 1);
  54160. vertices.push(-1, -1);
  54161. vertices.push(1, -1);
  54162. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  54163. // Indices
  54164. var indices = [];
  54165. indices.push(0);
  54166. indices.push(1);
  54167. indices.push(2);
  54168. indices.push(0);
  54169. indices.push(2);
  54170. indices.push(3);
  54171. this._indexBuffer = engine.createIndexBuffer(indices);
  54172. // Effects
  54173. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  54174. }
  54175. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  54176. get: function () {
  54177. return this._isEnabled;
  54178. },
  54179. set: function (value) {
  54180. this._isEnabled = value;
  54181. },
  54182. enumerable: true,
  54183. configurable: true
  54184. });
  54185. LensFlareSystem.prototype.getScene = function () {
  54186. return this._scene;
  54187. };
  54188. LensFlareSystem.prototype.getEmitter = function () {
  54189. return this._emitter;
  54190. };
  54191. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  54192. this._emitter = newEmitter;
  54193. };
  54194. LensFlareSystem.prototype.getEmitterPosition = function () {
  54195. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  54196. };
  54197. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  54198. var position = this.getEmitterPosition();
  54199. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  54200. this._positionX = position.x;
  54201. this._positionY = position.y;
  54202. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  54203. if (this.viewportBorder > 0) {
  54204. globalViewport.x -= this.viewportBorder;
  54205. globalViewport.y -= this.viewportBorder;
  54206. globalViewport.width += this.viewportBorder * 2;
  54207. globalViewport.height += this.viewportBorder * 2;
  54208. position.x += this.viewportBorder;
  54209. position.y += this.viewportBorder;
  54210. this._positionX += this.viewportBorder;
  54211. this._positionY += this.viewportBorder;
  54212. }
  54213. if (position.z > 0) {
  54214. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  54215. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  54216. return true;
  54217. }
  54218. return true;
  54219. }
  54220. return false;
  54221. };
  54222. LensFlareSystem.prototype._isVisible = function () {
  54223. if (!this._isEnabled) {
  54224. return false;
  54225. }
  54226. var emitterPosition = this.getEmitterPosition();
  54227. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  54228. var distance = direction.length();
  54229. direction.normalize();
  54230. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  54231. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  54232. return !pickInfo.hit || pickInfo.distance > distance;
  54233. };
  54234. LensFlareSystem.prototype.render = function () {
  54235. if (!this._effect.isReady())
  54236. return false;
  54237. var engine = this._scene.getEngine();
  54238. var viewport = this._scene.activeCamera.viewport;
  54239. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  54240. // Position
  54241. if (!this.computeEffectivePosition(globalViewport)) {
  54242. return false;
  54243. }
  54244. // Visibility
  54245. if (!this._isVisible()) {
  54246. return false;
  54247. }
  54248. // Intensity
  54249. var awayX;
  54250. var awayY;
  54251. if (this._positionX < this.borderLimit + globalViewport.x) {
  54252. awayX = this.borderLimit + globalViewport.x - this._positionX;
  54253. }
  54254. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  54255. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  54256. }
  54257. else {
  54258. awayX = 0;
  54259. }
  54260. if (this._positionY < this.borderLimit + globalViewport.y) {
  54261. awayY = this.borderLimit + globalViewport.y - this._positionY;
  54262. }
  54263. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  54264. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  54265. }
  54266. else {
  54267. awayY = 0;
  54268. }
  54269. var away = (awayX > awayY) ? awayX : awayY;
  54270. away -= this.viewportBorder;
  54271. if (away > this.borderLimit) {
  54272. away = this.borderLimit;
  54273. }
  54274. var intensity = 1.0 - (away / this.borderLimit);
  54275. if (intensity < 0) {
  54276. return false;
  54277. }
  54278. if (intensity > 1.0) {
  54279. intensity = 1.0;
  54280. }
  54281. if (this.viewportBorder > 0) {
  54282. globalViewport.x += this.viewportBorder;
  54283. globalViewport.y += this.viewportBorder;
  54284. globalViewport.width -= this.viewportBorder * 2;
  54285. globalViewport.height -= this.viewportBorder * 2;
  54286. this._positionX -= this.viewportBorder;
  54287. this._positionY -= this.viewportBorder;
  54288. }
  54289. // Position
  54290. var centerX = globalViewport.x + globalViewport.width / 2;
  54291. var centerY = globalViewport.y + globalViewport.height / 2;
  54292. var distX = centerX - this._positionX;
  54293. var distY = centerY - this._positionY;
  54294. // Effects
  54295. engine.enableEffect(this._effect);
  54296. engine.setState(false);
  54297. engine.setDepthBuffer(false);
  54298. // VBOs
  54299. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54300. // Flares
  54301. for (var index = 0; index < this.lensFlares.length; index++) {
  54302. var flare = this.lensFlares[index];
  54303. engine.setAlphaMode(flare.alphaMode);
  54304. var x = centerX - (distX * flare.position);
  54305. var y = centerY - (distY * flare.position);
  54306. var cw = flare.size;
  54307. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  54308. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  54309. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  54310. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  54311. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  54312. // Texture
  54313. this._effect.setTexture("textureSampler", flare.texture);
  54314. // Color
  54315. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  54316. // Draw order
  54317. engine.draw(true, 0, 6);
  54318. }
  54319. engine.setDepthBuffer(true);
  54320. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54321. return true;
  54322. };
  54323. LensFlareSystem.prototype.dispose = function () {
  54324. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54325. if (vertexBuffer) {
  54326. vertexBuffer.dispose();
  54327. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  54328. }
  54329. if (this._indexBuffer) {
  54330. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54331. this._indexBuffer = null;
  54332. }
  54333. while (this.lensFlares.length) {
  54334. this.lensFlares[0].dispose();
  54335. }
  54336. // Remove from scene
  54337. var index = this._scene.lensFlareSystems.indexOf(this);
  54338. this._scene.lensFlareSystems.splice(index, 1);
  54339. };
  54340. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  54341. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  54342. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  54343. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  54344. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  54345. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  54346. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  54347. var parsedFlare = parsedLensFlareSystem.flares[index];
  54348. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  54349. }
  54350. return lensFlareSystem;
  54351. };
  54352. LensFlareSystem.prototype.serialize = function () {
  54353. var serializationObject = {};
  54354. serializationObject.id = this.id;
  54355. serializationObject.name = this.name;
  54356. serializationObject.emitterId = this.getEmitter().id;
  54357. serializationObject.borderLimit = this.borderLimit;
  54358. serializationObject.flares = [];
  54359. for (var index = 0; index < this.lensFlares.length; index++) {
  54360. var flare = this.lensFlares[index];
  54361. serializationObject.flares.push({
  54362. size: flare.size,
  54363. position: flare.position,
  54364. color: flare.color.asArray(),
  54365. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  54366. });
  54367. }
  54368. return serializationObject;
  54369. };
  54370. return LensFlareSystem;
  54371. }());
  54372. BABYLON.LensFlareSystem = LensFlareSystem;
  54373. })(BABYLON || (BABYLON = {}));
  54374. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  54375. var BABYLON;
  54376. (function (BABYLON) {
  54377. /**
  54378. * This is a holder class for the physics joint created by the physics plugin.
  54379. * It holds a set of functions to control the underlying joint.
  54380. */
  54381. var PhysicsJoint = (function () {
  54382. function PhysicsJoint(type, jointData) {
  54383. this.type = type;
  54384. this.jointData = jointData;
  54385. jointData.nativeParams = jointData.nativeParams || {};
  54386. }
  54387. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  54388. get: function () {
  54389. return this._physicsJoint;
  54390. },
  54391. set: function (newJoint) {
  54392. if (this._physicsJoint) {
  54393. //remove from the wolrd
  54394. }
  54395. this._physicsJoint = newJoint;
  54396. },
  54397. enumerable: true,
  54398. configurable: true
  54399. });
  54400. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  54401. set: function (physicsPlugin) {
  54402. this._physicsPlugin = physicsPlugin;
  54403. },
  54404. enumerable: true,
  54405. configurable: true
  54406. });
  54407. /**
  54408. * Execute a function that is physics-plugin specific.
  54409. * @param {Function} func the function that will be executed.
  54410. * It accepts two parameters: the physics world and the physics joint.
  54411. */
  54412. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  54413. func(this._physicsPlugin.world, this._physicsJoint);
  54414. };
  54415. return PhysicsJoint;
  54416. }());
  54417. //TODO check if the native joints are the same
  54418. //Joint Types
  54419. PhysicsJoint.DistanceJoint = 0;
  54420. PhysicsJoint.HingeJoint = 1;
  54421. PhysicsJoint.BallAndSocketJoint = 2;
  54422. PhysicsJoint.WheelJoint = 3;
  54423. PhysicsJoint.SliderJoint = 4;
  54424. //OIMO
  54425. PhysicsJoint.PrismaticJoint = 5;
  54426. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  54427. PhysicsJoint.UniversalJoint = 6;
  54428. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  54429. //Cannon
  54430. //Similar to a Ball-Joint. Different in params
  54431. PhysicsJoint.PointToPointJoint = 8;
  54432. //Cannon only at the moment
  54433. PhysicsJoint.SpringJoint = 9;
  54434. PhysicsJoint.LockJoint = 10;
  54435. BABYLON.PhysicsJoint = PhysicsJoint;
  54436. /**
  54437. * A class representing a physics distance joint.
  54438. */
  54439. var DistanceJoint = (function (_super) {
  54440. __extends(DistanceJoint, _super);
  54441. function DistanceJoint(jointData) {
  54442. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  54443. }
  54444. /**
  54445. * Update the predefined distance.
  54446. */
  54447. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  54448. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  54449. };
  54450. return DistanceJoint;
  54451. }(PhysicsJoint));
  54452. BABYLON.DistanceJoint = DistanceJoint;
  54453. var MotorEnabledJoint = (function (_super) {
  54454. __extends(MotorEnabledJoint, _super);
  54455. function MotorEnabledJoint(type, jointData) {
  54456. return _super.call(this, type, jointData) || this;
  54457. }
  54458. /**
  54459. * Set the motor values.
  54460. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54461. * @param {number} force the force to apply
  54462. * @param {number} maxForce max force for this motor.
  54463. */
  54464. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  54465. this._physicsPlugin.setMotor(this, force, maxForce);
  54466. };
  54467. /**
  54468. * Set the motor's limits.
  54469. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54470. */
  54471. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  54472. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  54473. };
  54474. return MotorEnabledJoint;
  54475. }(PhysicsJoint));
  54476. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  54477. /**
  54478. * This class represents a single hinge physics joint
  54479. */
  54480. var HingeJoint = (function (_super) {
  54481. __extends(HingeJoint, _super);
  54482. function HingeJoint(jointData) {
  54483. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  54484. }
  54485. /**
  54486. * Set the motor values.
  54487. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54488. * @param {number} force the force to apply
  54489. * @param {number} maxForce max force for this motor.
  54490. */
  54491. HingeJoint.prototype.setMotor = function (force, maxForce) {
  54492. this._physicsPlugin.setMotor(this, force, maxForce);
  54493. };
  54494. /**
  54495. * Set the motor's limits.
  54496. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54497. */
  54498. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  54499. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  54500. };
  54501. return HingeJoint;
  54502. }(MotorEnabledJoint));
  54503. BABYLON.HingeJoint = HingeJoint;
  54504. /**
  54505. * This class represents a dual hinge physics joint (same as wheel joint)
  54506. */
  54507. var Hinge2Joint = (function (_super) {
  54508. __extends(Hinge2Joint, _super);
  54509. function Hinge2Joint(jointData) {
  54510. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  54511. }
  54512. /**
  54513. * Set the motor values.
  54514. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54515. * @param {number} force the force to apply
  54516. * @param {number} maxForce max force for this motor.
  54517. * @param {motorIndex} the motor's index, 0 or 1.
  54518. */
  54519. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  54520. if (motorIndex === void 0) { motorIndex = 0; }
  54521. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  54522. };
  54523. /**
  54524. * Set the motor limits.
  54525. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54526. * @param {number} upperLimit the upper limit
  54527. * @param {number} lowerLimit lower limit
  54528. * @param {motorIndex} the motor's index, 0 or 1.
  54529. */
  54530. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  54531. if (motorIndex === void 0) { motorIndex = 0; }
  54532. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  54533. };
  54534. return Hinge2Joint;
  54535. }(MotorEnabledJoint));
  54536. BABYLON.Hinge2Joint = Hinge2Joint;
  54537. })(BABYLON || (BABYLON = {}));
  54538. //# sourceMappingURL=babylon.physicsJoint.js.map
  54539. var BABYLON;
  54540. (function (BABYLON) {
  54541. var PhysicsImpostor = (function () {
  54542. function PhysicsImpostor(object, type, _options, _scene) {
  54543. if (_options === void 0) { _options = { mass: 0 }; }
  54544. var _this = this;
  54545. this.object = object;
  54546. this.type = type;
  54547. this._options = _options;
  54548. this._scene = _scene;
  54549. this._bodyUpdateRequired = false;
  54550. this._onBeforePhysicsStepCallbacks = new Array();
  54551. this._onAfterPhysicsStepCallbacks = new Array();
  54552. this._onPhysicsCollideCallbacks = [];
  54553. this._deltaPosition = BABYLON.Vector3.Zero();
  54554. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  54555. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  54556. /**
  54557. * this function is executed by the physics engine.
  54558. */
  54559. this.beforeStep = function () {
  54560. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  54561. //conjugate deltaRotation
  54562. if (_this._deltaRotationConjugated) {
  54563. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  54564. }
  54565. else {
  54566. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  54567. }
  54568. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  54569. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  54570. func(_this);
  54571. });
  54572. };
  54573. /**
  54574. * this function is executed by the physics engine.
  54575. */
  54576. this.afterStep = function () {
  54577. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  54578. func(_this);
  54579. });
  54580. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  54581. _this.object.position.addInPlace(_this._deltaPosition);
  54582. if (_this._deltaRotation) {
  54583. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  54584. }
  54585. };
  54586. /**
  54587. * Legacy collision detection event support
  54588. */
  54589. this.onCollideEvent = null;
  54590. //event and body object due to cannon's event-based architecture.
  54591. this.onCollide = function (e) {
  54592. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  54593. return;
  54594. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  54595. if (otherImpostor) {
  54596. // Legacy collision detection event support
  54597. if (_this.onCollideEvent) {
  54598. _this.onCollideEvent(_this, otherImpostor);
  54599. }
  54600. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  54601. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  54602. }).forEach(function (obj) {
  54603. obj.callback(_this, otherImpostor);
  54604. });
  54605. }
  54606. };
  54607. //sanity check!
  54608. if (!this.object) {
  54609. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  54610. return;
  54611. }
  54612. //legacy support for old syntax.
  54613. if (!this._scene && object.getScene) {
  54614. this._scene = object.getScene();
  54615. }
  54616. this._physicsEngine = this._scene.getPhysicsEngine();
  54617. if (!this._physicsEngine) {
  54618. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  54619. }
  54620. else {
  54621. //set the object's quaternion, if not set
  54622. if (!this.object.rotationQuaternion) {
  54623. if (this.object.rotation) {
  54624. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  54625. }
  54626. else {
  54627. this.object.rotationQuaternion = new BABYLON.Quaternion();
  54628. }
  54629. }
  54630. //default options params
  54631. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  54632. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  54633. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  54634. this._joints = [];
  54635. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  54636. if (!this.object.parent) {
  54637. this._init();
  54638. }
  54639. }
  54640. }
  54641. /**
  54642. * This function will completly initialize this impostor.
  54643. * It will create a new body - but only if this mesh has no parent.
  54644. * If it has, this impostor will not be used other than to define the impostor
  54645. * of the child mesh.
  54646. */
  54647. PhysicsImpostor.prototype._init = function () {
  54648. this._physicsEngine.removeImpostor(this);
  54649. this.physicsBody = null;
  54650. this._parent = this._parent || this._getPhysicsParent();
  54651. if (!this.parent) {
  54652. this._physicsEngine.addImpostor(this);
  54653. }
  54654. };
  54655. PhysicsImpostor.prototype._getPhysicsParent = function () {
  54656. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  54657. var parentMesh = this.object.parent;
  54658. return parentMesh.physicsImpostor;
  54659. }
  54660. return;
  54661. };
  54662. /**
  54663. * Should a new body be generated.
  54664. */
  54665. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  54666. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  54667. };
  54668. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  54669. this.forceUpdate();
  54670. };
  54671. /**
  54672. * Force a regeneration of this or the parent's impostor's body.
  54673. * Use under cautious - This will remove all joints already implemented.
  54674. */
  54675. PhysicsImpostor.prototype.forceUpdate = function () {
  54676. this._init();
  54677. if (this.parent) {
  54678. this.parent.forceUpdate();
  54679. }
  54680. };
  54681. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  54682. /*public get mesh(): AbstractMesh {
  54683. return this._mesh;
  54684. }*/
  54685. /**
  54686. * Gets the body that holds this impostor. Either its own, or its parent.
  54687. */
  54688. get: function () {
  54689. return this._parent ? this._parent.physicsBody : this._physicsBody;
  54690. },
  54691. /**
  54692. * Set the physics body. Used mainly by the physics engine/plugin
  54693. */
  54694. set: function (physicsBody) {
  54695. if (this._physicsBody) {
  54696. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  54697. }
  54698. this._physicsBody = physicsBody;
  54699. this.resetUpdateFlags();
  54700. },
  54701. enumerable: true,
  54702. configurable: true
  54703. });
  54704. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  54705. get: function () {
  54706. return this._parent;
  54707. },
  54708. set: function (value) {
  54709. this._parent = value;
  54710. },
  54711. enumerable: true,
  54712. configurable: true
  54713. });
  54714. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  54715. this._bodyUpdateRequired = false;
  54716. };
  54717. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  54718. if (this.object.getBoundingInfo) {
  54719. var q = this.object.rotationQuaternion;
  54720. //reset rotation
  54721. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  54722. //calculate the world matrix with no rotation
  54723. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  54724. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  54725. //bring back the rotation
  54726. this.object.rotationQuaternion = q;
  54727. //calculate the world matrix with the new rotation
  54728. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  54729. return size;
  54730. }
  54731. else {
  54732. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  54733. }
  54734. };
  54735. PhysicsImpostor.prototype.getObjectCenter = function () {
  54736. if (this.object.getBoundingInfo) {
  54737. return this.object.getBoundingInfo().boundingBox.centerWorld;
  54738. }
  54739. else {
  54740. return this.object.position;
  54741. }
  54742. };
  54743. /**
  54744. * Get a specific parametes from the options parameter.
  54745. */
  54746. PhysicsImpostor.prototype.getParam = function (paramName) {
  54747. return this._options[paramName];
  54748. };
  54749. /**
  54750. * Sets a specific parameter in the options given to the physics plugin
  54751. */
  54752. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  54753. this._options[paramName] = value;
  54754. this._bodyUpdateRequired = true;
  54755. };
  54756. /**
  54757. * Specifically change the body's mass option. Won't recreate the physics body object
  54758. */
  54759. PhysicsImpostor.prototype.setMass = function (mass) {
  54760. if (this.getParam("mass") !== mass) {
  54761. this.setParam("mass", mass);
  54762. }
  54763. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  54764. };
  54765. PhysicsImpostor.prototype.getLinearVelocity = function () {
  54766. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  54767. };
  54768. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  54769. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  54770. };
  54771. PhysicsImpostor.prototype.getAngularVelocity = function () {
  54772. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  54773. };
  54774. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  54775. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  54776. };
  54777. /**
  54778. * Execute a function with the physics plugin native code.
  54779. * Provide a function the will have two variables - the world object and the physics body object.
  54780. */
  54781. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  54782. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  54783. };
  54784. /**
  54785. * Register a function that will be executed before the physics world is stepping forward.
  54786. */
  54787. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  54788. this._onBeforePhysicsStepCallbacks.push(func);
  54789. };
  54790. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  54791. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  54792. if (index > -1) {
  54793. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  54794. }
  54795. else {
  54796. BABYLON.Tools.Warn("Function to remove was not found");
  54797. }
  54798. };
  54799. /**
  54800. * Register a function that will be executed after the physics step
  54801. */
  54802. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  54803. this._onAfterPhysicsStepCallbacks.push(func);
  54804. };
  54805. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  54806. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  54807. if (index > -1) {
  54808. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  54809. }
  54810. else {
  54811. BABYLON.Tools.Warn("Function to remove was not found");
  54812. }
  54813. };
  54814. /**
  54815. * register a function that will be executed when this impostor collides against a different body.
  54816. */
  54817. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  54818. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  54819. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  54820. };
  54821. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  54822. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  54823. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  54824. if (index > -1) {
  54825. this._onPhysicsCollideCallbacks.splice(index, 1);
  54826. }
  54827. else {
  54828. BABYLON.Tools.Warn("Function to remove was not found");
  54829. }
  54830. };
  54831. /**
  54832. * Apply a force
  54833. */
  54834. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  54835. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  54836. };
  54837. /**
  54838. * Apply an impulse
  54839. */
  54840. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  54841. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  54842. };
  54843. /**
  54844. * A help function to create a joint.
  54845. */
  54846. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  54847. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  54848. this.addJoint(otherImpostor, joint);
  54849. };
  54850. /**
  54851. * Add a joint to this impostor with a different impostor.
  54852. */
  54853. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  54854. this._joints.push({
  54855. otherImpostor: otherImpostor,
  54856. joint: joint
  54857. });
  54858. this._physicsEngine.addJoint(this, otherImpostor, joint);
  54859. };
  54860. /**
  54861. * Will keep this body still, in a sleep mode.
  54862. */
  54863. PhysicsImpostor.prototype.sleep = function () {
  54864. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  54865. };
  54866. /**
  54867. * Wake the body up.
  54868. */
  54869. PhysicsImpostor.prototype.wakeUp = function () {
  54870. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  54871. };
  54872. PhysicsImpostor.prototype.clone = function (newObject) {
  54873. if (!newObject)
  54874. return null;
  54875. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  54876. };
  54877. PhysicsImpostor.prototype.dispose = function () {
  54878. var _this = this;
  54879. //no dispose if no physics engine is available.
  54880. if (!this._physicsEngine) {
  54881. return;
  54882. }
  54883. this._joints.forEach(function (j) {
  54884. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  54885. });
  54886. //dispose the physics body
  54887. this._physicsEngine.removeImpostor(this);
  54888. if (this.parent) {
  54889. this.parent.forceUpdate();
  54890. }
  54891. else {
  54892. /*this._object.getChildMeshes().forEach(function(mesh) {
  54893. if (mesh.physicsImpostor) {
  54894. if (disposeChildren) {
  54895. mesh.physicsImpostor.dispose();
  54896. mesh.physicsImpostor = null;
  54897. }
  54898. }
  54899. })*/
  54900. }
  54901. };
  54902. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  54903. this._deltaPosition.copyFrom(position);
  54904. };
  54905. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  54906. if (!this._deltaRotation) {
  54907. this._deltaRotation = new BABYLON.Quaternion();
  54908. }
  54909. this._deltaRotation.copyFrom(rotation);
  54910. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  54911. };
  54912. return PhysicsImpostor;
  54913. }());
  54914. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  54915. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  54916. //Impostor types
  54917. PhysicsImpostor.NoImpostor = 0;
  54918. PhysicsImpostor.SphereImpostor = 1;
  54919. PhysicsImpostor.BoxImpostor = 2;
  54920. PhysicsImpostor.PlaneImpostor = 3;
  54921. PhysicsImpostor.MeshImpostor = 4;
  54922. PhysicsImpostor.CylinderImpostor = 7;
  54923. PhysicsImpostor.ParticleImpostor = 8;
  54924. PhysicsImpostor.HeightmapImpostor = 9;
  54925. BABYLON.PhysicsImpostor = PhysicsImpostor;
  54926. })(BABYLON || (BABYLON = {}));
  54927. //# sourceMappingURL=babylon.physicsImpostor.js.map
  54928. var BABYLON;
  54929. (function (BABYLON) {
  54930. var PhysicsEngine = (function () {
  54931. function PhysicsEngine(gravity, _physicsPlugin) {
  54932. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  54933. this._physicsPlugin = _physicsPlugin;
  54934. //new methods and parameters
  54935. this._impostors = [];
  54936. this._joints = [];
  54937. if (!this._physicsPlugin.isSupported()) {
  54938. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  54939. + "Please make sure it is included.");
  54940. }
  54941. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  54942. this.setGravity(gravity);
  54943. this.setTimeStep();
  54944. }
  54945. PhysicsEngine.prototype.setGravity = function (gravity) {
  54946. this.gravity = gravity;
  54947. this._physicsPlugin.setGravity(this.gravity);
  54948. };
  54949. /**
  54950. * Set the time step of the physics engine.
  54951. * default is 1/60.
  54952. * To slow it down, enter 1/600 for example.
  54953. * To speed it up, 1/30
  54954. * @param {number} newTimeStep the new timestep to apply to this world.
  54955. */
  54956. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  54957. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  54958. this._physicsPlugin.setTimeStep(newTimeStep);
  54959. };
  54960. PhysicsEngine.prototype.dispose = function () {
  54961. this._impostors.forEach(function (impostor) {
  54962. impostor.dispose();
  54963. });
  54964. this._physicsPlugin.dispose();
  54965. };
  54966. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  54967. return this._physicsPlugin.name;
  54968. };
  54969. /**
  54970. * Adding a new impostor for the impostor tracking.
  54971. * This will be done by the impostor itself.
  54972. * @param {PhysicsImpostor} impostor the impostor to add
  54973. */
  54974. PhysicsEngine.prototype.addImpostor = function (impostor) {
  54975. impostor.uniqueId = this._impostors.push(impostor);
  54976. //if no parent, generate the body
  54977. if (!impostor.parent) {
  54978. this._physicsPlugin.generatePhysicsBody(impostor);
  54979. }
  54980. };
  54981. /**
  54982. * Remove an impostor from the engine.
  54983. * This impostor and its mesh will not longer be updated by the physics engine.
  54984. * @param {PhysicsImpostor} impostor the impostor to remove
  54985. */
  54986. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  54987. var index = this._impostors.indexOf(impostor);
  54988. if (index > -1) {
  54989. var removed = this._impostors.splice(index, 1);
  54990. //Is it needed?
  54991. if (removed.length) {
  54992. //this will also remove it from the world.
  54993. removed[0].physicsBody = null;
  54994. }
  54995. }
  54996. };
  54997. /**
  54998. * Add a joint to the physics engine
  54999. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  55000. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  55001. * @param {PhysicsJoint} the joint that will connect both impostors.
  55002. */
  55003. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  55004. var impostorJoint = {
  55005. mainImpostor: mainImpostor,
  55006. connectedImpostor: connectedImpostor,
  55007. joint: joint
  55008. };
  55009. joint.physicsPlugin = this._physicsPlugin;
  55010. this._joints.push(impostorJoint);
  55011. this._physicsPlugin.generateJoint(impostorJoint);
  55012. };
  55013. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  55014. var matchingJoints = this._joints.filter(function (impostorJoint) {
  55015. return (impostorJoint.connectedImpostor === connectedImpostor
  55016. && impostorJoint.joint === joint
  55017. && impostorJoint.mainImpostor === mainImpostor);
  55018. });
  55019. if (matchingJoints.length) {
  55020. this._physicsPlugin.removeJoint(matchingJoints[0]);
  55021. //TODO remove it from the list as well
  55022. }
  55023. };
  55024. /**
  55025. * Called by the scene. no need to call it.
  55026. */
  55027. PhysicsEngine.prototype._step = function (delta) {
  55028. var _this = this;
  55029. //check if any mesh has no body / requires an update
  55030. this._impostors.forEach(function (impostor) {
  55031. if (impostor.isBodyInitRequired()) {
  55032. _this._physicsPlugin.generatePhysicsBody(impostor);
  55033. }
  55034. });
  55035. if (delta > 0.1) {
  55036. delta = 0.1;
  55037. }
  55038. else if (delta <= 0) {
  55039. delta = 1.0 / 60.0;
  55040. }
  55041. this._physicsPlugin.executeStep(delta, this._impostors);
  55042. };
  55043. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  55044. return this._physicsPlugin;
  55045. };
  55046. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  55047. for (var i = 0; i < this._impostors.length; ++i) {
  55048. if (this._impostors[i].object === object) {
  55049. return this._impostors[i];
  55050. }
  55051. }
  55052. };
  55053. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  55054. for (var i = 0; i < this._impostors.length; ++i) {
  55055. if (this._impostors[i].physicsBody === body) {
  55056. return this._impostors[i];
  55057. }
  55058. }
  55059. };
  55060. return PhysicsEngine;
  55061. }());
  55062. // Statics
  55063. PhysicsEngine.Epsilon = 0.001;
  55064. BABYLON.PhysicsEngine = PhysicsEngine;
  55065. })(BABYLON || (BABYLON = {}));
  55066. //# sourceMappingURL=babylon.physicsEngine.js.map
  55067. var BABYLON;
  55068. (function (BABYLON) {
  55069. var CannonJSPlugin = (function () {
  55070. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  55071. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  55072. if (iterations === void 0) { iterations = 10; }
  55073. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  55074. this.name = "CannonJSPlugin";
  55075. this._physicsMaterials = [];
  55076. this._fixedTimeStep = 1 / 60;
  55077. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  55078. this._currentCollisionGroup = 2;
  55079. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  55080. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  55081. this._tmpPosition = BABYLON.Vector3.Zero();
  55082. this._tmpQuaternion = new BABYLON.Quaternion();
  55083. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  55084. this._tmpDeltaRotation = new BABYLON.Quaternion();
  55085. this._tmpUnityRotation = new BABYLON.Quaternion();
  55086. if (!this.isSupported()) {
  55087. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  55088. return;
  55089. }
  55090. this.world = new CANNON.World();
  55091. this.world.broadphase = new CANNON.NaiveBroadphase();
  55092. this.world.solver.iterations = iterations;
  55093. }
  55094. CannonJSPlugin.prototype.setGravity = function (gravity) {
  55095. this.world.gravity.copy(gravity);
  55096. };
  55097. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  55098. this._fixedTimeStep = timeStep;
  55099. };
  55100. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  55101. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  55102. };
  55103. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  55104. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  55105. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  55106. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  55107. };
  55108. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  55109. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  55110. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  55111. impostor.physicsBody.applyForce(impulse, worldPoint);
  55112. };
  55113. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  55114. //parent-child relationship. Does this impostor has a parent impostor?
  55115. if (impostor.parent) {
  55116. if (impostor.physicsBody) {
  55117. this.removePhysicsBody(impostor);
  55118. //TODO is that needed?
  55119. impostor.forceUpdate();
  55120. }
  55121. return;
  55122. }
  55123. //should a new body be created for this impostor?
  55124. if (impostor.isBodyInitRequired()) {
  55125. var shape = this._createShape(impostor);
  55126. //unregister events, if body is being changed
  55127. var oldBody = impostor.physicsBody;
  55128. if (oldBody) {
  55129. this.removePhysicsBody(impostor);
  55130. }
  55131. //create the body and material
  55132. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  55133. var bodyCreationObject = {
  55134. mass: impostor.getParam("mass"),
  55135. material: material
  55136. };
  55137. // A simple extend, in case native options were used.
  55138. var nativeOptions = impostor.getParam("nativeOptions");
  55139. for (var key in nativeOptions) {
  55140. if (nativeOptions.hasOwnProperty(key)) {
  55141. bodyCreationObject[key] = nativeOptions[key];
  55142. }
  55143. }
  55144. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  55145. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  55146. this.world.addEventListener("preStep", impostor.beforeStep);
  55147. this.world.addEventListener("postStep", impostor.afterStep);
  55148. impostor.physicsBody.addShape(shape);
  55149. this.world.add(impostor.physicsBody);
  55150. //try to keep the body moving in the right direction by taking old properties.
  55151. //Should be tested!
  55152. if (oldBody) {
  55153. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  55154. impostor.physicsBody[param].copy(oldBody[param]);
  55155. });
  55156. }
  55157. this._processChildMeshes(impostor);
  55158. }
  55159. //now update the body's transformation
  55160. this._updatePhysicsBodyTransformation(impostor);
  55161. };
  55162. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  55163. var _this = this;
  55164. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  55165. if (meshChildren.length) {
  55166. var processMesh = function (localPosition, mesh) {
  55167. var childImpostor = mesh.getPhysicsImpostor();
  55168. if (childImpostor) {
  55169. var parent = childImpostor.parent;
  55170. if (parent !== mainImpostor) {
  55171. var localPosition = mesh.position;
  55172. if (childImpostor.physicsBody) {
  55173. _this.removePhysicsBody(childImpostor);
  55174. childImpostor.physicsBody = null;
  55175. }
  55176. childImpostor.parent = mainImpostor;
  55177. childImpostor.resetUpdateFlags();
  55178. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  55179. //Add the mass of the children.
  55180. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  55181. }
  55182. }
  55183. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  55184. };
  55185. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  55186. }
  55187. };
  55188. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  55189. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  55190. this.world.removeEventListener("preStep", impostor.beforeStep);
  55191. this.world.removeEventListener("postStep", impostor.afterStep);
  55192. this.world.remove(impostor.physicsBody);
  55193. };
  55194. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  55195. var mainBody = impostorJoint.mainImpostor.physicsBody;
  55196. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  55197. if (!mainBody || !connectedBody) {
  55198. return;
  55199. }
  55200. var constraint;
  55201. var jointData = impostorJoint.joint.jointData;
  55202. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  55203. var constraintData = {
  55204. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  55205. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  55206. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  55207. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  55208. maxForce: jointData.nativeParams.maxForce,
  55209. collideConnected: !!jointData.collision
  55210. };
  55211. switch (impostorJoint.joint.type) {
  55212. case BABYLON.PhysicsJoint.HingeJoint:
  55213. case BABYLON.PhysicsJoint.Hinge2Joint:
  55214. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  55215. break;
  55216. case BABYLON.PhysicsJoint.DistanceJoint:
  55217. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  55218. break;
  55219. case BABYLON.PhysicsJoint.SpringJoint:
  55220. var springData = jointData;
  55221. constraint = new CANNON.Spring(mainBody, connectedBody, {
  55222. restLength: springData.length,
  55223. stiffness: springData.stiffness,
  55224. damping: springData.damping,
  55225. localAnchorA: constraintData.pivotA,
  55226. localAnchorB: constraintData.pivotB
  55227. });
  55228. break;
  55229. case BABYLON.PhysicsJoint.LockJoint:
  55230. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  55231. break;
  55232. case BABYLON.PhysicsJoint.PointToPointJoint:
  55233. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  55234. default:
  55235. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  55236. break;
  55237. }
  55238. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  55239. constraint.collideConnected = !!jointData.collision;
  55240. impostorJoint.joint.physicsJoint = constraint;
  55241. //don't add spring as constraint, as it is not one.
  55242. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  55243. this.world.addConstraint(constraint);
  55244. }
  55245. else {
  55246. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  55247. constraint.applyForce();
  55248. });
  55249. }
  55250. };
  55251. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  55252. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  55253. };
  55254. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  55255. var index;
  55256. var mat;
  55257. for (index = 0; index < this._physicsMaterials.length; index++) {
  55258. mat = this._physicsMaterials[index];
  55259. if (mat.friction === friction && mat.restitution === restitution) {
  55260. return mat;
  55261. }
  55262. }
  55263. var currentMat = new CANNON.Material(name);
  55264. currentMat.friction = friction;
  55265. currentMat.restitution = restitution;
  55266. this._physicsMaterials.push(currentMat);
  55267. return currentMat;
  55268. };
  55269. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  55270. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  55271. };
  55272. CannonJSPlugin.prototype._createShape = function (impostor) {
  55273. var object = impostor.object;
  55274. var returnValue;
  55275. var extendSize = impostor.getObjectExtendSize();
  55276. switch (impostor.type) {
  55277. case BABYLON.PhysicsImpostor.SphereImpostor:
  55278. var radiusX = extendSize.x;
  55279. var radiusY = extendSize.y;
  55280. var radiusZ = extendSize.z;
  55281. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  55282. break;
  55283. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  55284. case BABYLON.PhysicsImpostor.CylinderImpostor:
  55285. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  55286. break;
  55287. case BABYLON.PhysicsImpostor.BoxImpostor:
  55288. var box = extendSize.scale(0.5);
  55289. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  55290. break;
  55291. case BABYLON.PhysicsImpostor.PlaneImpostor:
  55292. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  55293. returnValue = new CANNON.Plane();
  55294. break;
  55295. case BABYLON.PhysicsImpostor.MeshImpostor:
  55296. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  55297. var rawFaces = object.getIndices ? object.getIndices() : [];
  55298. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  55299. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  55300. break;
  55301. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  55302. returnValue = this._createHeightmap(object);
  55303. break;
  55304. case BABYLON.PhysicsImpostor.ParticleImpostor:
  55305. returnValue = new CANNON.Particle();
  55306. break;
  55307. }
  55308. return returnValue;
  55309. };
  55310. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  55311. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55312. var matrix = [];
  55313. //For now pointDepth will not be used and will be automatically calculated.
  55314. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  55315. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  55316. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  55317. var elementSize = dim * 2 / arraySize;
  55318. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  55319. for (var i = 0; i < pos.length; i = i + 3) {
  55320. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  55321. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  55322. var y = pos[i + 1] + minY;
  55323. if (!matrix[x]) {
  55324. matrix[x] = [];
  55325. }
  55326. if (!matrix[x][z]) {
  55327. matrix[x][z] = y;
  55328. }
  55329. matrix[x][z] = Math.max(y, matrix[x][z]);
  55330. }
  55331. for (var x = 0; x <= arraySize; ++x) {
  55332. if (!matrix[x]) {
  55333. var loc = 1;
  55334. while (!matrix[(x + loc) % arraySize]) {
  55335. loc++;
  55336. }
  55337. matrix[x] = matrix[(x + loc) % arraySize].slice();
  55338. //console.log("missing x", x);
  55339. }
  55340. for (var z = 0; z <= arraySize; ++z) {
  55341. if (!matrix[x][z]) {
  55342. var loc = 1;
  55343. var newValue;
  55344. while (newValue === undefined) {
  55345. newValue = matrix[x][(z + loc++) % arraySize];
  55346. }
  55347. matrix[x][z] = newValue;
  55348. }
  55349. }
  55350. }
  55351. var shape = new CANNON.Heightfield(matrix, {
  55352. elementSize: elementSize
  55353. });
  55354. //For future reference, needed for body transformation
  55355. shape.minY = minY;
  55356. return shape;
  55357. };
  55358. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  55359. var object = impostor.object;
  55360. //make sure it is updated...
  55361. object.computeWorldMatrix && object.computeWorldMatrix(true);
  55362. // The delta between the mesh position and the mesh bounding box center
  55363. var center = impostor.getObjectCenter();
  55364. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  55365. this._tmpPosition.copyFrom(center);
  55366. var quaternion = object.rotationQuaternion;
  55367. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  55368. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  55369. //-90 DEG in X, precalculated
  55370. quaternion = quaternion.multiply(this._minus90X);
  55371. //Invert! (Precalculated, 90 deg in X)
  55372. //No need to clone. this will never change.
  55373. impostor.setDeltaRotation(this._plus90X);
  55374. }
  55375. //If it is a heightfield, if should be centered.
  55376. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  55377. var mesh = object;
  55378. //calculate the correct body position:
  55379. var rotationQuaternion = mesh.rotationQuaternion;
  55380. mesh.rotationQuaternion = this._tmpUnityRotation;
  55381. mesh.computeWorldMatrix(true);
  55382. //get original center with no rotation
  55383. var c = center.clone();
  55384. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  55385. //rotation is back
  55386. mesh.rotationQuaternion = rotationQuaternion;
  55387. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  55388. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  55389. mesh.setPivotMatrix(p);
  55390. mesh.computeWorldMatrix(true);
  55391. //calculate the translation
  55392. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  55393. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  55394. //add it inverted to the delta
  55395. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  55396. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  55397. mesh.setPivotMatrix(oldPivot);
  55398. mesh.computeWorldMatrix(true);
  55399. }
  55400. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  55401. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  55402. this._tmpPosition.copyFrom(object.position);
  55403. }
  55404. impostor.setDeltaPosition(this._tmpDeltaPosition);
  55405. //Now update the impostor object
  55406. impostor.physicsBody.position.copy(this._tmpPosition);
  55407. impostor.physicsBody.quaternion.copy(quaternion);
  55408. };
  55409. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  55410. impostor.object.position.copyFrom(impostor.physicsBody.position);
  55411. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  55412. };
  55413. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  55414. impostor.physicsBody.position.copy(newPosition);
  55415. impostor.physicsBody.quaternion.copy(newRotation);
  55416. };
  55417. CannonJSPlugin.prototype.isSupported = function () {
  55418. return window.CANNON !== undefined;
  55419. };
  55420. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  55421. impostor.physicsBody.velocity.copy(velocity);
  55422. };
  55423. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  55424. impostor.physicsBody.angularVelocity.copy(velocity);
  55425. };
  55426. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  55427. var v = impostor.physicsBody.velocity;
  55428. if (!v)
  55429. return null;
  55430. return new BABYLON.Vector3(v.x, v.y, v.z);
  55431. };
  55432. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  55433. var v = impostor.physicsBody.angularVelocity;
  55434. if (!v)
  55435. return null;
  55436. return new BABYLON.Vector3(v.x, v.y, v.z);
  55437. };
  55438. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  55439. impostor.physicsBody.mass = mass;
  55440. impostor.physicsBody.updateMassProperties();
  55441. };
  55442. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  55443. impostor.physicsBody.sleep();
  55444. };
  55445. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  55446. impostor.physicsBody.wakeUp();
  55447. };
  55448. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  55449. joint.physicsJoint.distance = maxDistance;
  55450. };
  55451. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  55452. if (!motorIndex) {
  55453. joint.physicsJoint.enableMotor();
  55454. }
  55455. };
  55456. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  55457. if (!motorIndex) {
  55458. joint.physicsJoint.disableMotor();
  55459. }
  55460. };
  55461. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  55462. if (!motorIndex) {
  55463. joint.physicsJoint.enableMotor();
  55464. joint.physicsJoint.setMotorSpeed(speed);
  55465. if (maxForce) {
  55466. this.setLimit(joint, maxForce);
  55467. }
  55468. }
  55469. };
  55470. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  55471. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  55472. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  55473. };
  55474. CannonJSPlugin.prototype.dispose = function () {
  55475. //nothing to do, actually.
  55476. };
  55477. return CannonJSPlugin;
  55478. }());
  55479. BABYLON.CannonJSPlugin = CannonJSPlugin;
  55480. })(BABYLON || (BABYLON = {}));
  55481. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  55482. var BABYLON;
  55483. (function (BABYLON) {
  55484. var OimoJSPlugin = (function () {
  55485. function OimoJSPlugin(iterations) {
  55486. this.name = "OimoJSPlugin";
  55487. this._tmpImpostorsArray = [];
  55488. this._tmpPositionVector = BABYLON.Vector3.Zero();
  55489. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  55490. this.world.worldscale(1);
  55491. this.world.clear();
  55492. //making sure no stats are calculated
  55493. this.world.isNoStat = true;
  55494. }
  55495. OimoJSPlugin.prototype.setGravity = function (gravity) {
  55496. this.world.gravity.copy(gravity);
  55497. };
  55498. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  55499. this.world.timeStep = timeStep;
  55500. };
  55501. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  55502. var _this = this;
  55503. impostors.forEach(function (impostor) {
  55504. impostor.beforeStep();
  55505. });
  55506. this.world.step();
  55507. impostors.forEach(function (impostor) {
  55508. impostor.afterStep();
  55509. //update the ordered impostors array
  55510. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  55511. });
  55512. //check for collisions
  55513. var contact = this.world.contacts;
  55514. while (contact !== null) {
  55515. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  55516. contact = contact.next;
  55517. continue;
  55518. }
  55519. //is this body colliding with any other? get the impostor
  55520. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  55521. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  55522. if (!mainImpostor || !collidingImpostor) {
  55523. contact = contact.next;
  55524. continue;
  55525. }
  55526. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  55527. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  55528. contact = contact.next;
  55529. }
  55530. };
  55531. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  55532. var mass = impostor.physicsBody.massInfo.mass;
  55533. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  55534. };
  55535. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  55536. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  55537. this.applyImpulse(impostor, force, contactPoint);
  55538. };
  55539. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  55540. var _this = this;
  55541. //parent-child relationship. Does this impostor has a parent impostor?
  55542. if (impostor.parent) {
  55543. if (impostor.physicsBody) {
  55544. this.removePhysicsBody(impostor);
  55545. //TODO is that needed?
  55546. impostor.forceUpdate();
  55547. }
  55548. return;
  55549. }
  55550. if (impostor.isBodyInitRequired()) {
  55551. var bodyConfig = {
  55552. name: impostor.uniqueId,
  55553. //Oimo must have mass, also for static objects.
  55554. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  55555. size: [],
  55556. type: [],
  55557. pos: [],
  55558. rot: [],
  55559. move: impostor.getParam("mass") !== 0,
  55560. //Supporting older versions of Oimo
  55561. world: this.world
  55562. };
  55563. var impostors = [impostor];
  55564. var addToArray = function (parent) {
  55565. if (!parent.getChildMeshes)
  55566. return;
  55567. parent.getChildMeshes().forEach(function (m) {
  55568. if (m.physicsImpostor) {
  55569. impostors.push(m.physicsImpostor);
  55570. m.physicsImpostor._init();
  55571. }
  55572. });
  55573. };
  55574. addToArray(impostor.object);
  55575. var checkWithEpsilon_1 = function (value) {
  55576. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  55577. };
  55578. impostors.forEach(function (i) {
  55579. //get the correct bounding box
  55580. var oldQuaternion = i.object.rotationQuaternion;
  55581. var rot = new OIMO.Euler().setFromQuaternion({
  55582. x: impostor.object.rotationQuaternion.x,
  55583. y: impostor.object.rotationQuaternion.y,
  55584. z: impostor.object.rotationQuaternion.z,
  55585. s: impostor.object.rotationQuaternion.w
  55586. });
  55587. var extendSize = i.getObjectExtendSize();
  55588. if (i === impostor) {
  55589. var center = impostor.getObjectCenter();
  55590. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  55591. //Can also use Array.prototype.push.apply
  55592. bodyConfig.pos.push(center.x);
  55593. bodyConfig.pos.push(center.y);
  55594. bodyConfig.pos.push(center.z);
  55595. //tmp solution
  55596. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  55597. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  55598. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  55599. }
  55600. else {
  55601. bodyConfig.pos.push(i.object.position.x);
  55602. bodyConfig.pos.push(i.object.position.y);
  55603. bodyConfig.pos.push(i.object.position.z);
  55604. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  55605. bodyConfig.rot.push(0);
  55606. bodyConfig.rot.push(0);
  55607. bodyConfig.rot.push(0);
  55608. }
  55609. // register mesh
  55610. switch (i.type) {
  55611. case BABYLON.PhysicsImpostor.ParticleImpostor:
  55612. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  55613. case BABYLON.PhysicsImpostor.SphereImpostor:
  55614. var radiusX = extendSize.x;
  55615. var radiusY = extendSize.y;
  55616. var radiusZ = extendSize.z;
  55617. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  55618. bodyConfig.type.push('sphere');
  55619. //due to the way oimo works with compounds, add 3 times
  55620. bodyConfig.size.push(size);
  55621. bodyConfig.size.push(size);
  55622. bodyConfig.size.push(size);
  55623. break;
  55624. case BABYLON.PhysicsImpostor.CylinderImpostor:
  55625. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  55626. var sizeY = checkWithEpsilon_1(extendSize.y);
  55627. bodyConfig.type.push('cylinder');
  55628. bodyConfig.size.push(sizeX);
  55629. bodyConfig.size.push(sizeY);
  55630. //due to the way oimo works with compounds, add one more value.
  55631. bodyConfig.size.push(sizeY);
  55632. break;
  55633. case BABYLON.PhysicsImpostor.PlaneImpostor:
  55634. case BABYLON.PhysicsImpostor.BoxImpostor:
  55635. default:
  55636. var sizeX = checkWithEpsilon_1(extendSize.x);
  55637. var sizeY = checkWithEpsilon_1(extendSize.y);
  55638. var sizeZ = checkWithEpsilon_1(extendSize.z);
  55639. bodyConfig.type.push('box');
  55640. bodyConfig.size.push(sizeX);
  55641. bodyConfig.size.push(sizeY);
  55642. bodyConfig.size.push(sizeZ);
  55643. break;
  55644. }
  55645. //actually not needed, but hey...
  55646. i.object.rotationQuaternion = oldQuaternion;
  55647. });
  55648. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  55649. }
  55650. else {
  55651. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  55652. }
  55653. impostor.setDeltaPosition(this._tmpPositionVector);
  55654. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  55655. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  55656. };
  55657. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  55658. //impostor.physicsBody.dispose();
  55659. //Same as : (older oimo versions)
  55660. this.world.removeRigidBody(impostor.physicsBody);
  55661. };
  55662. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  55663. var mainBody = impostorJoint.mainImpostor.physicsBody;
  55664. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  55665. if (!mainBody || !connectedBody) {
  55666. return;
  55667. }
  55668. var jointData = impostorJoint.joint.jointData;
  55669. var options = jointData.nativeParams || {};
  55670. var type;
  55671. var nativeJointData = {
  55672. body1: mainBody,
  55673. body2: connectedBody,
  55674. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  55675. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  55676. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  55677. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  55678. min: options.min,
  55679. max: options.max,
  55680. collision: options.collision || jointData.collision,
  55681. spring: options.spring,
  55682. //supporting older version of Oimo
  55683. world: this.world
  55684. };
  55685. switch (impostorJoint.joint.type) {
  55686. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  55687. type = "jointBall";
  55688. break;
  55689. case BABYLON.PhysicsJoint.SpringJoint:
  55690. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  55691. var springData = jointData;
  55692. nativeJointData.min = springData.length || nativeJointData.min;
  55693. //Max should also be set, just make sure it is at least min
  55694. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  55695. case BABYLON.PhysicsJoint.DistanceJoint:
  55696. type = "jointDistance";
  55697. nativeJointData.max = jointData.maxDistance;
  55698. break;
  55699. case BABYLON.PhysicsJoint.PrismaticJoint:
  55700. type = "jointPrisme";
  55701. break;
  55702. case BABYLON.PhysicsJoint.SliderJoint:
  55703. type = "jointSlide";
  55704. break;
  55705. case BABYLON.PhysicsJoint.WheelJoint:
  55706. type = "jointWheel";
  55707. break;
  55708. case BABYLON.PhysicsJoint.HingeJoint:
  55709. default:
  55710. type = "jointHinge";
  55711. break;
  55712. }
  55713. nativeJointData.type = type;
  55714. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  55715. };
  55716. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  55717. //Bug in Oimo prevents us from disposing a joint in the playground
  55718. //joint.joint.physicsJoint.dispose();
  55719. //So we will bruteforce it!
  55720. try {
  55721. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  55722. }
  55723. catch (e) {
  55724. BABYLON.Tools.Warn(e);
  55725. }
  55726. };
  55727. OimoJSPlugin.prototype.isSupported = function () {
  55728. return OIMO !== undefined;
  55729. };
  55730. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  55731. if (!impostor.physicsBody.sleeping) {
  55732. //TODO check that
  55733. if (impostor.physicsBody.shapes.next) {
  55734. var parentShape = this._getLastShape(impostor.physicsBody);
  55735. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  55736. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  55737. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  55738. }
  55739. else {
  55740. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  55741. }
  55742. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  55743. impostor.object.rotationQuaternion.normalize();
  55744. }
  55745. };
  55746. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  55747. var body = impostor.physicsBody;
  55748. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  55749. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  55750. body.syncShapes();
  55751. body.awake();
  55752. };
  55753. OimoJSPlugin.prototype._getLastShape = function (body) {
  55754. var lastShape = body.shapes;
  55755. while (lastShape.next) {
  55756. lastShape = lastShape.next;
  55757. }
  55758. return lastShape;
  55759. };
  55760. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  55761. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  55762. };
  55763. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  55764. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  55765. };
  55766. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  55767. var v = impostor.physicsBody.linearVelocity;
  55768. if (!v)
  55769. return null;
  55770. return new BABYLON.Vector3(v.x, v.y, v.z);
  55771. };
  55772. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  55773. var v = impostor.physicsBody.angularVelocity;
  55774. if (!v)
  55775. return null;
  55776. return new BABYLON.Vector3(v.x, v.y, v.z);
  55777. };
  55778. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  55779. var staticBody = mass === 0;
  55780. //this will actually set the body's density and not its mass.
  55781. //But this is how oimo treats the mass variable.
  55782. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  55783. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  55784. };
  55785. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  55786. impostor.physicsBody.sleep();
  55787. };
  55788. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  55789. impostor.physicsBody.awake();
  55790. };
  55791. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  55792. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  55793. if (minDistance !== void 0) {
  55794. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  55795. }
  55796. };
  55797. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  55798. //TODO separate rotational and transational motors.
  55799. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  55800. if (motor) {
  55801. motor.setMotor(speed, maxForce);
  55802. }
  55803. };
  55804. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  55805. //TODO separate rotational and transational motors.
  55806. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  55807. if (motor) {
  55808. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  55809. }
  55810. };
  55811. OimoJSPlugin.prototype.dispose = function () {
  55812. this.world.clear();
  55813. };
  55814. return OimoJSPlugin;
  55815. }());
  55816. BABYLON.OimoJSPlugin = OimoJSPlugin;
  55817. })(BABYLON || (BABYLON = {}));
  55818. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  55819. var BABYLON;
  55820. (function (BABYLON) {
  55821. var Internals;
  55822. (function (Internals) {
  55823. /*
  55824. * Based on jsTGALoader - Javascript loader for TGA file
  55825. * By Vincent Thibault
  55826. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  55827. */
  55828. var TGATools = (function () {
  55829. function TGATools() {
  55830. }
  55831. TGATools.GetTGAHeader = function (data) {
  55832. var offset = 0;
  55833. var header = {
  55834. id_length: data[offset++],
  55835. colormap_type: data[offset++],
  55836. image_type: data[offset++],
  55837. colormap_index: data[offset++] | data[offset++] << 8,
  55838. colormap_length: data[offset++] | data[offset++] << 8,
  55839. colormap_size: data[offset++],
  55840. origin: [
  55841. data[offset++] | data[offset++] << 8,
  55842. data[offset++] | data[offset++] << 8
  55843. ],
  55844. width: data[offset++] | data[offset++] << 8,
  55845. height: data[offset++] | data[offset++] << 8,
  55846. pixel_size: data[offset++],
  55847. flags: data[offset++]
  55848. };
  55849. return header;
  55850. };
  55851. TGATools.UploadContent = function (gl, data) {
  55852. // Not enough data to contain header ?
  55853. if (data.length < 19) {
  55854. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  55855. return;
  55856. }
  55857. // Read Header
  55858. var offset = 18;
  55859. var header = TGATools.GetTGAHeader(data);
  55860. // Assume it's a valid Targa file.
  55861. if (header.id_length + offset > data.length) {
  55862. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  55863. return;
  55864. }
  55865. // Skip not needed data
  55866. offset += header.id_length;
  55867. var use_rle = false;
  55868. var use_pal = false;
  55869. var use_rgb = false;
  55870. var use_grey = false;
  55871. // Get some informations.
  55872. switch (header.image_type) {
  55873. case TGATools._TYPE_RLE_INDEXED:
  55874. use_rle = true;
  55875. case TGATools._TYPE_INDEXED:
  55876. use_pal = true;
  55877. break;
  55878. case TGATools._TYPE_RLE_RGB:
  55879. use_rle = true;
  55880. case TGATools._TYPE_RGB:
  55881. use_rgb = true;
  55882. break;
  55883. case TGATools._TYPE_RLE_GREY:
  55884. use_rle = true;
  55885. case TGATools._TYPE_GREY:
  55886. use_grey = true;
  55887. break;
  55888. }
  55889. var pixel_data;
  55890. var numAlphaBits = header.flags & 0xf;
  55891. var pixel_size = header.pixel_size >> 3;
  55892. var pixel_total = header.width * header.height * pixel_size;
  55893. // Read palettes
  55894. var palettes;
  55895. if (use_pal) {
  55896. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  55897. }
  55898. // Read LRE
  55899. if (use_rle) {
  55900. pixel_data = new Uint8Array(pixel_total);
  55901. var c, count, i;
  55902. var localOffset = 0;
  55903. var pixels = new Uint8Array(pixel_size);
  55904. while (offset < pixel_total && localOffset < pixel_total) {
  55905. c = data[offset++];
  55906. count = (c & 0x7f) + 1;
  55907. // RLE pixels
  55908. if (c & 0x80) {
  55909. // Bind pixel tmp array
  55910. for (i = 0; i < pixel_size; ++i) {
  55911. pixels[i] = data[offset++];
  55912. }
  55913. // Copy pixel array
  55914. for (i = 0; i < count; ++i) {
  55915. pixel_data.set(pixels, localOffset + i * pixel_size);
  55916. }
  55917. localOffset += pixel_size * count;
  55918. }
  55919. else {
  55920. count *= pixel_size;
  55921. for (i = 0; i < count; ++i) {
  55922. pixel_data[localOffset + i] = data[offset++];
  55923. }
  55924. localOffset += count;
  55925. }
  55926. }
  55927. }
  55928. else {
  55929. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  55930. }
  55931. // Load to texture
  55932. var x_start, y_start, x_step, y_step, y_end, x_end;
  55933. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  55934. default:
  55935. case TGATools._ORIGIN_UL:
  55936. x_start = 0;
  55937. x_step = 1;
  55938. x_end = header.width;
  55939. y_start = 0;
  55940. y_step = 1;
  55941. y_end = header.height;
  55942. break;
  55943. case TGATools._ORIGIN_BL:
  55944. x_start = 0;
  55945. x_step = 1;
  55946. x_end = header.width;
  55947. y_start = header.height - 1;
  55948. y_step = -1;
  55949. y_end = -1;
  55950. break;
  55951. case TGATools._ORIGIN_UR:
  55952. x_start = header.width - 1;
  55953. x_step = -1;
  55954. x_end = -1;
  55955. y_start = 0;
  55956. y_step = 1;
  55957. y_end = header.height;
  55958. break;
  55959. case TGATools._ORIGIN_BR:
  55960. x_start = header.width - 1;
  55961. x_step = -1;
  55962. x_end = -1;
  55963. y_start = header.height - 1;
  55964. y_step = -1;
  55965. y_end = -1;
  55966. break;
  55967. }
  55968. // Load the specify method
  55969. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  55970. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  55971. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  55972. };
  55973. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  55974. var image = pixel_data, colormap = palettes;
  55975. var width = header.width, height = header.height;
  55976. var color, i = 0, x, y;
  55977. var imageData = new Uint8Array(width * height * 4);
  55978. for (y = y_start; y !== y_end; y += y_step) {
  55979. for (x = x_start; x !== x_end; x += x_step, i++) {
  55980. color = image[i];
  55981. imageData[(x + width * y) * 4 + 3] = 255;
  55982. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  55983. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  55984. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  55985. }
  55986. }
  55987. return imageData;
  55988. };
  55989. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  55990. var image = pixel_data;
  55991. var width = header.width, height = header.height;
  55992. var color, i = 0, x, y;
  55993. var imageData = new Uint8Array(width * height * 4);
  55994. for (y = y_start; y !== y_end; y += y_step) {
  55995. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  55996. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  55997. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  55998. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  55999. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  56000. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  56001. }
  56002. }
  56003. return imageData;
  56004. };
  56005. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  56006. var image = pixel_data;
  56007. var width = header.width, height = header.height;
  56008. var i = 0, x, y;
  56009. var imageData = new Uint8Array(width * height * 4);
  56010. for (y = y_start; y !== y_end; y += y_step) {
  56011. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  56012. imageData[(x + width * y) * 4 + 3] = 255;
  56013. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  56014. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  56015. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  56016. }
  56017. }
  56018. return imageData;
  56019. };
  56020. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  56021. var image = pixel_data;
  56022. var width = header.width, height = header.height;
  56023. var i = 0, x, y;
  56024. var imageData = new Uint8Array(width * height * 4);
  56025. for (y = y_start; y !== y_end; y += y_step) {
  56026. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  56027. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  56028. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  56029. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  56030. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  56031. }
  56032. }
  56033. return imageData;
  56034. };
  56035. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  56036. var image = pixel_data;
  56037. var width = header.width, height = header.height;
  56038. var color, i = 0, x, y;
  56039. var imageData = new Uint8Array(width * height * 4);
  56040. for (y = y_start; y !== y_end; y += y_step) {
  56041. for (x = x_start; x !== x_end; x += x_step, i++) {
  56042. color = image[i];
  56043. imageData[(x + width * y) * 4 + 0] = color;
  56044. imageData[(x + width * y) * 4 + 1] = color;
  56045. imageData[(x + width * y) * 4 + 2] = color;
  56046. imageData[(x + width * y) * 4 + 3] = 255;
  56047. }
  56048. }
  56049. return imageData;
  56050. };
  56051. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  56052. var image = pixel_data;
  56053. var width = header.width, height = header.height;
  56054. var i = 0, x, y;
  56055. var imageData = new Uint8Array(width * height * 4);
  56056. for (y = y_start; y !== y_end; y += y_step) {
  56057. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  56058. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  56059. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  56060. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  56061. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  56062. }
  56063. }
  56064. return imageData;
  56065. };
  56066. return TGATools;
  56067. }());
  56068. TGATools._TYPE_NO_DATA = 0;
  56069. TGATools._TYPE_INDEXED = 1;
  56070. TGATools._TYPE_RGB = 2;
  56071. TGATools._TYPE_GREY = 3;
  56072. TGATools._TYPE_RLE_INDEXED = 9;
  56073. TGATools._TYPE_RLE_RGB = 10;
  56074. TGATools._TYPE_RLE_GREY = 11;
  56075. TGATools._ORIGIN_MASK = 0x30;
  56076. TGATools._ORIGIN_SHIFT = 0x04;
  56077. TGATools._ORIGIN_BL = 0x00;
  56078. TGATools._ORIGIN_BR = 0x01;
  56079. TGATools._ORIGIN_UL = 0x02;
  56080. TGATools._ORIGIN_UR = 0x03;
  56081. Internals.TGATools = TGATools;
  56082. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56083. })(BABYLON || (BABYLON = {}));
  56084. //# sourceMappingURL=babylon.tga.js.map
  56085. var BABYLON;
  56086. (function (BABYLON) {
  56087. var Internals;
  56088. (function (Internals) {
  56089. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  56090. // All values and structures referenced from:
  56091. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  56092. var DDS_MAGIC = 0x20534444;
  56093. 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;
  56094. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  56095. 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;
  56096. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  56097. function FourCCToInt32(value) {
  56098. return value.charCodeAt(0) +
  56099. (value.charCodeAt(1) << 8) +
  56100. (value.charCodeAt(2) << 16) +
  56101. (value.charCodeAt(3) << 24);
  56102. }
  56103. function Int32ToFourCC(value) {
  56104. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  56105. }
  56106. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  56107. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  56108. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  56109. var headerLengthInt = 31; // The header length in 32 bit ints
  56110. // Offsets into the header array
  56111. var off_magic = 0;
  56112. var off_size = 1;
  56113. var off_flags = 2;
  56114. var off_height = 3;
  56115. var off_width = 4;
  56116. var off_mipmapCount = 7;
  56117. var off_pfFlags = 20;
  56118. var off_pfFourCC = 21;
  56119. var off_RGBbpp = 22;
  56120. var off_RMask = 23;
  56121. var off_GMask = 24;
  56122. var off_BMask = 25;
  56123. var off_AMask = 26;
  56124. var off_caps1 = 27;
  56125. var off_caps2 = 28;
  56126. ;
  56127. var DDSTools = (function () {
  56128. function DDSTools() {
  56129. }
  56130. DDSTools.GetDDSInfo = function (arrayBuffer) {
  56131. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  56132. var mipmapCount = 1;
  56133. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  56134. mipmapCount = Math.max(1, header[off_mipmapCount]);
  56135. }
  56136. return {
  56137. width: header[off_width],
  56138. height: header[off_height],
  56139. mipmapCount: mipmapCount,
  56140. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  56141. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  56142. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  56143. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  56144. };
  56145. };
  56146. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  56147. var byteArray = new Uint8Array(dataLength);
  56148. var srcData = new Uint8Array(arrayBuffer);
  56149. var index = 0;
  56150. for (var y = height - 1; y >= 0; y--) {
  56151. for (var x = 0; x < width; x++) {
  56152. var srcPos = dataOffset + (x + y * width) * 4;
  56153. byteArray[index + 2] = srcData[srcPos];
  56154. byteArray[index + 1] = srcData[srcPos + 1];
  56155. byteArray[index] = srcData[srcPos + 2];
  56156. byteArray[index + 3] = srcData[srcPos + 3];
  56157. index += 4;
  56158. }
  56159. }
  56160. return byteArray;
  56161. };
  56162. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  56163. var byteArray = new Uint8Array(dataLength);
  56164. var srcData = new Uint8Array(arrayBuffer);
  56165. var index = 0;
  56166. for (var y = height - 1; y >= 0; y--) {
  56167. for (var x = 0; x < width; x++) {
  56168. var srcPos = dataOffset + (x + y * width) * 3;
  56169. byteArray[index + 2] = srcData[srcPos];
  56170. byteArray[index + 1] = srcData[srcPos + 1];
  56171. byteArray[index] = srcData[srcPos + 2];
  56172. index += 3;
  56173. }
  56174. }
  56175. return byteArray;
  56176. };
  56177. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  56178. var byteArray = new Uint8Array(dataLength);
  56179. var srcData = new Uint8Array(arrayBuffer);
  56180. var index = 0;
  56181. for (var y = height - 1; y >= 0; y--) {
  56182. for (var x = 0; x < width; x++) {
  56183. var srcPos = dataOffset + (x + y * width);
  56184. byteArray[index] = srcData[srcPos];
  56185. index++;
  56186. }
  56187. }
  56188. return byteArray;
  56189. };
  56190. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  56191. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  56192. if (header[off_magic] != DDS_MAGIC) {
  56193. BABYLON.Tools.Error("Invalid magic number in DDS header");
  56194. return;
  56195. }
  56196. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  56197. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  56198. return;
  56199. }
  56200. if (info.isFourCC) {
  56201. fourCC = header[off_pfFourCC];
  56202. switch (fourCC) {
  56203. case FOURCC_DXT1:
  56204. blockBytes = 8;
  56205. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  56206. break;
  56207. case FOURCC_DXT3:
  56208. blockBytes = 16;
  56209. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  56210. break;
  56211. case FOURCC_DXT5:
  56212. blockBytes = 16;
  56213. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  56214. break;
  56215. default:
  56216. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  56217. return;
  56218. }
  56219. }
  56220. mipmapCount = 1;
  56221. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  56222. mipmapCount = Math.max(1, header[off_mipmapCount]);
  56223. }
  56224. var bpp = header[off_RGBbpp];
  56225. for (var face = 0; face < faces; face++) {
  56226. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  56227. width = header[off_width];
  56228. height = header[off_height];
  56229. dataOffset = header[off_size] + 4;
  56230. for (i = 0; i < mipmapCount; ++i) {
  56231. if (info.isRGB) {
  56232. if (bpp === 24) {
  56233. dataLength = width * height * 3;
  56234. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  56235. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  56236. }
  56237. else {
  56238. dataLength = width * height * 4;
  56239. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  56240. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  56241. }
  56242. }
  56243. else if (info.isLuminance) {
  56244. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  56245. var unpaddedRowSize = width;
  56246. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  56247. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  56248. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  56249. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  56250. }
  56251. else {
  56252. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  56253. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  56254. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  56255. }
  56256. dataOffset += dataLength;
  56257. width *= 0.5;
  56258. height *= 0.5;
  56259. width = Math.max(1.0, width);
  56260. height = Math.max(1.0, height);
  56261. }
  56262. }
  56263. };
  56264. return DDSTools;
  56265. }());
  56266. Internals.DDSTools = DDSTools;
  56267. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56268. })(BABYLON || (BABYLON = {}));
  56269. //# sourceMappingURL=babylon.dds.js.map
  56270. var BABYLON;
  56271. (function (BABYLON) {
  56272. var Internals;
  56273. (function (Internals) {
  56274. /**
  56275. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  56276. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  56277. */
  56278. var KhronosTextureContainer = (function () {
  56279. /**
  56280. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  56281. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  56282. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  56283. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  56284. */
  56285. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  56286. this.arrayBuffer = arrayBuffer;
  56287. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  56288. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  56289. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  56290. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  56291. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  56292. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  56293. BABYLON.Tools.Error("texture missing KTX identifier");
  56294. return;
  56295. }
  56296. // load the reset of the header in native 32 bit int
  56297. var header = new Int32Array(this.arrayBuffer, 12, 13);
  56298. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  56299. var oppositeEndianess = header[0] === 0x01020304;
  56300. // read all the header elements in order they exist in the file, without modification (sans endainness)
  56301. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  56302. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  56303. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  56304. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  56305. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  56306. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  56307. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  56308. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  56309. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  56310. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  56311. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  56312. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  56313. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  56314. if (this.glType !== 0) {
  56315. BABYLON.Tools.Error("only compressed formats currently supported");
  56316. return;
  56317. }
  56318. else {
  56319. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  56320. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  56321. }
  56322. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  56323. BABYLON.Tools.Error("only 2D textures currently supported");
  56324. return;
  56325. }
  56326. if (this.numberOfArrayElements !== 0) {
  56327. BABYLON.Tools.Error("texture arrays not currently supported");
  56328. return;
  56329. }
  56330. if (this.numberOfFaces !== facesExpected) {
  56331. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  56332. return;
  56333. }
  56334. // we now have a completely validated file, so could use existence of loadType as success
  56335. // would need to make this more elaborate & adjust checks above to support more than one load type
  56336. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  56337. }
  56338. // not as fast hardware based, but will probably never need to use
  56339. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  56340. return ((val & 0xFF) << 24)
  56341. | ((val & 0xFF00) << 8)
  56342. | ((val >> 8) & 0xFF00)
  56343. | ((val >> 24) & 0xFF);
  56344. };
  56345. /**
  56346. * It is assumed that the texture has already been created & is currently bound
  56347. */
  56348. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  56349. switch (this.loadType) {
  56350. case KhronosTextureContainer.COMPRESSED_2D:
  56351. this._upload2DCompressedLevels(gl, loadMipmaps);
  56352. break;
  56353. case KhronosTextureContainer.TEX_2D:
  56354. case KhronosTextureContainer.COMPRESSED_3D:
  56355. case KhronosTextureContainer.TEX_3D:
  56356. }
  56357. };
  56358. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  56359. // initialize width & height for level 1
  56360. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  56361. var width = this.pixelWidth;
  56362. var height = this.pixelHeight;
  56363. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  56364. for (var level = 0; level < mipmapCount; level++) {
  56365. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  56366. for (var face = 0; face < this.numberOfFaces; face++) {
  56367. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  56368. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  56369. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  56370. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  56371. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  56372. }
  56373. width = Math.max(1.0, width * 0.5);
  56374. height = Math.max(1.0, height * 0.5);
  56375. }
  56376. };
  56377. return KhronosTextureContainer;
  56378. }());
  56379. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  56380. // load types
  56381. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  56382. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  56383. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  56384. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  56385. Internals.KhronosTextureContainer = KhronosTextureContainer;
  56386. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56387. })(BABYLON || (BABYLON = {}));
  56388. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  56389. var BABYLON;
  56390. (function (BABYLON) {
  56391. var Debug;
  56392. (function (Debug) {
  56393. /**
  56394. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  56395. */
  56396. var SkeletonViewer = (function () {
  56397. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  56398. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  56399. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  56400. this.skeleton = skeleton;
  56401. this.mesh = mesh;
  56402. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  56403. this.renderingGroupId = renderingGroupId;
  56404. this.color = BABYLON.Color3.White();
  56405. this._debugLines = [];
  56406. this._isEnabled = false;
  56407. this._scene = scene;
  56408. this.update();
  56409. this._renderFunction = this.update.bind(this);
  56410. }
  56411. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  56412. get: function () {
  56413. return this._isEnabled;
  56414. },
  56415. set: function (value) {
  56416. if (this._isEnabled === value) {
  56417. return;
  56418. }
  56419. this._isEnabled = value;
  56420. if (value) {
  56421. this._scene.registerBeforeRender(this._renderFunction);
  56422. }
  56423. else {
  56424. this._scene.unregisterBeforeRender(this._renderFunction);
  56425. }
  56426. },
  56427. enumerable: true,
  56428. configurable: true
  56429. });
  56430. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  56431. if (x === void 0) { x = 0; }
  56432. if (y === void 0) { y = 0; }
  56433. if (z === void 0) { z = 0; }
  56434. var tmat = BABYLON.Tmp.Matrix[0];
  56435. var parentBone = bone.getParent();
  56436. tmat.copyFrom(bone.getLocalMatrix());
  56437. if (x !== 0 || y !== 0 || z !== 0) {
  56438. var tmat2 = BABYLON.Tmp.Matrix[1];
  56439. BABYLON.Matrix.IdentityToRef(tmat2);
  56440. tmat2.m[12] = x;
  56441. tmat2.m[13] = y;
  56442. tmat2.m[14] = z;
  56443. tmat2.multiplyToRef(tmat, tmat);
  56444. }
  56445. if (parentBone) {
  56446. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  56447. }
  56448. tmat.multiplyToRef(meshMat, tmat);
  56449. position.x = tmat.m[12];
  56450. position.y = tmat.m[13];
  56451. position.z = tmat.m[14];
  56452. };
  56453. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  56454. var len = bones.length;
  56455. var meshPos = this.mesh.position;
  56456. for (var i = 0; i < len; i++) {
  56457. var bone = bones[i];
  56458. var points = this._debugLines[i];
  56459. if (!points) {
  56460. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56461. this._debugLines[i] = points;
  56462. }
  56463. this._getBonePosition(points[0], bone, meshMat);
  56464. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  56465. points[0].subtractInPlace(meshPos);
  56466. points[1].subtractInPlace(meshPos);
  56467. }
  56468. };
  56469. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  56470. var len = bones.length;
  56471. var boneNum = 0;
  56472. var meshPos = this.mesh.position;
  56473. for (var i = len - 1; i >= 0; i--) {
  56474. var childBone = bones[i];
  56475. var parentBone = childBone.getParent();
  56476. if (!parentBone) {
  56477. continue;
  56478. }
  56479. var points = this._debugLines[boneNum];
  56480. if (!points) {
  56481. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56482. this._debugLines[boneNum] = points;
  56483. }
  56484. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  56485. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  56486. points[0].subtractInPlace(meshPos);
  56487. points[1].subtractInPlace(meshPos);
  56488. boneNum++;
  56489. }
  56490. };
  56491. SkeletonViewer.prototype.update = function () {
  56492. if (this.autoUpdateBonesMatrices) {
  56493. this.skeleton.computeAbsoluteTransforms();
  56494. }
  56495. if (this.skeleton.bones[0].length === undefined) {
  56496. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  56497. }
  56498. else {
  56499. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  56500. }
  56501. if (!this._debugMesh) {
  56502. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  56503. this._debugMesh.renderingGroupId = this.renderingGroupId;
  56504. }
  56505. else {
  56506. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  56507. }
  56508. this._debugMesh.position.copyFrom(this.mesh.position);
  56509. this._debugMesh.color = this.color;
  56510. };
  56511. SkeletonViewer.prototype.dispose = function () {
  56512. if (this._debugMesh) {
  56513. this.isEnabled = false;
  56514. this._debugMesh.dispose();
  56515. this._debugMesh = null;
  56516. }
  56517. };
  56518. return SkeletonViewer;
  56519. }());
  56520. Debug.SkeletonViewer = SkeletonViewer;
  56521. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  56522. })(BABYLON || (BABYLON = {}));
  56523. //# sourceMappingURL=babylon.skeletonViewer.js.map
  56524. var BABYLON;
  56525. (function (BABYLON) {
  56526. var Debug;
  56527. (function (Debug) {
  56528. var AxesViewer = (function () {
  56529. function AxesViewer(scene, scaleLines) {
  56530. if (scaleLines === void 0) { scaleLines = 1; }
  56531. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56532. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56533. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56534. this.scaleLines = 1;
  56535. this.scaleLines = scaleLines;
  56536. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  56537. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  56538. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  56539. this._xmesh.renderingGroupId = 2;
  56540. this._ymesh.renderingGroupId = 2;
  56541. this._zmesh.renderingGroupId = 2;
  56542. this._xmesh.material.checkReadyOnlyOnce = true;
  56543. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  56544. this._ymesh.material.checkReadyOnlyOnce = true;
  56545. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  56546. this._zmesh.material.checkReadyOnlyOnce = true;
  56547. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  56548. this.scene = scene;
  56549. }
  56550. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  56551. var scaleLines = this.scaleLines;
  56552. var point1 = this._xline[0];
  56553. var point2 = this._xline[1];
  56554. point1.x = position.x;
  56555. point1.y = position.y;
  56556. point1.z = position.z;
  56557. point2.x = point1.x + xaxis.x * scaleLines;
  56558. point2.y = point1.y + xaxis.y * scaleLines;
  56559. point2.z = point1.z + xaxis.z * scaleLines;
  56560. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  56561. point1 = this._yline[0];
  56562. point2 = this._yline[1];
  56563. point1.x = position.x;
  56564. point1.y = position.y;
  56565. point1.z = position.z;
  56566. point2.x = point1.x + yaxis.x * scaleLines;
  56567. point2.y = point1.y + yaxis.y * scaleLines;
  56568. point2.z = point1.z + yaxis.z * scaleLines;
  56569. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  56570. point1 = this._zline[0];
  56571. point2 = this._zline[1];
  56572. point1.x = position.x;
  56573. point1.y = position.y;
  56574. point1.z = position.z;
  56575. point2.x = point1.x + zaxis.x * scaleLines;
  56576. point2.y = point1.y + zaxis.y * scaleLines;
  56577. point2.z = point1.z + zaxis.z * scaleLines;
  56578. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  56579. };
  56580. AxesViewer.prototype.dispose = function () {
  56581. if (this._xmesh) {
  56582. this._xmesh.dispose();
  56583. this._ymesh.dispose();
  56584. this._zmesh.dispose();
  56585. this._xmesh = null;
  56586. this._ymesh = null;
  56587. this._zmesh = null;
  56588. this._xline = null;
  56589. this._yline = null;
  56590. this._zline = null;
  56591. this.scene = null;
  56592. }
  56593. };
  56594. return AxesViewer;
  56595. }());
  56596. Debug.AxesViewer = AxesViewer;
  56597. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  56598. })(BABYLON || (BABYLON = {}));
  56599. //# sourceMappingURL=babylon.axesViewer.js.map
  56600. var BABYLON;
  56601. (function (BABYLON) {
  56602. var Debug;
  56603. (function (Debug) {
  56604. var BoneAxesViewer = (function (_super) {
  56605. __extends(BoneAxesViewer, _super);
  56606. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  56607. if (scaleLines === void 0) { scaleLines = 1; }
  56608. var _this = _super.call(this, scene, scaleLines) || this;
  56609. _this.pos = BABYLON.Vector3.Zero();
  56610. _this.xaxis = BABYLON.Vector3.Zero();
  56611. _this.yaxis = BABYLON.Vector3.Zero();
  56612. _this.zaxis = BABYLON.Vector3.Zero();
  56613. _this.mesh = mesh;
  56614. _this.bone = bone;
  56615. return _this;
  56616. }
  56617. BoneAxesViewer.prototype.update = function () {
  56618. var bone = this.bone;
  56619. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  56620. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  56621. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  56622. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  56623. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  56624. };
  56625. BoneAxesViewer.prototype.dispose = function () {
  56626. if (this.pos) {
  56627. this.pos = null;
  56628. this.xaxis = null;
  56629. this.yaxis = null;
  56630. this.zaxis = null;
  56631. this.mesh = null;
  56632. this.bone = null;
  56633. _super.prototype.dispose.call(this);
  56634. }
  56635. };
  56636. return BoneAxesViewer;
  56637. }(Debug.AxesViewer));
  56638. Debug.BoneAxesViewer = BoneAxesViewer;
  56639. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  56640. })(BABYLON || (BABYLON = {}));
  56641. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  56642. var BABYLON;
  56643. (function (BABYLON) {
  56644. var RayHelper = (function () {
  56645. function RayHelper(ray) {
  56646. this.ray = ray;
  56647. }
  56648. RayHelper.CreateAndShow = function (ray, scene, color) {
  56649. var helper = new RayHelper(ray);
  56650. helper.show(scene, color);
  56651. return helper;
  56652. };
  56653. RayHelper.prototype.show = function (scene, color) {
  56654. if (!this._renderFunction) {
  56655. var ray = this.ray;
  56656. this._renderFunction = this._render.bind(this);
  56657. this._scene = scene;
  56658. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  56659. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  56660. this._scene.registerBeforeRender(this._renderFunction);
  56661. }
  56662. if (color) {
  56663. this._renderLine.color.copyFrom(color);
  56664. }
  56665. };
  56666. RayHelper.prototype.hide = function () {
  56667. if (this._renderFunction) {
  56668. this._scene.unregisterBeforeRender(this._renderFunction);
  56669. this._scene = null;
  56670. this._renderFunction = null;
  56671. this._renderLine.dispose();
  56672. this._renderLine = null;
  56673. this._renderPoints = null;
  56674. }
  56675. };
  56676. RayHelper.prototype._render = function () {
  56677. var ray = this.ray;
  56678. var point = this._renderPoints[1];
  56679. var len = Math.min(ray.length, 1000000);
  56680. point.copyFrom(ray.direction);
  56681. point.scaleInPlace(len);
  56682. point.addInPlace(ray.origin);
  56683. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  56684. };
  56685. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  56686. this._attachedToMesh = mesh;
  56687. var ray = this.ray;
  56688. if (!ray.direction) {
  56689. ray.direction = BABYLON.Vector3.Zero();
  56690. }
  56691. if (!ray.origin) {
  56692. ray.origin = BABYLON.Vector3.Zero();
  56693. }
  56694. if (length) {
  56695. ray.length = length;
  56696. }
  56697. if (!meshSpaceOrigin) {
  56698. meshSpaceOrigin = BABYLON.Vector3.Zero();
  56699. }
  56700. if (!meshSpaceDirection) {
  56701. // -1 so that this will work with Mesh.lookAt
  56702. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  56703. }
  56704. if (!this._meshSpaceDirection) {
  56705. this._meshSpaceDirection = meshSpaceDirection.clone();
  56706. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  56707. }
  56708. else {
  56709. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  56710. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  56711. }
  56712. if (!this._updateToMeshFunction) {
  56713. this._updateToMeshFunction = this._updateToMesh.bind(this);
  56714. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  56715. }
  56716. this._updateToMesh();
  56717. };
  56718. RayHelper.prototype.detachFromMesh = function () {
  56719. if (this._attachedToMesh) {
  56720. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  56721. this._attachedToMesh = null;
  56722. this._updateToMeshFunction = null;
  56723. }
  56724. };
  56725. RayHelper.prototype._updateToMesh = function () {
  56726. var ray = this.ray;
  56727. if (this._attachedToMesh._isDisposed) {
  56728. this.detachFromMesh();
  56729. return;
  56730. }
  56731. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  56732. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  56733. };
  56734. RayHelper.prototype.dispose = function () {
  56735. this.hide();
  56736. this.detachFromMesh();
  56737. this.ray = null;
  56738. };
  56739. return RayHelper;
  56740. }());
  56741. BABYLON.RayHelper = RayHelper;
  56742. })(BABYLON || (BABYLON = {}));
  56743. //# sourceMappingURL=babylon.rayHelper.js.map
  56744. var BABYLON;
  56745. (function (BABYLON) {
  56746. var DebugLayer = (function () {
  56747. function DebugLayer(scene) {
  56748. this._scene = scene;
  56749. }
  56750. /** Creates the inspector window. */
  56751. DebugLayer.prototype._createInspector = function (config) {
  56752. if (config === void 0) { config = {}; }
  56753. var popup = config.popup || false;
  56754. var initialTab = config.initialTab || 0;
  56755. var parentElement = config.parentElement || null;
  56756. if (!this._inspector) {
  56757. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  56758. } // else nothing to do,; instance is already existing
  56759. };
  56760. DebugLayer.prototype.isVisible = function () {
  56761. if (!this._inspector) {
  56762. return false;
  56763. }
  56764. return true;
  56765. };
  56766. DebugLayer.prototype.hide = function () {
  56767. if (this._inspector) {
  56768. try {
  56769. this._inspector.dispose();
  56770. }
  56771. catch (e) {
  56772. // If the inspector has been removed directly from the inspector tool
  56773. }
  56774. this._inspector = null;
  56775. }
  56776. };
  56777. DebugLayer.prototype.show = function (config) {
  56778. if (config === void 0) { config = {}; }
  56779. if (typeof INSPECTOR == 'undefined') {
  56780. // Load inspector and add it to the DOM
  56781. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  56782. }
  56783. else {
  56784. // Otherwise creates the inspector
  56785. this._createInspector(config);
  56786. }
  56787. };
  56788. return DebugLayer;
  56789. }());
  56790. // Get protocol used - http or https
  56791. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//www.babylonjs.com/babylon.inspector.bundle.js';
  56792. BABYLON.DebugLayer = DebugLayer;
  56793. })(BABYLON || (BABYLON = {}));
  56794. //# sourceMappingURL=babylon.debugLayer.js.map
  56795. var BABYLON;
  56796. (function (BABYLON) {
  56797. var BoundingBoxRenderer = (function () {
  56798. function BoundingBoxRenderer(scene) {
  56799. this.frontColor = new BABYLON.Color3(1, 1, 1);
  56800. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  56801. this.showBackLines = true;
  56802. this.renderList = new BABYLON.SmartArray(32);
  56803. this._vertexBuffers = {};
  56804. this._scene = scene;
  56805. }
  56806. BoundingBoxRenderer.prototype._prepareRessources = function () {
  56807. if (this._colorShader) {
  56808. return;
  56809. }
  56810. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  56811. attributes: [BABYLON.VertexBuffer.PositionKind],
  56812. uniforms: ["world", "viewProjection", "color"]
  56813. });
  56814. var engine = this._scene.getEngine();
  56815. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  56816. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  56817. this._indexBuffer = 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]);
  56818. };
  56819. BoundingBoxRenderer.prototype.reset = function () {
  56820. this.renderList.reset();
  56821. };
  56822. BoundingBoxRenderer.prototype.render = function () {
  56823. if (this.renderList.length === 0) {
  56824. return;
  56825. }
  56826. this._prepareRessources();
  56827. if (!this._colorShader.isReady()) {
  56828. return;
  56829. }
  56830. var engine = this._scene.getEngine();
  56831. engine.setDepthWrite(false);
  56832. this._colorShader._preBind();
  56833. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  56834. var boundingBox = this.renderList.data[boundingBoxIndex];
  56835. var min = boundingBox.minimum;
  56836. var max = boundingBox.maximum;
  56837. var diff = max.subtract(min);
  56838. var median = min.add(diff.scale(0.5));
  56839. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  56840. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  56841. .multiply(boundingBox.getWorldMatrix());
  56842. // VBOs
  56843. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  56844. if (this.showBackLines) {
  56845. // Back
  56846. engine.setDepthFunctionToGreaterOrEqual();
  56847. this._scene.resetCachedMaterial();
  56848. this._colorShader.setColor4("color", this.backColor.toColor4());
  56849. this._colorShader.bind(worldMatrix);
  56850. // Draw order
  56851. engine.draw(false, 0, 24);
  56852. }
  56853. // Front
  56854. engine.setDepthFunctionToLess();
  56855. this._scene.resetCachedMaterial();
  56856. this._colorShader.setColor4("color", this.frontColor.toColor4());
  56857. this._colorShader.bind(worldMatrix);
  56858. // Draw order
  56859. engine.draw(false, 0, 24);
  56860. }
  56861. this._colorShader.unbind();
  56862. engine.setDepthFunctionToLessOrEqual();
  56863. engine.setDepthWrite(true);
  56864. };
  56865. BoundingBoxRenderer.prototype.dispose = function () {
  56866. if (!this._colorShader) {
  56867. return;
  56868. }
  56869. this.renderList.dispose();
  56870. this._colorShader.dispose();
  56871. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  56872. if (buffer) {
  56873. buffer.dispose();
  56874. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  56875. }
  56876. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56877. };
  56878. return BoundingBoxRenderer;
  56879. }());
  56880. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  56881. })(BABYLON || (BABYLON = {}));
  56882. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  56883. var BABYLON;
  56884. (function (BABYLON) {
  56885. var MorphTarget = (function () {
  56886. function MorphTarget(name, influence) {
  56887. if (influence === void 0) { influence = 0; }
  56888. this.name = name;
  56889. this.animations = new Array();
  56890. this.onInfluenceChanged = new BABYLON.Observable();
  56891. this.influence = influence;
  56892. }
  56893. Object.defineProperty(MorphTarget.prototype, "influence", {
  56894. get: function () {
  56895. return this._influence;
  56896. },
  56897. set: function (influence) {
  56898. if (this._influence === influence) {
  56899. return;
  56900. }
  56901. var previous = this._influence;
  56902. this._influence = influence;
  56903. if (this.onInfluenceChanged.hasObservers) {
  56904. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  56905. }
  56906. },
  56907. enumerable: true,
  56908. configurable: true
  56909. });
  56910. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  56911. get: function () {
  56912. return this._normals !== undefined;
  56913. },
  56914. enumerable: true,
  56915. configurable: true
  56916. });
  56917. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  56918. get: function () {
  56919. return this._tangents !== undefined;
  56920. },
  56921. enumerable: true,
  56922. configurable: true
  56923. });
  56924. MorphTarget.prototype.setPositions = function (data) {
  56925. this._positions = new Float32Array(data);
  56926. };
  56927. MorphTarget.prototype.getPositions = function () {
  56928. return this._positions;
  56929. };
  56930. MorphTarget.prototype.setNormals = function (data) {
  56931. this._normals = new Float32Array(data);
  56932. };
  56933. MorphTarget.prototype.getNormals = function () {
  56934. return this._normals;
  56935. };
  56936. MorphTarget.prototype.setTangents = function (data) {
  56937. this._tangents = new Float32Array(data);
  56938. };
  56939. MorphTarget.prototype.getTangents = function () {
  56940. return this._tangents;
  56941. };
  56942. /**
  56943. * Serializes the current target into a Serialization object.
  56944. * Returns the serialized object.
  56945. */
  56946. MorphTarget.prototype.serialize = function () {
  56947. var serializationObject = {};
  56948. serializationObject.name = this.name;
  56949. serializationObject.influence = this.influence;
  56950. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  56951. if (this.hasNormals) {
  56952. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  56953. }
  56954. if (this.hasTangents) {
  56955. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  56956. }
  56957. return serializationObject;
  56958. };
  56959. // Statics
  56960. MorphTarget.Parse = function (serializationObject) {
  56961. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  56962. result.setPositions(serializationObject.positions);
  56963. if (serializationObject.normals) {
  56964. result.setNormals(serializationObject.normals);
  56965. }
  56966. if (serializationObject.tangents) {
  56967. result.setTangents(serializationObject.tangents);
  56968. }
  56969. return result;
  56970. };
  56971. MorphTarget.FromMesh = function (mesh, name, influence) {
  56972. if (!name) {
  56973. name = mesh.name;
  56974. }
  56975. var result = new MorphTarget(name, influence);
  56976. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  56977. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  56978. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  56979. }
  56980. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  56981. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  56982. }
  56983. return result;
  56984. };
  56985. return MorphTarget;
  56986. }());
  56987. BABYLON.MorphTarget = MorphTarget;
  56988. })(BABYLON || (BABYLON = {}));
  56989. //# sourceMappingURL=babylon.morphTarget.js.map
  56990. var BABYLON;
  56991. (function (BABYLON) {
  56992. var MorphTargetManager = (function () {
  56993. function MorphTargetManager(scene) {
  56994. this._targets = new Array();
  56995. this._targetObservable = new Array();
  56996. this._activeTargets = new BABYLON.SmartArray(16);
  56997. this._supportsNormals = false;
  56998. this._supportsTangents = false;
  56999. this._vertexCount = 0;
  57000. this._uniqueId = 0;
  57001. if (!scene) {
  57002. scene = BABYLON.Engine.LastCreatedScene;
  57003. }
  57004. this._scene = scene;
  57005. this._scene.morphTargetManagers.push(this);
  57006. this._uniqueId = scene.getUniqueId();
  57007. }
  57008. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  57009. get: function () {
  57010. return this._uniqueId;
  57011. },
  57012. enumerable: true,
  57013. configurable: true
  57014. });
  57015. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  57016. get: function () {
  57017. return this._vertexCount;
  57018. },
  57019. enumerable: true,
  57020. configurable: true
  57021. });
  57022. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  57023. get: function () {
  57024. return this._supportsNormals;
  57025. },
  57026. enumerable: true,
  57027. configurable: true
  57028. });
  57029. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  57030. get: function () {
  57031. return this._supportsTangents;
  57032. },
  57033. enumerable: true,
  57034. configurable: true
  57035. });
  57036. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  57037. get: function () {
  57038. return this._targets.length;
  57039. },
  57040. enumerable: true,
  57041. configurable: true
  57042. });
  57043. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  57044. get: function () {
  57045. return this._activeTargets.length;
  57046. },
  57047. enumerable: true,
  57048. configurable: true
  57049. });
  57050. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  57051. get: function () {
  57052. return this._influences;
  57053. },
  57054. enumerable: true,
  57055. configurable: true
  57056. });
  57057. MorphTargetManager.prototype.getActiveTarget = function (index) {
  57058. return this._activeTargets.data[index];
  57059. };
  57060. MorphTargetManager.prototype.getTarget = function (index) {
  57061. return this._targets[index];
  57062. };
  57063. MorphTargetManager.prototype.addTarget = function (target) {
  57064. var _this = this;
  57065. if (this._vertexCount) {
  57066. if (this._vertexCount !== target.getPositions().length / 3) {
  57067. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  57068. return;
  57069. }
  57070. }
  57071. this._targets.push(target);
  57072. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  57073. _this._syncActiveTargets(needUpdate);
  57074. }));
  57075. this._syncActiveTargets(true);
  57076. };
  57077. MorphTargetManager.prototype.removeTarget = function (target) {
  57078. var index = this._targets.indexOf(target);
  57079. if (index >= 0) {
  57080. this._targets.splice(index, 1);
  57081. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  57082. this._vertexCount = 0;
  57083. this._syncActiveTargets(true);
  57084. }
  57085. };
  57086. /**
  57087. * Serializes the current manager into a Serialization object.
  57088. * Returns the serialized object.
  57089. */
  57090. MorphTargetManager.prototype.serialize = function () {
  57091. var serializationObject = {};
  57092. serializationObject.id = this.uniqueId;
  57093. serializationObject.targets = [];
  57094. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  57095. var target = _a[_i];
  57096. serializationObject.targets.push(target.serialize());
  57097. }
  57098. return serializationObject;
  57099. };
  57100. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  57101. this._syncActiveTargets(needUpdate);
  57102. };
  57103. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  57104. this._activeTargets.reset();
  57105. var tempInfluences = [];
  57106. this._supportsNormals = true;
  57107. this._supportsTangents = true;
  57108. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  57109. var target = _a[_i];
  57110. if (target.influence > 0) {
  57111. this._activeTargets.push(target);
  57112. tempInfluences.push(target.influence);
  57113. this._supportsNormals = this._supportsNormals && target.hasNormals;
  57114. this._supportsTangents = this._supportsTangents && target.hasTangents;
  57115. if (this._vertexCount === 0) {
  57116. this._vertexCount = target.getPositions().length / 3;
  57117. }
  57118. }
  57119. }
  57120. this._influences = new Float32Array(tempInfluences);
  57121. if (needUpdate) {
  57122. // Flag meshes as dirty to resync with the active targets
  57123. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  57124. var mesh = _c[_b];
  57125. if (mesh.morphTargetManager === this) {
  57126. mesh._syncGeometryWithMorphTargetManager();
  57127. }
  57128. }
  57129. }
  57130. };
  57131. // Statics
  57132. MorphTargetManager.Parse = function (serializationObject, scene) {
  57133. var result = new MorphTargetManager(scene);
  57134. result._uniqueId = serializationObject.id;
  57135. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  57136. var targetData = _a[_i];
  57137. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  57138. }
  57139. return result;
  57140. };
  57141. return MorphTargetManager;
  57142. }());
  57143. BABYLON.MorphTargetManager = MorphTargetManager;
  57144. })(BABYLON || (BABYLON = {}));
  57145. //# sourceMappingURL=babylon.morphTargetManager.js.map
  57146. var BABYLON;
  57147. (function (BABYLON) {
  57148. /**
  57149. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  57150. * It can help converting any input color in a desired output one. This can then be used to create effects
  57151. * from sepia, black and white to sixties or futuristic rendering...
  57152. *
  57153. * The only supported format is currently 3dl.
  57154. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  57155. */
  57156. var ColorGradingTexture = (function (_super) {
  57157. __extends(ColorGradingTexture, _super);
  57158. /**
  57159. * Instantiates a ColorGradingTexture from the following parameters.
  57160. *
  57161. * @param url The location of the color gradind data (currently only supporting 3dl)
  57162. * @param scene The scene the texture will be used in
  57163. */
  57164. function ColorGradingTexture(url, scene) {
  57165. var _this = _super.call(this, scene) || this;
  57166. if (!url) {
  57167. return _this;
  57168. }
  57169. _this._textureMatrix = BABYLON.Matrix.Identity();
  57170. _this.name = url;
  57171. _this.url = url;
  57172. _this.hasAlpha = false;
  57173. _this.isCube = false;
  57174. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57175. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57176. _this.anisotropicFilteringLevel = 1;
  57177. _this._texture = _this._getFromCache(url, true);
  57178. if (!_this._texture) {
  57179. if (!scene.useDelayedTextureLoading) {
  57180. _this.loadTexture();
  57181. }
  57182. else {
  57183. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57184. }
  57185. }
  57186. return _this;
  57187. }
  57188. /**
  57189. * Returns the texture matrix used in most of the material.
  57190. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  57191. */
  57192. ColorGradingTexture.prototype.getTextureMatrix = function () {
  57193. return this._textureMatrix;
  57194. };
  57195. /**
  57196. * Occurs when the file being loaded is a .3dl LUT file.
  57197. */
  57198. ColorGradingTexture.prototype.load3dlTexture = function () {
  57199. var _this = this;
  57200. var mipLevels = 0;
  57201. var floatArrayView = null;
  57202. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57203. this._texture = texture;
  57204. var callback = function (text) {
  57205. var data;
  57206. var tempData;
  57207. var line;
  57208. var lines = text.split('\n');
  57209. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  57210. var maxColor = 0;
  57211. for (var i = 0; i < lines.length; i++) {
  57212. line = lines[i];
  57213. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  57214. continue;
  57215. if (line.indexOf('#') === 0)
  57216. continue;
  57217. var words = line.split(" ");
  57218. if (size === 0) {
  57219. // Number of space + one
  57220. size = words.length;
  57221. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  57222. tempData = new Float32Array(size * size * size * 4);
  57223. continue;
  57224. }
  57225. if (size != 0) {
  57226. var r = Math.max(parseInt(words[0]), 0);
  57227. var g = Math.max(parseInt(words[1]), 0);
  57228. var b = Math.max(parseInt(words[2]), 0);
  57229. maxColor = Math.max(r, maxColor);
  57230. maxColor = Math.max(g, maxColor);
  57231. maxColor = Math.max(b, maxColor);
  57232. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  57233. tempData[pixelStorageIndex + 0] = r;
  57234. tempData[pixelStorageIndex + 1] = g;
  57235. tempData[pixelStorageIndex + 2] = b;
  57236. tempData[pixelStorageIndex + 3] = 0;
  57237. pixelIndexSlice++;
  57238. if (pixelIndexSlice % size == 0) {
  57239. pixelIndexH++;
  57240. pixelIndexSlice = 0;
  57241. if (pixelIndexH % size == 0) {
  57242. pixelIndexW++;
  57243. pixelIndexH = 0;
  57244. }
  57245. }
  57246. }
  57247. }
  57248. for (var i = 0; i < tempData.length; i++) {
  57249. var value = tempData[i];
  57250. data[i] = (value / maxColor * 255);
  57251. }
  57252. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  57253. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  57254. };
  57255. BABYLON.Tools.LoadFile(this.url, callback);
  57256. return this._texture;
  57257. };
  57258. /**
  57259. * Starts the loading process of the texture.
  57260. */
  57261. ColorGradingTexture.prototype.loadTexture = function () {
  57262. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  57263. this.load3dlTexture();
  57264. }
  57265. };
  57266. /**
  57267. * Clones the color gradind texture.
  57268. */
  57269. ColorGradingTexture.prototype.clone = function () {
  57270. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  57271. // Base texture
  57272. newTexture.level = this.level;
  57273. return newTexture;
  57274. };
  57275. /**
  57276. * Called during delayed load for textures.
  57277. */
  57278. ColorGradingTexture.prototype.delayLoad = function () {
  57279. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57280. return;
  57281. }
  57282. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57283. this._texture = this._getFromCache(this.url, true);
  57284. if (!this._texture) {
  57285. this.loadTexture();
  57286. }
  57287. };
  57288. /**
  57289. * Binds the color grading to the shader.
  57290. * @param colorGrading The texture to bind
  57291. * @param effect The effect to bind to
  57292. */
  57293. ColorGradingTexture.Bind = function (colorGrading, effect) {
  57294. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  57295. var x = colorGrading.level; // Texture Level
  57296. var y = colorGrading.getSize().height; // Texture Size example with 8
  57297. var z = y - 1.0; // SizeMinusOne 8 - 1
  57298. var w = 1 / y; // Space of 1 slice 1 / 8
  57299. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  57300. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  57301. var slicePixelSizeV = w; // Space of 1 pixel in V direction, e.g. 1/8 // Space of 1 pixel in V direction, e.g. 1/8
  57302. var x2 = z * slicePixelSizeU; // Extent of lookup range in U for a single slice so that range corresponds to (size-1) texels, for example 7/64
  57303. var y2 = z / y; // Extent of lookup range in V for a single slice so that range corresponds to (size-1) texels, for example 7/8
  57304. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  57305. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  57306. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  57307. };
  57308. /**
  57309. * Prepare the list of uniforms associated with the ColorGrading effects.
  57310. * @param uniformsList The list of uniforms used in the effect
  57311. * @param samplersList The list of samplers used in the effect
  57312. */
  57313. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  57314. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  57315. samplersList.push("cameraColorGrading2DSampler");
  57316. };
  57317. /**
  57318. * Parses a color grading texture serialized by Babylon.
  57319. * @param parsedTexture The texture information being parsedTexture
  57320. * @param scene The scene to load the texture in
  57321. * @param rootUrl The root url of the data assets to load
  57322. * @return A color gradind texture
  57323. */
  57324. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57325. var texture = null;
  57326. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  57327. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  57328. texture.name = parsedTexture.name;
  57329. texture.level = parsedTexture.level;
  57330. }
  57331. return texture;
  57332. };
  57333. /**
  57334. * Serializes the LUT texture to json format.
  57335. */
  57336. ColorGradingTexture.prototype.serialize = function () {
  57337. if (!this.name) {
  57338. return null;
  57339. }
  57340. var serializationObject = {};
  57341. serializationObject.name = this.name;
  57342. serializationObject.level = this.level;
  57343. serializationObject.customType = "BABYLON.ColorGradingTexture";
  57344. return serializationObject;
  57345. };
  57346. return ColorGradingTexture;
  57347. }(BABYLON.BaseTexture));
  57348. /**
  57349. * Empty line regex stored for GC.
  57350. */
  57351. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  57352. BABYLON.ColorGradingTexture = ColorGradingTexture;
  57353. })(BABYLON || (BABYLON = {}));
  57354. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  57355. var BABYLON;
  57356. (function (BABYLON) {
  57357. /**
  57358. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  57359. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  57360. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  57361. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  57362. */
  57363. var ColorCurves = (function () {
  57364. function ColorCurves() {
  57365. this._dirty = true;
  57366. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  57367. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  57368. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  57369. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  57370. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  57371. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  57372. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  57373. this._globalHue = 30;
  57374. this._globalDensity = 0;
  57375. this._globalSaturation = 0;
  57376. this._globalExposure = 0;
  57377. this._highlightsHue = 30;
  57378. this._highlightsDensity = 0;
  57379. this._highlightsSaturation = 0;
  57380. this._highlightsExposure = 0;
  57381. this._midtonesHue = 30;
  57382. this._midtonesDensity = 0;
  57383. this._midtonesSaturation = 0;
  57384. this._midtonesExposure = 0;
  57385. this._shadowsHue = 30;
  57386. this._shadowsDensity = 0;
  57387. this._shadowsSaturation = 0;
  57388. this._shadowsExposure = 0;
  57389. }
  57390. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  57391. /**
  57392. * Gets the global Hue value.
  57393. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  57394. */
  57395. get: function () {
  57396. return this._globalHue;
  57397. },
  57398. /**
  57399. * Sets the global Hue value.
  57400. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  57401. */
  57402. set: function (value) {
  57403. this._globalHue = value;
  57404. this._dirty = true;
  57405. },
  57406. enumerable: true,
  57407. configurable: true
  57408. });
  57409. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  57410. /**
  57411. * Gets the global Density value.
  57412. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  57413. * Values less than zero provide a filter of opposite hue.
  57414. */
  57415. get: function () {
  57416. return this._globalDensity;
  57417. },
  57418. /**
  57419. * Sets the global Density value.
  57420. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  57421. * Values less than zero provide a filter of opposite hue.
  57422. */
  57423. set: function (value) {
  57424. this._globalDensity = value;
  57425. this._dirty = true;
  57426. },
  57427. enumerable: true,
  57428. configurable: true
  57429. });
  57430. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  57431. /**
  57432. * Gets the global Saturation value.
  57433. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  57434. */
  57435. get: function () {
  57436. return this._globalSaturation;
  57437. },
  57438. /**
  57439. * Sets the global Saturation value.
  57440. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  57441. */
  57442. set: function (value) {
  57443. this._globalSaturation = value;
  57444. this._dirty = true;
  57445. },
  57446. enumerable: true,
  57447. configurable: true
  57448. });
  57449. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  57450. /**
  57451. * Gets the highlights Hue value.
  57452. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  57453. */
  57454. get: function () {
  57455. return this._highlightsHue;
  57456. },
  57457. /**
  57458. * Sets the highlights Hue value.
  57459. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  57460. */
  57461. set: function (value) {
  57462. this._highlightsHue = value;
  57463. this._dirty = true;
  57464. },
  57465. enumerable: true,
  57466. configurable: true
  57467. });
  57468. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  57469. /**
  57470. * Gets the highlights Density value.
  57471. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  57472. * Values less than zero provide a filter of opposite hue.
  57473. */
  57474. get: function () {
  57475. return this._highlightsDensity;
  57476. },
  57477. /**
  57478. * Sets the highlights Density value.
  57479. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  57480. * Values less than zero provide a filter of opposite hue.
  57481. */
  57482. set: function (value) {
  57483. this._highlightsDensity = value;
  57484. this._dirty = true;
  57485. },
  57486. enumerable: true,
  57487. configurable: true
  57488. });
  57489. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  57490. /**
  57491. * Gets the highlights Saturation value.
  57492. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  57493. */
  57494. get: function () {
  57495. return this._highlightsSaturation;
  57496. },
  57497. /**
  57498. * Sets the highlights Saturation value.
  57499. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  57500. */
  57501. set: function (value) {
  57502. this._highlightsSaturation = value;
  57503. this._dirty = true;
  57504. },
  57505. enumerable: true,
  57506. configurable: true
  57507. });
  57508. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  57509. /**
  57510. * Gets the highlights Exposure value.
  57511. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  57512. */
  57513. get: function () {
  57514. return this._highlightsExposure;
  57515. },
  57516. /**
  57517. * Sets the highlights Exposure value.
  57518. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  57519. */
  57520. set: function (value) {
  57521. this._highlightsExposure = value;
  57522. this._dirty = true;
  57523. },
  57524. enumerable: true,
  57525. configurable: true
  57526. });
  57527. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  57528. /**
  57529. * Gets the midtones Hue value.
  57530. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  57531. */
  57532. get: function () {
  57533. return this._midtonesHue;
  57534. },
  57535. /**
  57536. * Sets the midtones Hue value.
  57537. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  57538. */
  57539. set: function (value) {
  57540. this._midtonesHue = value;
  57541. this._dirty = true;
  57542. },
  57543. enumerable: true,
  57544. configurable: true
  57545. });
  57546. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  57547. /**
  57548. * Gets the midtones Density value.
  57549. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  57550. * Values less than zero provide a filter of opposite hue.
  57551. */
  57552. get: function () {
  57553. return this._midtonesDensity;
  57554. },
  57555. /**
  57556. * Sets the midtones Density value.
  57557. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  57558. * Values less than zero provide a filter of opposite hue.
  57559. */
  57560. set: function (value) {
  57561. this._midtonesDensity = value;
  57562. this._dirty = true;
  57563. },
  57564. enumerable: true,
  57565. configurable: true
  57566. });
  57567. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  57568. /**
  57569. * Gets the midtones Saturation value.
  57570. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  57571. */
  57572. get: function () {
  57573. return this._midtonesSaturation;
  57574. },
  57575. /**
  57576. * Sets the midtones Saturation value.
  57577. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  57578. */
  57579. set: function (value) {
  57580. this._midtonesSaturation = value;
  57581. this._dirty = true;
  57582. },
  57583. enumerable: true,
  57584. configurable: true
  57585. });
  57586. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  57587. /**
  57588. * Gets the midtones Exposure value.
  57589. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  57590. */
  57591. get: function () {
  57592. return this._midtonesExposure;
  57593. },
  57594. /**
  57595. * Sets the midtones Exposure value.
  57596. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  57597. */
  57598. set: function (value) {
  57599. this._midtonesExposure = value;
  57600. this._dirty = true;
  57601. },
  57602. enumerable: true,
  57603. configurable: true
  57604. });
  57605. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  57606. /**
  57607. * Gets the shadows Hue value.
  57608. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  57609. */
  57610. get: function () {
  57611. return this._shadowsHue;
  57612. },
  57613. /**
  57614. * Sets the shadows Hue value.
  57615. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  57616. */
  57617. set: function (value) {
  57618. this._shadowsHue = value;
  57619. this._dirty = true;
  57620. },
  57621. enumerable: true,
  57622. configurable: true
  57623. });
  57624. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  57625. /**
  57626. * Gets the shadows Density value.
  57627. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  57628. * Values less than zero provide a filter of opposite hue.
  57629. */
  57630. get: function () {
  57631. return this._shadowsDensity;
  57632. },
  57633. /**
  57634. * Sets the shadows Density value.
  57635. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  57636. * Values less than zero provide a filter of opposite hue.
  57637. */
  57638. set: function (value) {
  57639. this._shadowsDensity = value;
  57640. this._dirty = true;
  57641. },
  57642. enumerable: true,
  57643. configurable: true
  57644. });
  57645. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  57646. /**
  57647. * Gets the shadows Saturation value.
  57648. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  57649. */
  57650. get: function () {
  57651. return this._shadowsSaturation;
  57652. },
  57653. /**
  57654. * Sets the shadows Saturation value.
  57655. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  57656. */
  57657. set: function (value) {
  57658. this._shadowsSaturation = value;
  57659. this._dirty = true;
  57660. },
  57661. enumerable: true,
  57662. configurable: true
  57663. });
  57664. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  57665. /**
  57666. * Gets the shadows Exposure value.
  57667. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  57668. */
  57669. get: function () {
  57670. return this._shadowsExposure;
  57671. },
  57672. /**
  57673. * Sets the shadows Exposure value.
  57674. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  57675. */
  57676. set: function (value) {
  57677. this._shadowsExposure = value;
  57678. this._dirty = true;
  57679. },
  57680. enumerable: true,
  57681. configurable: true
  57682. });
  57683. /**
  57684. * Binds the color curves to the shader.
  57685. * @param colorCurves The color curve to bind
  57686. * @param effect The effect to bind to
  57687. */
  57688. ColorCurves.Bind = function (colorCurves, effect) {
  57689. if (colorCurves._dirty) {
  57690. colorCurves._dirty = false;
  57691. // Fill in global info.
  57692. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  57693. // Compute highlights info.
  57694. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  57695. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  57696. // Compute midtones info.
  57697. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  57698. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  57699. // Compute shadows info.
  57700. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  57701. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  57702. // Compute deltas (neutral is midtones).
  57703. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  57704. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  57705. }
  57706. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  57707. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  57708. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  57709. };
  57710. /**
  57711. * Prepare the list of uniforms associated with the ColorCurves effects.
  57712. * @param uniformsList The list of uniforms used in the effect
  57713. */
  57714. ColorCurves.PrepareUniforms = function (uniformsList) {
  57715. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  57716. };
  57717. /**
  57718. * Returns color grading data based on a hue, density, saturation and exposure value.
  57719. * @param filterHue The hue of the color filter.
  57720. * @param filterDensity The density of the color filter.
  57721. * @param saturation The saturation.
  57722. * @param exposure The exposure.
  57723. * @param result The result data container.
  57724. */
  57725. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  57726. if (hue == null) {
  57727. return;
  57728. }
  57729. hue = ColorCurves.clamp(hue, 0, 360);
  57730. density = ColorCurves.clamp(density, -100, 100);
  57731. saturation = ColorCurves.clamp(saturation, -100, 100);
  57732. exposure = ColorCurves.clamp(exposure, -100, 100);
  57733. // Remap the slider/config filter density with non-linear mapping and also scale by half
  57734. // so that the maximum filter density is only 50% control. This provides fine control
  57735. // for small values and reasonable range.
  57736. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  57737. density *= 0.5;
  57738. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  57739. if (density < 0) {
  57740. density *= -1;
  57741. hue = (hue + 180) % 360;
  57742. }
  57743. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  57744. result.scaleToRef(2, result);
  57745. result.a = 1 + 0.01 * saturation;
  57746. };
  57747. /**
  57748. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  57749. * @param value The input slider value in range [-100,100].
  57750. * @returns Adjusted value.
  57751. */
  57752. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  57753. value /= 100;
  57754. var x = Math.abs(value);
  57755. x = Math.pow(x, 2);
  57756. if (value < 0) {
  57757. x *= -1;
  57758. }
  57759. x *= 100;
  57760. return x;
  57761. };
  57762. /**
  57763. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  57764. * @param hue The hue (H) input.
  57765. * @param saturation The saturation (S) input.
  57766. * @param brightness The brightness (B) input.
  57767. * @result An RGBA color represented as Vector4.
  57768. */
  57769. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  57770. var h = ColorCurves.clamp(hue, 0, 360);
  57771. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  57772. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  57773. if (s === 0) {
  57774. result.r = v;
  57775. result.g = v;
  57776. result.b = v;
  57777. }
  57778. else {
  57779. // sector 0 to 5
  57780. h /= 60;
  57781. var i = Math.floor(h);
  57782. // fractional part of h
  57783. var f = h - i;
  57784. var p = v * (1 - s);
  57785. var q = v * (1 - s * f);
  57786. var t = v * (1 - s * (1 - f));
  57787. switch (i) {
  57788. case 0:
  57789. result.r = v;
  57790. result.g = t;
  57791. result.b = p;
  57792. break;
  57793. case 1:
  57794. result.r = q;
  57795. result.g = v;
  57796. result.b = p;
  57797. break;
  57798. case 2:
  57799. result.r = p;
  57800. result.g = v;
  57801. result.b = t;
  57802. break;
  57803. case 3:
  57804. result.r = p;
  57805. result.g = q;
  57806. result.b = v;
  57807. break;
  57808. case 4:
  57809. result.r = t;
  57810. result.g = p;
  57811. result.b = v;
  57812. break;
  57813. default:
  57814. result.r = v;
  57815. result.g = p;
  57816. result.b = q;
  57817. break;
  57818. }
  57819. }
  57820. result.a = 1;
  57821. };
  57822. /**
  57823. * Returns a value clamped between min and max
  57824. * @param value The value to clamp
  57825. * @param min The minimum of value
  57826. * @param max The maximum of value
  57827. * @returns The clamped value.
  57828. */
  57829. ColorCurves.clamp = function (value, min, max) {
  57830. return Math.min(Math.max(value, min), max);
  57831. };
  57832. /**
  57833. * Clones the current color curve instance.
  57834. * @return The cloned curves
  57835. */
  57836. ColorCurves.prototype.clone = function () {
  57837. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  57838. };
  57839. /**
  57840. * Serializes the current color curve instance to a json representation.
  57841. * @return a JSON representation
  57842. */
  57843. ColorCurves.prototype.serialize = function () {
  57844. return BABYLON.SerializationHelper.Serialize(this);
  57845. };
  57846. /**
  57847. * Parses the color curve from a json representation.
  57848. * @param source the JSON source to parse
  57849. * @return The parsed curves
  57850. */
  57851. ColorCurves.Parse = function (source) {
  57852. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  57853. };
  57854. return ColorCurves;
  57855. }());
  57856. __decorate([
  57857. BABYLON.serialize()
  57858. ], ColorCurves.prototype, "_globalHue", void 0);
  57859. __decorate([
  57860. BABYLON.serialize()
  57861. ], ColorCurves.prototype, "_globalDensity", void 0);
  57862. __decorate([
  57863. BABYLON.serialize()
  57864. ], ColorCurves.prototype, "_globalSaturation", void 0);
  57865. __decorate([
  57866. BABYLON.serialize()
  57867. ], ColorCurves.prototype, "_globalExposure", void 0);
  57868. __decorate([
  57869. BABYLON.serialize()
  57870. ], ColorCurves.prototype, "_highlightsHue", void 0);
  57871. __decorate([
  57872. BABYLON.serialize()
  57873. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  57874. __decorate([
  57875. BABYLON.serialize()
  57876. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  57877. __decorate([
  57878. BABYLON.serialize()
  57879. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  57880. __decorate([
  57881. BABYLON.serialize()
  57882. ], ColorCurves.prototype, "_midtonesHue", void 0);
  57883. __decorate([
  57884. BABYLON.serialize()
  57885. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  57886. __decorate([
  57887. BABYLON.serialize()
  57888. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  57889. __decorate([
  57890. BABYLON.serialize()
  57891. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  57892. BABYLON.ColorCurves = ColorCurves;
  57893. })(BABYLON || (BABYLON = {}));
  57894. //# sourceMappingURL=babylon.colorCurves.js.map
  57895. var BABYLON;
  57896. (function (BABYLON) {
  57897. var Octree = (function () {
  57898. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  57899. if (maxDepth === void 0) { maxDepth = 2; }
  57900. this.maxDepth = maxDepth;
  57901. this.dynamicContent = new Array();
  57902. this._maxBlockCapacity = maxBlockCapacity || 64;
  57903. this._selectionContent = new BABYLON.SmartArray(1024);
  57904. this._creationFunc = creationFunc;
  57905. }
  57906. // Methods
  57907. Octree.prototype.update = function (worldMin, worldMax, entries) {
  57908. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  57909. };
  57910. Octree.prototype.addMesh = function (entry) {
  57911. for (var index = 0; index < this.blocks.length; index++) {
  57912. var block = this.blocks[index];
  57913. block.addEntry(entry);
  57914. }
  57915. };
  57916. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  57917. this._selectionContent.reset();
  57918. for (var index = 0; index < this.blocks.length; index++) {
  57919. var block = this.blocks[index];
  57920. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  57921. }
  57922. if (allowDuplicate) {
  57923. this._selectionContent.concat(this.dynamicContent);
  57924. }
  57925. else {
  57926. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  57927. }
  57928. return this._selectionContent;
  57929. };
  57930. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  57931. this._selectionContent.reset();
  57932. for (var index = 0; index < this.blocks.length; index++) {
  57933. var block = this.blocks[index];
  57934. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  57935. }
  57936. if (allowDuplicate) {
  57937. this._selectionContent.concat(this.dynamicContent);
  57938. }
  57939. else {
  57940. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  57941. }
  57942. return this._selectionContent;
  57943. };
  57944. Octree.prototype.intersectsRay = function (ray) {
  57945. this._selectionContent.reset();
  57946. for (var index = 0; index < this.blocks.length; index++) {
  57947. var block = this.blocks[index];
  57948. block.intersectsRay(ray, this._selectionContent);
  57949. }
  57950. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  57951. return this._selectionContent;
  57952. };
  57953. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  57954. target.blocks = new Array();
  57955. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  57956. // Segmenting space
  57957. for (var x = 0; x < 2; x++) {
  57958. for (var y = 0; y < 2; y++) {
  57959. for (var z = 0; z < 2; z++) {
  57960. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  57961. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  57962. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  57963. block.addEntries(entries);
  57964. target.blocks.push(block);
  57965. }
  57966. }
  57967. }
  57968. };
  57969. return Octree;
  57970. }());
  57971. Octree.CreationFuncForMeshes = function (entry, block) {
  57972. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  57973. block.entries.push(entry);
  57974. }
  57975. };
  57976. Octree.CreationFuncForSubMeshes = function (entry, block) {
  57977. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  57978. block.entries.push(entry);
  57979. }
  57980. };
  57981. BABYLON.Octree = Octree;
  57982. })(BABYLON || (BABYLON = {}));
  57983. //# sourceMappingURL=babylon.octree.js.map
  57984. var BABYLON;
  57985. (function (BABYLON) {
  57986. var OctreeBlock = (function () {
  57987. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  57988. this.entries = new Array();
  57989. this._boundingVectors = new Array();
  57990. this._capacity = capacity;
  57991. this._depth = depth;
  57992. this._maxDepth = maxDepth;
  57993. this._creationFunc = creationFunc;
  57994. this._minPoint = minPoint;
  57995. this._maxPoint = maxPoint;
  57996. this._boundingVectors.push(minPoint.clone());
  57997. this._boundingVectors.push(maxPoint.clone());
  57998. this._boundingVectors.push(minPoint.clone());
  57999. this._boundingVectors[2].x = maxPoint.x;
  58000. this._boundingVectors.push(minPoint.clone());
  58001. this._boundingVectors[3].y = maxPoint.y;
  58002. this._boundingVectors.push(minPoint.clone());
  58003. this._boundingVectors[4].z = maxPoint.z;
  58004. this._boundingVectors.push(maxPoint.clone());
  58005. this._boundingVectors[5].z = minPoint.z;
  58006. this._boundingVectors.push(maxPoint.clone());
  58007. this._boundingVectors[6].x = minPoint.x;
  58008. this._boundingVectors.push(maxPoint.clone());
  58009. this._boundingVectors[7].y = minPoint.y;
  58010. }
  58011. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  58012. // Property
  58013. get: function () {
  58014. return this._capacity;
  58015. },
  58016. enumerable: true,
  58017. configurable: true
  58018. });
  58019. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  58020. get: function () {
  58021. return this._minPoint;
  58022. },
  58023. enumerable: true,
  58024. configurable: true
  58025. });
  58026. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  58027. get: function () {
  58028. return this._maxPoint;
  58029. },
  58030. enumerable: true,
  58031. configurable: true
  58032. });
  58033. // Methods
  58034. OctreeBlock.prototype.addEntry = function (entry) {
  58035. if (this.blocks) {
  58036. for (var index = 0; index < this.blocks.length; index++) {
  58037. var block = this.blocks[index];
  58038. block.addEntry(entry);
  58039. }
  58040. return;
  58041. }
  58042. this._creationFunc(entry, this);
  58043. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  58044. this.createInnerBlocks();
  58045. }
  58046. };
  58047. OctreeBlock.prototype.addEntries = function (entries) {
  58048. for (var index = 0; index < entries.length; index++) {
  58049. var mesh = entries[index];
  58050. this.addEntry(mesh);
  58051. }
  58052. };
  58053. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  58054. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  58055. if (this.blocks) {
  58056. for (var index = 0; index < this.blocks.length; index++) {
  58057. var block = this.blocks[index];
  58058. block.select(frustumPlanes, selection, allowDuplicate);
  58059. }
  58060. return;
  58061. }
  58062. if (allowDuplicate) {
  58063. selection.concat(this.entries);
  58064. }
  58065. else {
  58066. selection.concatWithNoDuplicate(this.entries);
  58067. }
  58068. }
  58069. };
  58070. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  58071. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  58072. if (this.blocks) {
  58073. for (var index = 0; index < this.blocks.length; index++) {
  58074. var block = this.blocks[index];
  58075. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  58076. }
  58077. return;
  58078. }
  58079. if (allowDuplicate) {
  58080. selection.concat(this.entries);
  58081. }
  58082. else {
  58083. selection.concatWithNoDuplicate(this.entries);
  58084. }
  58085. }
  58086. };
  58087. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  58088. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  58089. if (this.blocks) {
  58090. for (var index = 0; index < this.blocks.length; index++) {
  58091. var block = this.blocks[index];
  58092. block.intersectsRay(ray, selection);
  58093. }
  58094. return;
  58095. }
  58096. selection.concatWithNoDuplicate(this.entries);
  58097. }
  58098. };
  58099. OctreeBlock.prototype.createInnerBlocks = function () {
  58100. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  58101. };
  58102. return OctreeBlock;
  58103. }());
  58104. BABYLON.OctreeBlock = OctreeBlock;
  58105. })(BABYLON || (BABYLON = {}));
  58106. //# sourceMappingURL=babylon.octreeBlock.js.map
  58107. var BABYLON;
  58108. (function (BABYLON) {
  58109. var SIMDVector3 = (function () {
  58110. function SIMDVector3() {
  58111. }
  58112. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  58113. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  58114. };
  58115. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  58116. var m = transformation.m;
  58117. var m0 = SIMD.Float32x4.load(m, 0);
  58118. var m1 = SIMD.Float32x4.load(m, 4);
  58119. var m2 = SIMD.Float32x4.load(m, 8);
  58120. var m3 = SIMD.Float32x4.load(m, 12);
  58121. var r = SIMD.Float32x4.add(SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(x), m0), SIMD.Float32x4.mul(SIMD.Float32x4.splat(y), m1)), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(z), m2), m3));
  58122. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  58123. result.x = SIMD.Float32x4.extractLane(r, 0);
  58124. result.y = SIMD.Float32x4.extractLane(r, 1);
  58125. result.z = SIMD.Float32x4.extractLane(r, 2);
  58126. };
  58127. return SIMDVector3;
  58128. }());
  58129. var SIMDMatrix = (function () {
  58130. function SIMDMatrix() {
  58131. }
  58132. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  58133. var tm = this.m;
  58134. var om = other.m;
  58135. var m0 = SIMD.Float32x4.load(om, 0);
  58136. var m1 = SIMD.Float32x4.load(om, 4);
  58137. var m2 = SIMD.Float32x4.load(om, 8);
  58138. var m3 = SIMD.Float32x4.load(om, 12);
  58139. for (var i = 0; i < 16; i += 4) {
  58140. SIMD.Float32x4.store(result, i + offset, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i]), m0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 1]), m1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 2]), m2), SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 3]), m3)))));
  58141. }
  58142. return this;
  58143. };
  58144. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  58145. var src = this.m;
  58146. var dest = other.m;
  58147. // Load the 4 rows
  58148. var src0 = SIMD.Float32x4.load(src, 0);
  58149. var src1 = SIMD.Float32x4.load(src, 4);
  58150. var src2 = SIMD.Float32x4.load(src, 8);
  58151. var src3 = SIMD.Float32x4.load(src, 12);
  58152. // Transpose the source matrix. Sort of. Not a true transpose operation
  58153. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  58154. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  58155. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  58156. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  58157. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  58158. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  58159. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  58160. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  58161. // This is a true transposition, but it will lead to an incorrect result
  58162. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  58163. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  58164. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  58165. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  58166. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  58167. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  58168. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  58169. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  58170. // ----
  58171. tmp1 = SIMD.Float32x4.mul(row2, row3);
  58172. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  58173. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  58174. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  58175. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  58176. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  58177. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  58178. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  58179. // ----
  58180. tmp1 = SIMD.Float32x4.mul(row1, row2);
  58181. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  58182. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  58183. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  58184. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  58185. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  58186. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  58187. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  58188. // ----
  58189. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  58190. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  58191. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  58192. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  58193. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  58194. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  58195. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  58196. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  58197. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  58198. // ----
  58199. tmp1 = SIMD.Float32x4.mul(row0, row1);
  58200. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  58201. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  58202. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  58203. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  58204. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  58205. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  58206. // ----
  58207. tmp1 = SIMD.Float32x4.mul(row0, row3);
  58208. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  58209. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  58210. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  58211. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  58212. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  58213. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  58214. // ----
  58215. tmp1 = SIMD.Float32x4.mul(row0, row2);
  58216. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  58217. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  58218. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  58219. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  58220. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  58221. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  58222. // Compute determinant
  58223. var det = SIMD.Float32x4.mul(row0, minor0);
  58224. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  58225. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  58226. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  58227. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  58228. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  58229. // These shuffles aren't necessary if the faulty transposition is done
  58230. // up at the top of this function.
  58231. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  58232. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  58233. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  58234. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  58235. // Compute final values by multiplying with 1/det
  58236. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  58237. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  58238. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  58239. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  58240. return this;
  58241. };
  58242. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  58243. var out = result.m;
  58244. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  58245. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  58246. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  58247. // cc.kmVec3Subtract(f, pCenter, pEye);
  58248. var f = SIMD.Float32x4.sub(center, eye);
  58249. // cc.kmVec3Normalize(f, f);
  58250. var tmp = SIMD.Float32x4.mul(f, f);
  58251. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  58252. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  58253. // cc.kmVec3Assign(up, pUp);
  58254. // cc.kmVec3Normalize(up, up);
  58255. tmp = SIMD.Float32x4.mul(up, up);
  58256. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  58257. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  58258. // cc.kmVec3Cross(s, f, up);
  58259. 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)));
  58260. // cc.kmVec3Normalize(s, s);
  58261. tmp = SIMD.Float32x4.mul(s, s);
  58262. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  58263. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  58264. // cc.kmVec3Cross(u, s, f);
  58265. 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)));
  58266. // cc.kmVec3Normalize(s, s);
  58267. tmp = SIMD.Float32x4.mul(s, s);
  58268. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  58269. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  58270. var zero = SIMD.Float32x4.splat(0.0);
  58271. s = SIMD.Float32x4.neg(s);
  58272. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  58273. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  58274. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  58275. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  58276. var a2 = SIMD.Float32x4.shuffle(SIMD.Float32x4.shuffle(s, u, 2, 3, 6, 7), SIMD.Float32x4.shuffle(f, zero, 2, 3, 6, 7), 0, 2, 4, 6);
  58277. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  58278. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  58279. SIMD.Float32x4.store(out, 0, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  58280. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  58281. SIMD.Float32x4.store(out, 4, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  58282. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  58283. SIMD.Float32x4.store(out, 8, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  58284. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  58285. SIMD.Float32x4.store(out, 12, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  58286. };
  58287. return SIMDMatrix;
  58288. }());
  58289. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  58290. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  58291. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  58292. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  58293. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  58294. var SIMDHelper = (function () {
  58295. function SIMDHelper() {
  58296. }
  58297. Object.defineProperty(SIMDHelper, "IsEnabled", {
  58298. get: function () {
  58299. return SIMDHelper._isEnabled;
  58300. },
  58301. enumerable: true,
  58302. configurable: true
  58303. });
  58304. SIMDHelper.DisableSIMD = function () {
  58305. // Replace functions
  58306. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  58307. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  58308. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  58309. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  58310. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  58311. SIMDHelper._isEnabled = false;
  58312. };
  58313. SIMDHelper.EnableSIMD = function () {
  58314. if (self.SIMD === undefined) {
  58315. return;
  58316. }
  58317. // check if polyfills needed
  58318. if (!self.Math.fround) {
  58319. self.Math.fround = (function (array) { return function (x) {
  58320. return array[0] = x, array[0];
  58321. }; })(new Float32Array(1));
  58322. }
  58323. if (!self.Math.imul) {
  58324. self.Math.imul = function (a, b) {
  58325. var ah = (a >>> 16) & 0xffff;
  58326. var al = a & 0xffff;
  58327. var bh = (b >>> 16) & 0xffff;
  58328. var bl = b & 0xffff;
  58329. // the shift by 0 fixes the sign on the high part
  58330. // the final |0 converts the unsigned value into a signed value
  58331. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  58332. };
  58333. }
  58334. // Replace functions
  58335. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  58336. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  58337. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  58338. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  58339. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  58340. SIMDHelper._isEnabled = true;
  58341. };
  58342. return SIMDHelper;
  58343. }());
  58344. SIMDHelper._isEnabled = false;
  58345. BABYLON.SIMDHelper = SIMDHelper;
  58346. })(BABYLON || (BABYLON = {}));
  58347. //# sourceMappingURL=babylon.math.SIMD.js.map
  58348. var BABYLON;
  58349. (function (BABYLON) {
  58350. var VRDistortionCorrectionPostProcess = (function (_super) {
  58351. __extends(VRDistortionCorrectionPostProcess, _super);
  58352. //ANY
  58353. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  58354. var _this = _super.call(this, name, "vrDistortionCorrection", [
  58355. 'LensCenter',
  58356. 'Scale',
  58357. 'ScaleIn',
  58358. 'HmdWarpParam'
  58359. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  58360. _this._isRightEye = isRightEye;
  58361. _this._distortionFactors = vrMetrics.distortionK;
  58362. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  58363. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  58364. _this.onSizeChangedObservable.add(function () {
  58365. _this.aspectRatio = _this.width * .5 / _this.height;
  58366. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  58367. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  58368. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  58369. });
  58370. _this.onApplyObservable.add(function (effect) {
  58371. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  58372. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  58373. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  58374. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  58375. });
  58376. return _this;
  58377. }
  58378. return VRDistortionCorrectionPostProcess;
  58379. }(BABYLON.PostProcess));
  58380. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  58381. })(BABYLON || (BABYLON = {}));
  58382. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  58383. var BABYLON;
  58384. (function (BABYLON) {
  58385. var AnaglyphPostProcess = (function (_super) {
  58386. __extends(AnaglyphPostProcess, _super);
  58387. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  58388. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  58389. _this._passedProcess = rigCameras[0]._rigPostProcess;
  58390. _this.onApplyObservable.add(function (effect) {
  58391. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  58392. });
  58393. return _this;
  58394. }
  58395. return AnaglyphPostProcess;
  58396. }(BABYLON.PostProcess));
  58397. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  58398. })(BABYLON || (BABYLON = {}));
  58399. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  58400. var BABYLON;
  58401. (function (BABYLON) {
  58402. var StereoscopicInterlacePostProcess = (function (_super) {
  58403. __extends(StereoscopicInterlacePostProcess, _super);
  58404. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  58405. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  58406. _this._passedProcess = rigCameras[0]._rigPostProcess;
  58407. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  58408. _this.onSizeChangedObservable.add(function () {
  58409. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  58410. });
  58411. _this.onApplyObservable.add(function (effect) {
  58412. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  58413. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  58414. });
  58415. return _this;
  58416. }
  58417. return StereoscopicInterlacePostProcess;
  58418. }(BABYLON.PostProcess));
  58419. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  58420. })(BABYLON || (BABYLON = {}));
  58421. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  58422. var BABYLON;
  58423. (function (BABYLON) {
  58424. var FreeCameraDeviceOrientationInput = (function () {
  58425. function FreeCameraDeviceOrientationInput() {
  58426. var _this = this;
  58427. this._screenOrientationAngle = 0;
  58428. this._screenQuaternion = new BABYLON.Quaternion();
  58429. this._alpha = 0;
  58430. this._beta = 0;
  58431. this._gamma = 0;
  58432. this._orientationChanged = function () {
  58433. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  58434. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  58435. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  58436. };
  58437. this._deviceOrientation = function (evt) {
  58438. _this._alpha = evt.alpha;
  58439. _this._beta = evt.beta;
  58440. _this._gamma = evt.gamma;
  58441. };
  58442. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  58443. this._orientationChanged();
  58444. }
  58445. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  58446. get: function () {
  58447. return this._camera;
  58448. },
  58449. set: function (camera) {
  58450. this._camera = camera;
  58451. if (!this._camera.rotationQuaternion)
  58452. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  58453. },
  58454. enumerable: true,
  58455. configurable: true
  58456. });
  58457. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  58458. window.addEventListener("orientationchange", this._orientationChanged);
  58459. window.addEventListener("deviceorientation", this._deviceOrientation);
  58460. //In certain cases, the attach control is called AFTER orientation was changed,
  58461. //So this is needed.
  58462. this._orientationChanged();
  58463. };
  58464. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  58465. window.removeEventListener("orientationchange", this._orientationChanged);
  58466. window.removeEventListener("deviceorientation", this._deviceOrientation);
  58467. };
  58468. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  58469. //if no device orientation provided, don't update the rotation.
  58470. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  58471. if (!this._alpha)
  58472. return;
  58473. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  58474. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  58475. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  58476. //Mirror on XY Plane
  58477. this._camera.rotationQuaternion.z *= -1;
  58478. this._camera.rotationQuaternion.w *= -1;
  58479. };
  58480. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  58481. return "FreeCameraDeviceOrientationInput";
  58482. };
  58483. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  58484. return "deviceOrientation";
  58485. };
  58486. return FreeCameraDeviceOrientationInput;
  58487. }());
  58488. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  58489. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  58490. })(BABYLON || (BABYLON = {}));
  58491. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  58492. var BABYLON;
  58493. (function (BABYLON) {
  58494. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  58495. function ArcRotateCameraVRDeviceOrientationInput() {
  58496. this.alphaCorrection = 1;
  58497. this.betaCorrection = 1;
  58498. this.gammaCorrection = 1;
  58499. this._alpha = 0;
  58500. this._beta = 0;
  58501. this._gamma = 0;
  58502. this._dirty = false;
  58503. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  58504. }
  58505. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  58506. this.camera.attachControl(element, noPreventDefault);
  58507. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  58508. };
  58509. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  58510. var camera = this.camera;
  58511. this._alpha = +evt.alpha | 0;
  58512. this._beta = +evt.beta | 0;
  58513. this._gamma = +evt.gamma | 0;
  58514. this._dirty = true;
  58515. };
  58516. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  58517. if (this._dirty) {
  58518. this._dirty = false;
  58519. if (this._gamma < 0) {
  58520. this._gamma = 180 + this._gamma;
  58521. }
  58522. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  58523. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  58524. }
  58525. };
  58526. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  58527. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  58528. };
  58529. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  58530. return "ArcRotateCameraVRDeviceOrientationInput";
  58531. };
  58532. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  58533. return "VRDeviceOrientation";
  58534. };
  58535. return ArcRotateCameraVRDeviceOrientationInput;
  58536. }());
  58537. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  58538. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  58539. })(BABYLON || (BABYLON = {}));
  58540. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  58541. var BABYLON;
  58542. (function (BABYLON) {
  58543. var VRCameraMetrics = (function () {
  58544. function VRCameraMetrics() {
  58545. this.compensateDistortion = true;
  58546. }
  58547. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  58548. get: function () {
  58549. return this.hResolution / (2 * this.vResolution);
  58550. },
  58551. enumerable: true,
  58552. configurable: true
  58553. });
  58554. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  58555. get: function () {
  58556. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  58557. },
  58558. enumerable: true,
  58559. configurable: true
  58560. });
  58561. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  58562. get: function () {
  58563. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  58564. var h = (4 * meters) / this.hScreenSize;
  58565. return BABYLON.Matrix.Translation(h, 0, 0);
  58566. },
  58567. enumerable: true,
  58568. configurable: true
  58569. });
  58570. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  58571. get: function () {
  58572. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  58573. var h = (4 * meters) / this.hScreenSize;
  58574. return BABYLON.Matrix.Translation(-h, 0, 0);
  58575. },
  58576. enumerable: true,
  58577. configurable: true
  58578. });
  58579. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  58580. get: function () {
  58581. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  58582. },
  58583. enumerable: true,
  58584. configurable: true
  58585. });
  58586. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  58587. get: function () {
  58588. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  58589. },
  58590. enumerable: true,
  58591. configurable: true
  58592. });
  58593. VRCameraMetrics.GetDefault = function () {
  58594. var result = new VRCameraMetrics();
  58595. result.hResolution = 1280;
  58596. result.vResolution = 800;
  58597. result.hScreenSize = 0.149759993;
  58598. result.vScreenSize = 0.0935999975;
  58599. result.vScreenCenter = 0.0467999987;
  58600. result.eyeToScreenDistance = 0.0410000011;
  58601. result.lensSeparationDistance = 0.0635000020;
  58602. result.interpupillaryDistance = 0.0640000030;
  58603. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  58604. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  58605. result.postProcessScaleFactor = 1.714605507808412;
  58606. result.lensCenterOffset = 0.151976421;
  58607. return result;
  58608. };
  58609. return VRCameraMetrics;
  58610. }());
  58611. BABYLON.VRCameraMetrics = VRCameraMetrics;
  58612. })(BABYLON || (BABYLON = {}));
  58613. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  58614. var BABYLON;
  58615. (function (BABYLON) {
  58616. var WebVRFreeCamera = (function (_super) {
  58617. __extends(WebVRFreeCamera, _super);
  58618. function WebVRFreeCamera(name, position, scene, webVROptions) {
  58619. if (webVROptions === void 0) { webVROptions = {}; }
  58620. var _this = _super.call(this, name, position, scene) || this;
  58621. _this.webVROptions = webVROptions;
  58622. _this._vrDevice = null;
  58623. _this.rawPose = null;
  58624. _this._vrEnabled = false;
  58625. _this._specsVersion = 1.1;
  58626. _this._attached = false;
  58627. _this._positionOffset = BABYLON.Vector3.Zero();
  58628. _this._descendants = [];
  58629. _this.devicePosition = BABYLON.Vector3.Zero();
  58630. _this.deviceScaleFactor = 1;
  58631. _this.controllers = [];
  58632. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  58633. //legacy support - the compensation boolean was removed.
  58634. if (arguments.length === 5) {
  58635. _this.webVROptions = arguments[4];
  58636. }
  58637. // default webVR options
  58638. if (_this.webVROptions.trackPosition == undefined) {
  58639. _this.webVROptions.trackPosition = true;
  58640. }
  58641. if (_this.webVROptions.controllerMeshes == undefined) {
  58642. _this.webVROptions.controllerMeshes = true;
  58643. }
  58644. if (_this.webVROptions.defaultLightningOnControllers == undefined) {
  58645. _this.webVROptions.defaultLightningOnControllers = true;
  58646. }
  58647. _this.rotationQuaternion = new BABYLON.Quaternion();
  58648. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  58649. if (_this.webVROptions && _this.webVROptions.positionScale) {
  58650. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  58651. }
  58652. //enable VR
  58653. _this.getEngine().initWebVR();
  58654. //check specs version
  58655. if (!window.VRFrameData) {
  58656. _this._specsVersion = 1.0;
  58657. _this._frameData = {};
  58658. }
  58659. else {
  58660. _this._frameData = new VRFrameData();
  58661. }
  58662. _this.getEngine().getVRDevice(_this.webVROptions.displayName, function (device) {
  58663. if (!device) {
  58664. return;
  58665. }
  58666. _this._vrEnabled = true;
  58667. _this._vrDevice = device;
  58668. //reset the rig parameters.
  58669. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  58670. if (_this._attached) {
  58671. _this.getEngine().enableVR(_this._vrDevice);
  58672. }
  58673. });
  58674. // try to attach the controllers, if found.
  58675. _this.initControllers();
  58676. /**
  58677. * The idea behind the following lines:
  58678. * objects that have the camera as parent should actually have the rig cameras as a parent.
  58679. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  58680. * the second will not show it correctly.
  58681. *
  58682. * To solve this - each object that has the camera as parent will be added to a protected array.
  58683. * When the rig camera renders, it will take this array and set all of those to be its children.
  58684. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  58685. * Amazing!
  58686. */
  58687. scene.onBeforeCameraRenderObservable.add(function (camera) {
  58688. if (camera.parent === _this && _this.rigParenting) {
  58689. _this._descendants = _this.getDescendants(true, function (n) {
  58690. // don't take the cameras or the controllers!
  58691. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  58692. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  58693. return !isController && !isRigCamera;
  58694. });
  58695. _this._descendants.forEach(function (node) {
  58696. node.parent = camera;
  58697. });
  58698. }
  58699. });
  58700. scene.onAfterCameraRenderObservable.add(function (camera) {
  58701. if (camera.parent === _this && _this.rigParenting) {
  58702. _this._descendants.forEach(function (node) {
  58703. node.parent = _this;
  58704. });
  58705. }
  58706. });
  58707. return _this;
  58708. }
  58709. Object.defineProperty(WebVRFreeCamera.prototype, "onControllersAttached", {
  58710. set: function (callback) {
  58711. this._onControllersAttached = callback;
  58712. // after setting - if the controllers are already set, execute the callback.
  58713. if (this.controllers.length >= 2) {
  58714. callback(this.controllers);
  58715. }
  58716. },
  58717. enumerable: true,
  58718. configurable: true
  58719. });
  58720. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  58721. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  58722. var gp = _a[_i];
  58723. if (gp.hand === name) {
  58724. return gp;
  58725. }
  58726. }
  58727. return undefined;
  58728. };
  58729. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  58730. get: function () {
  58731. if (!this._leftController) {
  58732. this._leftController = this.getControllerByName("left");
  58733. }
  58734. return this._leftController;
  58735. },
  58736. enumerable: true,
  58737. configurable: true
  58738. });
  58739. ;
  58740. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  58741. get: function () {
  58742. if (!this._rightController) {
  58743. this._rightController = this.getControllerByName("right");
  58744. }
  58745. return this._rightController;
  58746. },
  58747. enumerable: true,
  58748. configurable: true
  58749. });
  58750. ;
  58751. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  58752. if (length === void 0) { length = 100; }
  58753. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  58754. };
  58755. WebVRFreeCamera.prototype._checkInputs = function () {
  58756. if (this._vrEnabled) {
  58757. if (this._specsVersion === 1.1) {
  58758. this._vrDevice.getFrameData(this._frameData);
  58759. }
  58760. else {
  58761. //backwards comp
  58762. var pose = this._vrDevice.getPose();
  58763. this._frameData.pose = pose;
  58764. // calculate view and projection matrix
  58765. }
  58766. this.updateFromDevice(this._frameData.pose);
  58767. }
  58768. _super.prototype._checkInputs.call(this);
  58769. };
  58770. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  58771. if (poseData && poseData.orientation) {
  58772. this.rawPose = poseData;
  58773. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  58774. if (this.getScene().useRightHandedSystem) {
  58775. this.deviceRotationQuaternion.z *= -1;
  58776. this.deviceRotationQuaternion.w *= -1;
  58777. }
  58778. if (this.webVROptions.trackPosition && this.rawPose.position) {
  58779. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  58780. if (this.getScene().useRightHandedSystem) {
  58781. this.devicePosition.z *= -1;
  58782. }
  58783. }
  58784. }
  58785. };
  58786. /**
  58787. * WebVR's attach control will start broadcasting frames to the device.
  58788. * Note that in certain browsers (chrome for example) this function must be called
  58789. * within a user-interaction callback. Example:
  58790. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  58791. *
  58792. * @param {HTMLElement} element
  58793. * @param {boolean} [noPreventDefault]
  58794. *
  58795. * @memberOf WebVRFreeCamera
  58796. */
  58797. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  58798. _super.prototype.attachControl.call(this, element, noPreventDefault);
  58799. this._attached = true;
  58800. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  58801. if (this._vrEnabled) {
  58802. this.getEngine().enableVR(this._vrDevice);
  58803. }
  58804. };
  58805. WebVRFreeCamera.prototype.detachControl = function (element) {
  58806. _super.prototype.detachControl.call(this, element);
  58807. this._vrEnabled = false;
  58808. this._attached = false;
  58809. this.getEngine().disableVR();
  58810. };
  58811. WebVRFreeCamera.prototype.getClassName = function () {
  58812. return "WebVRFreeCamera";
  58813. };
  58814. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  58815. //uses the vrDisplay's "resetPose()".
  58816. //pitch and roll won't be affected.
  58817. this._vrDevice.resetPose();
  58818. };
  58819. WebVRFreeCamera.prototype._updateRigCameras = function () {
  58820. var camLeft = this._rigCameras[0];
  58821. var camRight = this._rigCameras[1];
  58822. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  58823. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  58824. camLeft.position.copyFrom(this.devicePosition);
  58825. camRight.position.copyFrom(this.devicePosition);
  58826. };
  58827. /**
  58828. * This function is called by the two RIG cameras.
  58829. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  58830. */
  58831. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  58832. var _this = this;
  58833. //WebVR 1.0
  58834. if (this._cameraRigParams["specs"] === 1.0) {
  58835. this._updateCameraRotationMatrix();
  58836. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  58837. // Computing target and final matrix
  58838. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  58839. if (this.getScene().useRightHandedSystem) {
  58840. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  58841. }
  58842. else {
  58843. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  58844. }
  58845. //now move the eye in the right direction
  58846. var eyeParams = this._cameraRigParams["eyeParameters"];
  58847. var offset = eyeParams.offset;
  58848. // it will actually always be 0, but just in case
  58849. if (this.getScene().useRightHandedSystem) {
  58850. offset[2] *= -1;
  58851. }
  58852. BABYLON.Matrix.TranslationToRef(-offset[0], offset[1], -offset[2], BABYLON.Tmp.Matrix[0]);
  58853. this._webvrViewMatrix.multiplyToRef(BABYLON.Tmp.Matrix[0], this._webvrViewMatrix);
  58854. }
  58855. else {
  58856. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  58857. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  58858. if (!this.getScene().useRightHandedSystem) {
  58859. [2, 6, 8, 9, 14].forEach(function (num) {
  58860. _this._webvrViewMatrix.m[num] *= -1;
  58861. });
  58862. }
  58863. // update the camera rotation matrix
  58864. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  58865. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  58866. // Computing target and final matrix
  58867. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  58868. }
  58869. var parentCamera = this._cameraRigParams["parentCamera"];
  58870. // should the view matrix be updated with scale and position offset?
  58871. if (parentCamera.deviceScaleFactor !== 1) {
  58872. this._webvrViewMatrix.invert();
  58873. // scale the position, if set
  58874. if (parentCamera.deviceScaleFactor) {
  58875. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  58876. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  58877. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  58878. }
  58879. this._webvrViewMatrix.invert();
  58880. }
  58881. return this._webvrViewMatrix;
  58882. };
  58883. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  58884. var _this = this;
  58885. if (this._cameraRigParams["specs"] === 1.0) {
  58886. var eyeParams = this._cameraRigParams["eyeParameters"];
  58887. // deprecated!!
  58888. BABYLON.Matrix.PerspectiveFovWebVRToRef(eyeParams.fieldOfView, 0.1, 1000, this._projectionMatrix, this.getScene().useRightHandedSystem);
  58889. }
  58890. else {
  58891. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  58892. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  58893. //babylon compatible matrix
  58894. if (!this.getScene().useRightHandedSystem) {
  58895. [8, 9, 10, 11].forEach(function (num) {
  58896. _this._projectionMatrix.m[num] *= -1;
  58897. });
  58898. }
  58899. }
  58900. return this._projectionMatrix;
  58901. };
  58902. WebVRFreeCamera.prototype.initControllers = function () {
  58903. var _this = this;
  58904. this.controllers = [];
  58905. new BABYLON.Gamepads(function (gp) {
  58906. if (gp.type === BABYLON.Gamepad.POSE_ENABLED) {
  58907. var webVrController = gp;
  58908. if (_this.webVROptions.controllerMeshes) {
  58909. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  58910. if (_this.webVROptions.defaultLightningOnControllers) {
  58911. if (!_this._lightOnControllers) {
  58912. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  58913. }
  58914. loadedMesh.getChildren().forEach(function (mesh) {
  58915. _this._lightOnControllers.includedOnlyMeshes.push(mesh);
  58916. });
  58917. }
  58918. });
  58919. }
  58920. webVrController.attachToPoseControlledCamera(_this);
  58921. // since this is async - sanity check. Is the controller already stored?
  58922. if (_this.controllers.indexOf(webVrController) === -1) {
  58923. //add to the controllers array
  58924. _this.controllers.push(webVrController);
  58925. //did we find enough controllers? Great! let the developer know.
  58926. if (_this._onControllersAttached && _this.controllers.length >= 2) {
  58927. _this._onControllersAttached(_this.controllers);
  58928. }
  58929. }
  58930. }
  58931. });
  58932. };
  58933. return WebVRFreeCamera;
  58934. }(BABYLON.FreeCamera));
  58935. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  58936. })(BABYLON || (BABYLON = {}));
  58937. //# sourceMappingURL=babylon.webVRCamera.js.map
  58938. /// <reference path="babylon.freeCamera.ts" />
  58939. var BABYLON;
  58940. (function (BABYLON) {
  58941. // We're mainly based on the logic defined into the FreeCamera code
  58942. var DeviceOrientationCamera = (function (_super) {
  58943. __extends(DeviceOrientationCamera, _super);
  58944. function DeviceOrientationCamera(name, position, scene) {
  58945. var _this = _super.call(this, name, position, scene) || this;
  58946. _this._quaternionCache = new BABYLON.Quaternion();
  58947. _this.inputs.addDeviceOrientation();
  58948. return _this;
  58949. }
  58950. DeviceOrientationCamera.prototype.getClassName = function () {
  58951. return "DeviceOrientationCamera";
  58952. };
  58953. DeviceOrientationCamera.prototype._checkInputs = function () {
  58954. _super.prototype._checkInputs.call(this);
  58955. this._quaternionCache.copyFrom(this.rotationQuaternion);
  58956. if (this._initialQuaternion) {
  58957. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  58958. }
  58959. };
  58960. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  58961. var _this = this;
  58962. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  58963. //can only work if this camera has a rotation quaternion already.
  58964. if (!this.rotationQuaternion)
  58965. return;
  58966. if (!this._initialQuaternion) {
  58967. this._initialQuaternion = new BABYLON.Quaternion();
  58968. }
  58969. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  58970. ['x', 'y', 'z'].forEach(function (axisName) {
  58971. if (!axis[axisName]) {
  58972. _this._initialQuaternion[axisName] = 0;
  58973. }
  58974. else {
  58975. _this._initialQuaternion[axisName] *= -1;
  58976. }
  58977. });
  58978. this._initialQuaternion.normalize();
  58979. //force rotation update
  58980. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  58981. };
  58982. return DeviceOrientationCamera;
  58983. }(BABYLON.FreeCamera));
  58984. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  58985. })(BABYLON || (BABYLON = {}));
  58986. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  58987. var BABYLON;
  58988. (function (BABYLON) {
  58989. var VRDeviceOrientationFreeCamera = (function (_super) {
  58990. __extends(VRDeviceOrientationFreeCamera, _super);
  58991. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  58992. if (compensateDistortion === void 0) { compensateDistortion = true; }
  58993. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  58994. var _this = _super.call(this, name, position, scene) || this;
  58995. vrCameraMetrics.compensateDistortion = compensateDistortion;
  58996. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  58997. return _this;
  58998. }
  58999. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  59000. return "VRDeviceOrientationFreeCamera";
  59001. };
  59002. return VRDeviceOrientationFreeCamera;
  59003. }(BABYLON.DeviceOrientationCamera));
  59004. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  59005. var VRDeviceOrientationGamepadCamera = (function (_super) {
  59006. __extends(VRDeviceOrientationGamepadCamera, _super);
  59007. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  59008. if (compensateDistortion === void 0) { compensateDistortion = true; }
  59009. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  59010. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  59011. _this.inputs.addGamepad();
  59012. return _this;
  59013. }
  59014. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  59015. return "VRDeviceOrientationGamepadCamera";
  59016. };
  59017. return VRDeviceOrientationGamepadCamera;
  59018. }(VRDeviceOrientationFreeCamera));
  59019. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  59020. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  59021. __extends(VRDeviceOrientationArcRotateCamera, _super);
  59022. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  59023. if (compensateDistortion === void 0) { compensateDistortion = true; }
  59024. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  59025. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  59026. vrCameraMetrics.compensateDistortion = compensateDistortion;
  59027. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  59028. _this.inputs.addVRDeviceOrientation();
  59029. return _this;
  59030. }
  59031. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  59032. return "VRDeviceOrientationArcRotateCamera";
  59033. };
  59034. return VRDeviceOrientationArcRotateCamera;
  59035. }(BABYLON.ArcRotateCamera));
  59036. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  59037. })(BABYLON || (BABYLON = {}));
  59038. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  59039. /// <reference path="babylon.freeCamera.ts" />
  59040. /// <reference path="babylon.arcRotateCamera.ts" />
  59041. /// <reference path="babylon.gamepadCamera.ts" />
  59042. /// <reference path="babylon.universalCamera.ts" />
  59043. var BABYLON;
  59044. (function (BABYLON) {
  59045. var AnaglyphFreeCamera = (function (_super) {
  59046. __extends(AnaglyphFreeCamera, _super);
  59047. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  59048. var _this = _super.call(this, name, position, scene) || this;
  59049. _this.interaxialDistance = interaxialDistance;
  59050. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  59051. return _this;
  59052. }
  59053. AnaglyphFreeCamera.prototype.getClassName = function () {
  59054. return "AnaglyphFreeCamera";
  59055. };
  59056. return AnaglyphFreeCamera;
  59057. }(BABYLON.FreeCamera));
  59058. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  59059. var AnaglyphArcRotateCamera = (function (_super) {
  59060. __extends(AnaglyphArcRotateCamera, _super);
  59061. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  59062. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  59063. _this.interaxialDistance = interaxialDistance;
  59064. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  59065. return _this;
  59066. }
  59067. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  59068. return "AnaglyphArcRotateCamera";
  59069. };
  59070. return AnaglyphArcRotateCamera;
  59071. }(BABYLON.ArcRotateCamera));
  59072. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  59073. var AnaglyphGamepadCamera = (function (_super) {
  59074. __extends(AnaglyphGamepadCamera, _super);
  59075. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  59076. var _this = _super.call(this, name, position, scene) || this;
  59077. _this.interaxialDistance = interaxialDistance;
  59078. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  59079. return _this;
  59080. }
  59081. AnaglyphGamepadCamera.prototype.getClassName = function () {
  59082. return "AnaglyphGamepadCamera";
  59083. };
  59084. return AnaglyphGamepadCamera;
  59085. }(BABYLON.GamepadCamera));
  59086. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  59087. var AnaglyphUniversalCamera = (function (_super) {
  59088. __extends(AnaglyphUniversalCamera, _super);
  59089. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  59090. var _this = _super.call(this, name, position, scene) || this;
  59091. _this.interaxialDistance = interaxialDistance;
  59092. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  59093. return _this;
  59094. }
  59095. AnaglyphUniversalCamera.prototype.getClassName = function () {
  59096. return "AnaglyphUniversalCamera";
  59097. };
  59098. return AnaglyphUniversalCamera;
  59099. }(BABYLON.UniversalCamera));
  59100. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  59101. var StereoscopicFreeCamera = (function (_super) {
  59102. __extends(StereoscopicFreeCamera, _super);
  59103. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  59104. var _this = _super.call(this, name, position, scene) || this;
  59105. _this.interaxialDistance = interaxialDistance;
  59106. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  59107. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  59108. return _this;
  59109. }
  59110. StereoscopicFreeCamera.prototype.getClassName = function () {
  59111. return "StereoscopicFreeCamera";
  59112. };
  59113. return StereoscopicFreeCamera;
  59114. }(BABYLON.FreeCamera));
  59115. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  59116. var StereoscopicArcRotateCamera = (function (_super) {
  59117. __extends(StereoscopicArcRotateCamera, _super);
  59118. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  59119. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  59120. _this.interaxialDistance = interaxialDistance;
  59121. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  59122. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  59123. return _this;
  59124. }
  59125. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  59126. return "StereoscopicArcRotateCamera";
  59127. };
  59128. return StereoscopicArcRotateCamera;
  59129. }(BABYLON.ArcRotateCamera));
  59130. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  59131. var StereoscopicGamepadCamera = (function (_super) {
  59132. __extends(StereoscopicGamepadCamera, _super);
  59133. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  59134. var _this = _super.call(this, name, position, scene) || this;
  59135. _this.interaxialDistance = interaxialDistance;
  59136. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  59137. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  59138. return _this;
  59139. }
  59140. StereoscopicGamepadCamera.prototype.getClassName = function () {
  59141. return "StereoscopicGamepadCamera";
  59142. };
  59143. return StereoscopicGamepadCamera;
  59144. }(BABYLON.GamepadCamera));
  59145. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  59146. var StereoscopicUniversalCamera = (function (_super) {
  59147. __extends(StereoscopicUniversalCamera, _super);
  59148. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  59149. var _this = _super.call(this, name, position, scene) || this;
  59150. _this.interaxialDistance = interaxialDistance;
  59151. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  59152. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  59153. return _this;
  59154. }
  59155. StereoscopicUniversalCamera.prototype.getClassName = function () {
  59156. return "StereoscopicUniversalCamera";
  59157. };
  59158. return StereoscopicUniversalCamera;
  59159. }(BABYLON.UniversalCamera));
  59160. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  59161. })(BABYLON || (BABYLON = {}));
  59162. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  59163. // Mainly based on these 2 articles :
  59164. // 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
  59165. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  59166. var BABYLON;
  59167. (function (BABYLON) {
  59168. var JoystickAxis;
  59169. (function (JoystickAxis) {
  59170. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  59171. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  59172. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  59173. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  59174. var VirtualJoystick = (function () {
  59175. function VirtualJoystick(leftJoystick) {
  59176. var _this = this;
  59177. if (leftJoystick) {
  59178. this._leftJoystick = true;
  59179. }
  59180. else {
  59181. this._leftJoystick = false;
  59182. }
  59183. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  59184. VirtualJoystick._globalJoystickIndex++;
  59185. // By default left & right arrow keys are moving the X
  59186. // and up & down keys are moving the Y
  59187. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  59188. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  59189. this.reverseLeftRight = false;
  59190. this.reverseUpDown = false;
  59191. // collections of pointers
  59192. this._touches = new BABYLON.StringDictionary();
  59193. this.deltaPosition = BABYLON.Vector3.Zero();
  59194. this._joystickSensibility = 25;
  59195. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  59196. this._rotationSpeed = 25;
  59197. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  59198. this._rotateOnAxisRelativeToMesh = false;
  59199. this._onResize = function (evt) {
  59200. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  59201. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  59202. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  59203. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  59204. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  59205. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  59206. };
  59207. // injecting a canvas element on top of the canvas 3D game
  59208. if (!VirtualJoystick.vjCanvas) {
  59209. window.addEventListener("resize", this._onResize, false);
  59210. VirtualJoystick.vjCanvas = document.createElement("canvas");
  59211. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  59212. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  59213. VirtualJoystick.vjCanvas.width = window.innerWidth;
  59214. VirtualJoystick.vjCanvas.height = window.innerHeight;
  59215. VirtualJoystick.vjCanvas.style.width = "100%";
  59216. VirtualJoystick.vjCanvas.style.height = "100%";
  59217. VirtualJoystick.vjCanvas.style.position = "absolute";
  59218. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  59219. VirtualJoystick.vjCanvas.style.top = "0px";
  59220. VirtualJoystick.vjCanvas.style.left = "0px";
  59221. VirtualJoystick.vjCanvas.style.zIndex = "5";
  59222. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  59223. // Support for jQuery PEP polyfill
  59224. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  59225. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  59226. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  59227. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  59228. document.body.appendChild(VirtualJoystick.vjCanvas);
  59229. }
  59230. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  59231. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  59232. this.pressed = false;
  59233. // default joystick color
  59234. this._joystickColor = "cyan";
  59235. this._joystickPointerID = -1;
  59236. // current joystick position
  59237. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  59238. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  59239. // origin joystick position
  59240. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  59241. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  59242. this._onPointerDownHandlerRef = function (evt) {
  59243. _this._onPointerDown(evt);
  59244. };
  59245. this._onPointerMoveHandlerRef = function (evt) {
  59246. _this._onPointerMove(evt);
  59247. };
  59248. this._onPointerOutHandlerRef = function (evt) {
  59249. _this._onPointerUp(evt);
  59250. };
  59251. this._onPointerUpHandlerRef = function (evt) {
  59252. _this._onPointerUp(evt);
  59253. };
  59254. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  59255. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  59256. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  59257. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  59258. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  59259. evt.preventDefault(); // Disables system menu
  59260. }, false);
  59261. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  59262. }
  59263. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  59264. this._joystickSensibility = newJoystickSensibility;
  59265. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  59266. };
  59267. VirtualJoystick.prototype._onPointerDown = function (e) {
  59268. var positionOnScreenCondition;
  59269. e.preventDefault();
  59270. if (this._leftJoystick === true) {
  59271. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  59272. }
  59273. else {
  59274. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  59275. }
  59276. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  59277. // First contact will be dedicated to the virtual joystick
  59278. this._joystickPointerID = e.pointerId;
  59279. this._joystickPointerStartPos.x = e.clientX;
  59280. this._joystickPointerStartPos.y = e.clientY;
  59281. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  59282. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  59283. this._deltaJoystickVector.x = 0;
  59284. this._deltaJoystickVector.y = 0;
  59285. this.pressed = true;
  59286. this._touches.add(e.pointerId.toString(), e);
  59287. }
  59288. else {
  59289. // You can only trigger the action buttons with a joystick declared
  59290. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  59291. this._action();
  59292. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  59293. }
  59294. }
  59295. };
  59296. VirtualJoystick.prototype._onPointerMove = function (e) {
  59297. // If the current pointer is the one associated to the joystick (first touch contact)
  59298. if (this._joystickPointerID == e.pointerId) {
  59299. this._joystickPointerPos.x = e.clientX;
  59300. this._joystickPointerPos.y = e.clientY;
  59301. this._deltaJoystickVector = this._joystickPointerPos.clone();
  59302. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  59303. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  59304. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  59305. switch (this._axisTargetedByLeftAndRight) {
  59306. case JoystickAxis.X:
  59307. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  59308. break;
  59309. case JoystickAxis.Y:
  59310. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  59311. break;
  59312. case JoystickAxis.Z:
  59313. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  59314. break;
  59315. }
  59316. var directionUpDown = this.reverseUpDown ? 1 : -1;
  59317. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  59318. switch (this._axisTargetedByUpAndDown) {
  59319. case JoystickAxis.X:
  59320. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  59321. break;
  59322. case JoystickAxis.Y:
  59323. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  59324. break;
  59325. case JoystickAxis.Z:
  59326. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  59327. break;
  59328. }
  59329. }
  59330. else {
  59331. var data = this._touches.get(e.pointerId.toString());
  59332. if (data) {
  59333. data.x = e.clientX;
  59334. data.y = e.clientY;
  59335. }
  59336. }
  59337. };
  59338. VirtualJoystick.prototype._onPointerUp = function (e) {
  59339. if (this._joystickPointerID == e.pointerId) {
  59340. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  59341. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  59342. this._joystickPointerID = -1;
  59343. this.pressed = false;
  59344. }
  59345. else {
  59346. var touch = this._touches.get(e.pointerId.toString());
  59347. if (touch) {
  59348. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  59349. }
  59350. }
  59351. this._deltaJoystickVector.x = 0;
  59352. this._deltaJoystickVector.y = 0;
  59353. this._touches.remove(e.pointerId.toString());
  59354. };
  59355. /**
  59356. * Change the color of the virtual joystick
  59357. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  59358. */
  59359. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  59360. this._joystickColor = newColor;
  59361. };
  59362. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  59363. this._action = action;
  59364. };
  59365. // Define which axis you'd like to control for left & right
  59366. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  59367. switch (axis) {
  59368. case JoystickAxis.X:
  59369. case JoystickAxis.Y:
  59370. case JoystickAxis.Z:
  59371. this._axisTargetedByLeftAndRight = axis;
  59372. break;
  59373. default:
  59374. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  59375. break;
  59376. }
  59377. };
  59378. // Define which axis you'd like to control for up & down
  59379. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  59380. switch (axis) {
  59381. case JoystickAxis.X:
  59382. case JoystickAxis.Y:
  59383. case JoystickAxis.Z:
  59384. this._axisTargetedByUpAndDown = axis;
  59385. break;
  59386. default:
  59387. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  59388. break;
  59389. }
  59390. };
  59391. VirtualJoystick.prototype._clearCanvas = function () {
  59392. if (this._leftJoystick) {
  59393. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  59394. }
  59395. else {
  59396. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  59397. }
  59398. };
  59399. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  59400. var _this = this;
  59401. if (this.pressed) {
  59402. this._touches.forEach(function (key, touch) {
  59403. if (touch.pointerId === _this._joystickPointerID) {
  59404. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  59405. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  59406. VirtualJoystick.vjCanvasContext.beginPath();
  59407. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  59408. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  59409. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  59410. VirtualJoystick.vjCanvasContext.stroke();
  59411. VirtualJoystick.vjCanvasContext.closePath();
  59412. VirtualJoystick.vjCanvasContext.beginPath();
  59413. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  59414. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  59415. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  59416. VirtualJoystick.vjCanvasContext.stroke();
  59417. VirtualJoystick.vjCanvasContext.closePath();
  59418. VirtualJoystick.vjCanvasContext.beginPath();
  59419. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  59420. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  59421. VirtualJoystick.vjCanvasContext.stroke();
  59422. VirtualJoystick.vjCanvasContext.closePath();
  59423. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  59424. }
  59425. else {
  59426. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  59427. VirtualJoystick.vjCanvasContext.beginPath();
  59428. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  59429. VirtualJoystick.vjCanvasContext.beginPath();
  59430. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  59431. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  59432. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  59433. VirtualJoystick.vjCanvasContext.stroke();
  59434. VirtualJoystick.vjCanvasContext.closePath();
  59435. touch.prevX = touch.x;
  59436. touch.prevY = touch.y;
  59437. }
  59438. ;
  59439. });
  59440. }
  59441. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  59442. };
  59443. VirtualJoystick.prototype.releaseCanvas = function () {
  59444. if (VirtualJoystick.vjCanvas) {
  59445. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  59446. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  59447. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  59448. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  59449. window.removeEventListener("resize", this._onResize);
  59450. document.body.removeChild(VirtualJoystick.vjCanvas);
  59451. VirtualJoystick.vjCanvas = null;
  59452. }
  59453. };
  59454. return VirtualJoystick;
  59455. }());
  59456. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  59457. VirtualJoystick._globalJoystickIndex = 0;
  59458. BABYLON.VirtualJoystick = VirtualJoystick;
  59459. })(BABYLON || (BABYLON = {}));
  59460. //# sourceMappingURL=babylon.virtualJoystick.js.map
  59461. var BABYLON;
  59462. (function (BABYLON) {
  59463. // We're mainly based on the logic defined into the FreeCamera code
  59464. var VirtualJoysticksCamera = (function (_super) {
  59465. __extends(VirtualJoysticksCamera, _super);
  59466. function VirtualJoysticksCamera(name, position, scene) {
  59467. var _this = _super.call(this, name, position, scene) || this;
  59468. _this.inputs.addVirtualJoystick();
  59469. return _this;
  59470. }
  59471. VirtualJoysticksCamera.prototype.getClassName = function () {
  59472. return "VirtualJoysticksCamera";
  59473. };
  59474. return VirtualJoysticksCamera;
  59475. }(BABYLON.FreeCamera));
  59476. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  59477. })(BABYLON || (BABYLON = {}));
  59478. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  59479. var BABYLON;
  59480. (function (BABYLON) {
  59481. var FreeCameraVirtualJoystickInput = (function () {
  59482. function FreeCameraVirtualJoystickInput() {
  59483. }
  59484. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  59485. return this._leftjoystick;
  59486. };
  59487. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  59488. return this._rightjoystick;
  59489. };
  59490. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  59491. if (this._leftjoystick) {
  59492. var camera = this.camera;
  59493. var speed = camera._computeLocalCameraSpeed() * 50;
  59494. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  59495. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  59496. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  59497. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  59498. if (!this._leftjoystick.pressed) {
  59499. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  59500. }
  59501. if (!this._rightjoystick.pressed) {
  59502. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  59503. }
  59504. }
  59505. };
  59506. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  59507. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  59508. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  59509. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  59510. this._leftjoystick.setJoystickSensibility(0.15);
  59511. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  59512. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  59513. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  59514. this._rightjoystick.reverseUpDown = true;
  59515. this._rightjoystick.setJoystickSensibility(0.05);
  59516. this._rightjoystick.setJoystickColor("yellow");
  59517. };
  59518. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  59519. this._leftjoystick.releaseCanvas();
  59520. this._rightjoystick.releaseCanvas();
  59521. };
  59522. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  59523. return "FreeCameraVirtualJoystickInput";
  59524. };
  59525. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  59526. return "virtualJoystick";
  59527. };
  59528. return FreeCameraVirtualJoystickInput;
  59529. }());
  59530. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  59531. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  59532. })(BABYLON || (BABYLON = {}));
  59533. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  59534. var BABYLON;
  59535. (function (BABYLON) {
  59536. var SimplificationSettings = (function () {
  59537. function SimplificationSettings(quality, distance, optimizeMesh) {
  59538. this.quality = quality;
  59539. this.distance = distance;
  59540. this.optimizeMesh = optimizeMesh;
  59541. }
  59542. return SimplificationSettings;
  59543. }());
  59544. BABYLON.SimplificationSettings = SimplificationSettings;
  59545. var SimplificationQueue = (function () {
  59546. function SimplificationQueue() {
  59547. this.running = false;
  59548. this._simplificationArray = [];
  59549. }
  59550. SimplificationQueue.prototype.addTask = function (task) {
  59551. this._simplificationArray.push(task);
  59552. };
  59553. SimplificationQueue.prototype.executeNext = function () {
  59554. var task = this._simplificationArray.pop();
  59555. if (task) {
  59556. this.running = true;
  59557. this.runSimplification(task);
  59558. }
  59559. else {
  59560. this.running = false;
  59561. }
  59562. };
  59563. SimplificationQueue.prototype.runSimplification = function (task) {
  59564. var _this = this;
  59565. if (task.parallelProcessing) {
  59566. //parallel simplifier
  59567. task.settings.forEach(function (setting) {
  59568. var simplifier = _this.getSimplifier(task);
  59569. simplifier.simplify(setting, function (newMesh) {
  59570. task.mesh.addLODLevel(setting.distance, newMesh);
  59571. newMesh.isVisible = true;
  59572. //check if it is the last
  59573. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  59574. //all done, run the success callback.
  59575. task.successCallback();
  59576. }
  59577. _this.executeNext();
  59578. });
  59579. });
  59580. }
  59581. else {
  59582. //single simplifier.
  59583. var simplifier = this.getSimplifier(task);
  59584. var runDecimation = function (setting, callback) {
  59585. simplifier.simplify(setting, function (newMesh) {
  59586. task.mesh.addLODLevel(setting.distance, newMesh);
  59587. newMesh.isVisible = true;
  59588. //run the next quality level
  59589. callback();
  59590. });
  59591. };
  59592. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  59593. runDecimation(task.settings[loop.index], function () {
  59594. loop.executeNext();
  59595. });
  59596. }, function () {
  59597. //execution ended, run the success callback.
  59598. if (task.successCallback) {
  59599. task.successCallback();
  59600. }
  59601. _this.executeNext();
  59602. });
  59603. }
  59604. };
  59605. SimplificationQueue.prototype.getSimplifier = function (task) {
  59606. switch (task.simplificationType) {
  59607. case SimplificationType.QUADRATIC:
  59608. default:
  59609. return new QuadraticErrorSimplification(task.mesh);
  59610. }
  59611. };
  59612. return SimplificationQueue;
  59613. }());
  59614. BABYLON.SimplificationQueue = SimplificationQueue;
  59615. /**
  59616. * The implemented types of simplification.
  59617. * At the moment only Quadratic Error Decimation is implemented.
  59618. */
  59619. var SimplificationType;
  59620. (function (SimplificationType) {
  59621. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  59622. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  59623. var DecimationTriangle = (function () {
  59624. function DecimationTriangle(vertices) {
  59625. this.vertices = vertices;
  59626. this.error = new Array(4);
  59627. this.deleted = false;
  59628. this.isDirty = false;
  59629. this.deletePending = false;
  59630. this.borderFactor = 0;
  59631. }
  59632. return DecimationTriangle;
  59633. }());
  59634. BABYLON.DecimationTriangle = DecimationTriangle;
  59635. var DecimationVertex = (function () {
  59636. function DecimationVertex(position, id) {
  59637. this.position = position;
  59638. this.id = id;
  59639. this.isBorder = true;
  59640. this.q = new QuadraticMatrix();
  59641. this.triangleCount = 0;
  59642. this.triangleStart = 0;
  59643. this.originalOffsets = [];
  59644. }
  59645. DecimationVertex.prototype.updatePosition = function (newPosition) {
  59646. this.position.copyFrom(newPosition);
  59647. };
  59648. return DecimationVertex;
  59649. }());
  59650. BABYLON.DecimationVertex = DecimationVertex;
  59651. var QuadraticMatrix = (function () {
  59652. function QuadraticMatrix(data) {
  59653. this.data = new Array(10);
  59654. for (var i = 0; i < 10; ++i) {
  59655. if (data && data[i]) {
  59656. this.data[i] = data[i];
  59657. }
  59658. else {
  59659. this.data[i] = 0;
  59660. }
  59661. }
  59662. }
  59663. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  59664. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  59665. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  59666. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  59667. return det;
  59668. };
  59669. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  59670. for (var i = 0; i < 10; ++i) {
  59671. this.data[i] += matrix.data[i];
  59672. }
  59673. };
  59674. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  59675. for (var i = 0; i < 10; ++i) {
  59676. this.data[i] += data[i];
  59677. }
  59678. };
  59679. QuadraticMatrix.prototype.add = function (matrix) {
  59680. var m = new QuadraticMatrix();
  59681. for (var i = 0; i < 10; ++i) {
  59682. m.data[i] = this.data[i] + matrix.data[i];
  59683. }
  59684. return m;
  59685. };
  59686. QuadraticMatrix.FromData = function (a, b, c, d) {
  59687. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  59688. };
  59689. //returning an array to avoid garbage collection
  59690. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  59691. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  59692. };
  59693. return QuadraticMatrix;
  59694. }());
  59695. BABYLON.QuadraticMatrix = QuadraticMatrix;
  59696. var Reference = (function () {
  59697. function Reference(vertexId, triangleId) {
  59698. this.vertexId = vertexId;
  59699. this.triangleId = triangleId;
  59700. }
  59701. return Reference;
  59702. }());
  59703. BABYLON.Reference = Reference;
  59704. /**
  59705. * An implementation of the Quadratic Error simplification algorithm.
  59706. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  59707. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  59708. * @author RaananW
  59709. */
  59710. var QuadraticErrorSimplification = (function () {
  59711. function QuadraticErrorSimplification(_mesh) {
  59712. this._mesh = _mesh;
  59713. this.initialized = false;
  59714. this.syncIterations = 5000;
  59715. this.aggressiveness = 7;
  59716. this.decimationIterations = 100;
  59717. this.boundingBoxEpsilon = BABYLON.Epsilon;
  59718. }
  59719. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  59720. var _this = this;
  59721. this.initDecimatedMesh();
  59722. //iterating through the submeshes array, one after the other.
  59723. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  59724. _this.initWithMesh(loop.index, function () {
  59725. _this.runDecimation(settings, loop.index, function () {
  59726. loop.executeNext();
  59727. });
  59728. }, settings.optimizeMesh);
  59729. }, function () {
  59730. setTimeout(function () {
  59731. successCallback(_this._reconstructedMesh);
  59732. }, 0);
  59733. });
  59734. };
  59735. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  59736. var _this = this;
  59737. var gCount = 0;
  59738. triangle.vertices.forEach(function (vertex) {
  59739. var count = 0;
  59740. var vPos = vertex.position;
  59741. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  59742. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  59743. ++count;
  59744. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  59745. ++count;
  59746. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  59747. ++count;
  59748. if (count > 1) {
  59749. ++gCount;
  59750. }
  59751. ;
  59752. });
  59753. if (gCount > 1) {
  59754. console.log(triangle, gCount);
  59755. }
  59756. return gCount > 1;
  59757. };
  59758. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  59759. var _this = this;
  59760. var targetCount = ~~(this.triangles.length * settings.quality);
  59761. var deletedTriangles = 0;
  59762. var triangleCount = this.triangles.length;
  59763. var iterationFunction = function (iteration, callback) {
  59764. setTimeout(function () {
  59765. if (iteration % 5 === 0) {
  59766. _this.updateMesh(iteration === 0);
  59767. }
  59768. for (var i = 0; i < _this.triangles.length; ++i) {
  59769. _this.triangles[i].isDirty = false;
  59770. }
  59771. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  59772. var trianglesIterator = function (i) {
  59773. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  59774. var t = _this.triangles[tIdx];
  59775. if (!t)
  59776. return;
  59777. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  59778. return;
  59779. }
  59780. for (var j = 0; j < 3; ++j) {
  59781. if (t.error[j] < threshold) {
  59782. var deleted0 = [];
  59783. var deleted1 = [];
  59784. var v0 = t.vertices[j];
  59785. var v1 = t.vertices[(j + 1) % 3];
  59786. if (v0.isBorder || v1.isBorder)
  59787. continue;
  59788. var p = BABYLON.Vector3.Zero();
  59789. var n = BABYLON.Vector3.Zero();
  59790. var uv = BABYLON.Vector2.Zero();
  59791. var color = new BABYLON.Color4(0, 0, 0, 1);
  59792. _this.calculateError(v0, v1, p, n, uv, color);
  59793. var delTr = [];
  59794. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  59795. continue;
  59796. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  59797. continue;
  59798. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  59799. continue;
  59800. var uniqueArray = [];
  59801. delTr.forEach(function (deletedT) {
  59802. if (uniqueArray.indexOf(deletedT) === -1) {
  59803. deletedT.deletePending = true;
  59804. uniqueArray.push(deletedT);
  59805. }
  59806. });
  59807. if (uniqueArray.length % 2 !== 0) {
  59808. continue;
  59809. }
  59810. v0.q = v1.q.add(v0.q);
  59811. v0.updatePosition(p);
  59812. var tStart = _this.references.length;
  59813. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  59814. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  59815. var tCount = _this.references.length - tStart;
  59816. if (tCount <= v0.triangleCount) {
  59817. if (tCount) {
  59818. for (var c = 0; c < tCount; c++) {
  59819. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  59820. }
  59821. }
  59822. }
  59823. else {
  59824. v0.triangleStart = tStart;
  59825. }
  59826. v0.triangleCount = tCount;
  59827. break;
  59828. }
  59829. }
  59830. };
  59831. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  59832. }, 0);
  59833. };
  59834. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  59835. if (triangleCount - deletedTriangles <= targetCount)
  59836. loop.breakLoop();
  59837. else {
  59838. iterationFunction(loop.index, function () {
  59839. loop.executeNext();
  59840. });
  59841. }
  59842. }, function () {
  59843. setTimeout(function () {
  59844. //reconstruct this part of the mesh
  59845. _this.reconstructMesh(submeshIndex);
  59846. successCallback();
  59847. }, 0);
  59848. });
  59849. };
  59850. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  59851. var _this = this;
  59852. this.vertices = [];
  59853. this.triangles = [];
  59854. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59855. var indices = this._mesh.getIndices();
  59856. var submesh = this._mesh.subMeshes[submeshIndex];
  59857. var findInVertices = function (positionToSearch) {
  59858. if (optimizeMesh) {
  59859. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  59860. if (_this.vertices[ii].position.equals(positionToSearch)) {
  59861. return _this.vertices[ii];
  59862. }
  59863. }
  59864. }
  59865. return null;
  59866. };
  59867. var vertexReferences = [];
  59868. var vertexInit = function (i) {
  59869. var offset = i + submesh.verticesStart;
  59870. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  59871. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  59872. vertex.originalOffsets.push(offset);
  59873. if (vertex.id === _this.vertices.length) {
  59874. _this.vertices.push(vertex);
  59875. }
  59876. vertexReferences.push(vertex.id);
  59877. };
  59878. //var totalVertices = mesh.getTotalVertices();
  59879. var totalVertices = submesh.verticesCount;
  59880. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  59881. var indicesInit = function (i) {
  59882. var offset = (submesh.indexStart / 3) + i;
  59883. var pos = (offset * 3);
  59884. var i0 = indices[pos + 0];
  59885. var i1 = indices[pos + 1];
  59886. var i2 = indices[pos + 2];
  59887. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  59888. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  59889. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  59890. var triangle = new DecimationTriangle([v0, v1, v2]);
  59891. triangle.originalOffset = pos;
  59892. _this.triangles.push(triangle);
  59893. };
  59894. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  59895. _this.init(callback);
  59896. });
  59897. });
  59898. };
  59899. QuadraticErrorSimplification.prototype.init = function (callback) {
  59900. var _this = this;
  59901. var triangleInit1 = function (i) {
  59902. var t = _this.triangles[i];
  59903. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  59904. for (var j = 0; j < 3; j++) {
  59905. 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))));
  59906. }
  59907. };
  59908. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  59909. var triangleInit2 = function (i) {
  59910. var t = _this.triangles[i];
  59911. for (var j = 0; j < 3; ++j) {
  59912. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  59913. }
  59914. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  59915. };
  59916. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  59917. _this.initialized = true;
  59918. callback();
  59919. });
  59920. });
  59921. };
  59922. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  59923. var newTriangles = [];
  59924. var i;
  59925. for (i = 0; i < this.vertices.length; ++i) {
  59926. this.vertices[i].triangleCount = 0;
  59927. }
  59928. var t;
  59929. var j;
  59930. for (i = 0; i < this.triangles.length; ++i) {
  59931. if (!this.triangles[i].deleted) {
  59932. t = this.triangles[i];
  59933. for (j = 0; j < 3; ++j) {
  59934. t.vertices[j].triangleCount = 1;
  59935. }
  59936. newTriangles.push(t);
  59937. }
  59938. }
  59939. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  59940. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  59941. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  59942. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  59943. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  59944. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  59945. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59946. var vertexCount = 0;
  59947. for (i = 0; i < this.vertices.length; ++i) {
  59948. var vertex = this.vertices[i];
  59949. vertex.id = vertexCount;
  59950. if (vertex.triangleCount) {
  59951. vertex.originalOffsets.forEach(function (originalOffset) {
  59952. newPositionData.push(vertex.position.x);
  59953. newPositionData.push(vertex.position.y);
  59954. newPositionData.push(vertex.position.z);
  59955. newNormalData.push(normalData[originalOffset * 3]);
  59956. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  59957. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  59958. if (uvs && uvs.length) {
  59959. newUVsData.push(uvs[(originalOffset * 2)]);
  59960. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  59961. }
  59962. else if (colorsData && colorsData.length) {
  59963. newColorsData.push(colorsData[(originalOffset * 4)]);
  59964. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  59965. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  59966. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  59967. }
  59968. ++vertexCount;
  59969. });
  59970. }
  59971. }
  59972. var startingIndex = this._reconstructedMesh.getTotalIndices();
  59973. var startingVertex = this._reconstructedMesh.getTotalVertices();
  59974. var submeshesArray = this._reconstructedMesh.subMeshes;
  59975. this._reconstructedMesh.subMeshes = [];
  59976. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  59977. var originalIndices = this._mesh.getIndices();
  59978. for (i = 0; i < newTriangles.length; ++i) {
  59979. t = newTriangles[i]; //now get the new referencing point for each vertex
  59980. [0, 1, 2].forEach(function (idx) {
  59981. var id = originalIndices[t.originalOffset + idx];
  59982. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  59983. if (offset < 0)
  59984. offset = 0;
  59985. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  59986. });
  59987. }
  59988. //overwriting the old vertex buffers and indices.
  59989. this._reconstructedMesh.setIndices(newIndicesArray);
  59990. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  59991. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  59992. if (newUVsData.length > 0)
  59993. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  59994. if (newColorsData.length > 0)
  59995. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  59996. //create submesh
  59997. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  59998. if (submeshIndex > 0) {
  59999. this._reconstructedMesh.subMeshes = [];
  60000. submeshesArray.forEach(function (submesh) {
  60001. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  60002. });
  60003. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  60004. }
  60005. };
  60006. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  60007. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  60008. this._reconstructedMesh.material = this._mesh.material;
  60009. this._reconstructedMesh.parent = this._mesh.parent;
  60010. this._reconstructedMesh.isVisible = false;
  60011. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  60012. };
  60013. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  60014. for (var i = 0; i < vertex1.triangleCount; ++i) {
  60015. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  60016. if (t.deleted)
  60017. continue;
  60018. var s = this.references[vertex1.triangleStart + i].vertexId;
  60019. var v1 = t.vertices[(s + 1) % 3];
  60020. var v2 = t.vertices[(s + 2) % 3];
  60021. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  60022. deletedArray[i] = true;
  60023. delTr.push(t);
  60024. continue;
  60025. }
  60026. var d1 = v1.position.subtract(point);
  60027. d1 = d1.normalize();
  60028. var d2 = v2.position.subtract(point);
  60029. d2 = d2.normalize();
  60030. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  60031. return true;
  60032. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  60033. deletedArray[i] = false;
  60034. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  60035. return true;
  60036. }
  60037. return false;
  60038. };
  60039. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  60040. var newDeleted = deletedTriangles;
  60041. for (var i = 0; i < vertex.triangleCount; ++i) {
  60042. var ref = this.references[vertex.triangleStart + i];
  60043. var t = this.triangles[ref.triangleId];
  60044. if (t.deleted)
  60045. continue;
  60046. if (deletedArray[i] && t.deletePending) {
  60047. t.deleted = true;
  60048. newDeleted++;
  60049. continue;
  60050. }
  60051. t.vertices[ref.vertexId] = origVertex;
  60052. t.isDirty = true;
  60053. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  60054. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  60055. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  60056. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  60057. this.references.push(ref);
  60058. }
  60059. return newDeleted;
  60060. };
  60061. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  60062. for (var i = 0; i < this.vertices.length; ++i) {
  60063. var vCount = [];
  60064. var vId = [];
  60065. var v = this.vertices[i];
  60066. var j;
  60067. for (j = 0; j < v.triangleCount; ++j) {
  60068. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  60069. for (var ii = 0; ii < 3; ii++) {
  60070. var ofs = 0;
  60071. var vv = triangle.vertices[ii];
  60072. while (ofs < vCount.length) {
  60073. if (vId[ofs] === vv.id)
  60074. break;
  60075. ++ofs;
  60076. }
  60077. if (ofs === vCount.length) {
  60078. vCount.push(1);
  60079. vId.push(vv.id);
  60080. }
  60081. else {
  60082. vCount[ofs]++;
  60083. }
  60084. }
  60085. }
  60086. for (j = 0; j < vCount.length; ++j) {
  60087. if (vCount[j] === 1) {
  60088. this.vertices[vId[j]].isBorder = true;
  60089. }
  60090. else {
  60091. this.vertices[vId[j]].isBorder = false;
  60092. }
  60093. }
  60094. }
  60095. };
  60096. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  60097. if (identifyBorders === void 0) { identifyBorders = false; }
  60098. var i;
  60099. if (!identifyBorders) {
  60100. var newTrianglesVector = [];
  60101. for (i = 0; i < this.triangles.length; ++i) {
  60102. if (!this.triangles[i].deleted) {
  60103. newTrianglesVector.push(this.triangles[i]);
  60104. }
  60105. }
  60106. this.triangles = newTrianglesVector;
  60107. }
  60108. for (i = 0; i < this.vertices.length; ++i) {
  60109. this.vertices[i].triangleCount = 0;
  60110. this.vertices[i].triangleStart = 0;
  60111. }
  60112. var t;
  60113. var j;
  60114. var v;
  60115. for (i = 0; i < this.triangles.length; ++i) {
  60116. t = this.triangles[i];
  60117. for (j = 0; j < 3; ++j) {
  60118. v = t.vertices[j];
  60119. v.triangleCount++;
  60120. }
  60121. }
  60122. var tStart = 0;
  60123. for (i = 0; i < this.vertices.length; ++i) {
  60124. this.vertices[i].triangleStart = tStart;
  60125. tStart += this.vertices[i].triangleCount;
  60126. this.vertices[i].triangleCount = 0;
  60127. }
  60128. var newReferences = new Array(this.triangles.length * 3);
  60129. for (i = 0; i < this.triangles.length; ++i) {
  60130. t = this.triangles[i];
  60131. for (j = 0; j < 3; ++j) {
  60132. v = t.vertices[j];
  60133. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  60134. v.triangleCount++;
  60135. }
  60136. }
  60137. this.references = newReferences;
  60138. if (identifyBorders) {
  60139. this.identifyBorder();
  60140. }
  60141. };
  60142. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  60143. var x = point.x;
  60144. var y = point.y;
  60145. var z = point.z;
  60146. 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
  60147. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  60148. };
  60149. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  60150. var q = vertex1.q.add(vertex2.q);
  60151. var border = vertex1.isBorder && vertex2.isBorder;
  60152. var error = 0;
  60153. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  60154. if (qDet !== 0 && !border) {
  60155. if (!pointResult) {
  60156. pointResult = BABYLON.Vector3.Zero();
  60157. }
  60158. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  60159. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  60160. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  60161. error = this.vertexError(q, pointResult);
  60162. }
  60163. else {
  60164. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  60165. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  60166. var error1 = this.vertexError(q, vertex1.position);
  60167. var error2 = this.vertexError(q, vertex2.position);
  60168. var error3 = this.vertexError(q, p3);
  60169. error = Math.min(error1, error2, error3);
  60170. if (error === error1) {
  60171. if (pointResult) {
  60172. pointResult.copyFrom(vertex1.position);
  60173. }
  60174. }
  60175. else if (error === error2) {
  60176. if (pointResult) {
  60177. pointResult.copyFrom(vertex2.position);
  60178. }
  60179. }
  60180. else {
  60181. if (pointResult) {
  60182. pointResult.copyFrom(p3);
  60183. }
  60184. }
  60185. }
  60186. return error;
  60187. };
  60188. return QuadraticErrorSimplification;
  60189. }());
  60190. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  60191. })(BABYLON || (BABYLON = {}));
  60192. //# sourceMappingURL=babylon.meshSimplification.js.map
  60193. var BABYLON;
  60194. (function (BABYLON) {
  60195. var Internals;
  60196. (function (Internals) {
  60197. var MeshLODLevel = (function () {
  60198. function MeshLODLevel(distance, mesh) {
  60199. this.distance = distance;
  60200. this.mesh = mesh;
  60201. }
  60202. return MeshLODLevel;
  60203. }());
  60204. Internals.MeshLODLevel = MeshLODLevel;
  60205. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  60206. })(BABYLON || (BABYLON = {}));
  60207. //# sourceMappingURL=babylon.meshLODLevel.js.map
  60208. var BABYLON;
  60209. (function (BABYLON) {
  60210. // Standard optimizations
  60211. var SceneOptimization = (function () {
  60212. function SceneOptimization(priority) {
  60213. if (priority === void 0) { priority = 0; }
  60214. this.priority = priority;
  60215. this.apply = function (scene) {
  60216. return true; // Return true if everything that can be done was applied
  60217. };
  60218. }
  60219. return SceneOptimization;
  60220. }());
  60221. BABYLON.SceneOptimization = SceneOptimization;
  60222. var TextureOptimization = (function (_super) {
  60223. __extends(TextureOptimization, _super);
  60224. function TextureOptimization(priority, maximumSize) {
  60225. if (priority === void 0) { priority = 0; }
  60226. if (maximumSize === void 0) { maximumSize = 1024; }
  60227. var _this = _super.call(this, priority) || this;
  60228. _this.priority = priority;
  60229. _this.maximumSize = maximumSize;
  60230. _this.apply = function (scene) {
  60231. var allDone = true;
  60232. for (var index = 0; index < scene.textures.length; index++) {
  60233. var texture = scene.textures[index];
  60234. if (!texture.canRescale) {
  60235. continue;
  60236. }
  60237. var currentSize = texture.getSize();
  60238. var maxDimension = Math.max(currentSize.width, currentSize.height);
  60239. if (maxDimension > _this.maximumSize) {
  60240. texture.scale(0.5);
  60241. allDone = false;
  60242. }
  60243. }
  60244. return allDone;
  60245. };
  60246. return _this;
  60247. }
  60248. return TextureOptimization;
  60249. }(SceneOptimization));
  60250. BABYLON.TextureOptimization = TextureOptimization;
  60251. var HardwareScalingOptimization = (function (_super) {
  60252. __extends(HardwareScalingOptimization, _super);
  60253. function HardwareScalingOptimization(priority, maximumScale) {
  60254. if (priority === void 0) { priority = 0; }
  60255. if (maximumScale === void 0) { maximumScale = 2; }
  60256. var _this = _super.call(this, priority) || this;
  60257. _this.priority = priority;
  60258. _this.maximumScale = maximumScale;
  60259. _this._currentScale = 1;
  60260. _this.apply = function (scene) {
  60261. _this._currentScale++;
  60262. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  60263. return _this._currentScale >= _this.maximumScale;
  60264. };
  60265. return _this;
  60266. }
  60267. return HardwareScalingOptimization;
  60268. }(SceneOptimization));
  60269. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  60270. var ShadowsOptimization = (function (_super) {
  60271. __extends(ShadowsOptimization, _super);
  60272. function ShadowsOptimization() {
  60273. var _this = _super !== null && _super.apply(this, arguments) || this;
  60274. _this.apply = function (scene) {
  60275. scene.shadowsEnabled = false;
  60276. return true;
  60277. };
  60278. return _this;
  60279. }
  60280. return ShadowsOptimization;
  60281. }(SceneOptimization));
  60282. BABYLON.ShadowsOptimization = ShadowsOptimization;
  60283. var PostProcessesOptimization = (function (_super) {
  60284. __extends(PostProcessesOptimization, _super);
  60285. function PostProcessesOptimization() {
  60286. var _this = _super !== null && _super.apply(this, arguments) || this;
  60287. _this.apply = function (scene) {
  60288. scene.postProcessesEnabled = false;
  60289. return true;
  60290. };
  60291. return _this;
  60292. }
  60293. return PostProcessesOptimization;
  60294. }(SceneOptimization));
  60295. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  60296. var LensFlaresOptimization = (function (_super) {
  60297. __extends(LensFlaresOptimization, _super);
  60298. function LensFlaresOptimization() {
  60299. var _this = _super !== null && _super.apply(this, arguments) || this;
  60300. _this.apply = function (scene) {
  60301. scene.lensFlaresEnabled = false;
  60302. return true;
  60303. };
  60304. return _this;
  60305. }
  60306. return LensFlaresOptimization;
  60307. }(SceneOptimization));
  60308. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  60309. var ParticlesOptimization = (function (_super) {
  60310. __extends(ParticlesOptimization, _super);
  60311. function ParticlesOptimization() {
  60312. var _this = _super !== null && _super.apply(this, arguments) || this;
  60313. _this.apply = function (scene) {
  60314. scene.particlesEnabled = false;
  60315. return true;
  60316. };
  60317. return _this;
  60318. }
  60319. return ParticlesOptimization;
  60320. }(SceneOptimization));
  60321. BABYLON.ParticlesOptimization = ParticlesOptimization;
  60322. var RenderTargetsOptimization = (function (_super) {
  60323. __extends(RenderTargetsOptimization, _super);
  60324. function RenderTargetsOptimization() {
  60325. var _this = _super !== null && _super.apply(this, arguments) || this;
  60326. _this.apply = function (scene) {
  60327. scene.renderTargetsEnabled = false;
  60328. return true;
  60329. };
  60330. return _this;
  60331. }
  60332. return RenderTargetsOptimization;
  60333. }(SceneOptimization));
  60334. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  60335. var MergeMeshesOptimization = (function (_super) {
  60336. __extends(MergeMeshesOptimization, _super);
  60337. function MergeMeshesOptimization() {
  60338. var _this = _super !== null && _super.apply(this, arguments) || this;
  60339. _this._canBeMerged = function (abstractMesh) {
  60340. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  60341. return false;
  60342. }
  60343. var mesh = abstractMesh;
  60344. if (!mesh.isVisible || !mesh.isEnabled()) {
  60345. return false;
  60346. }
  60347. if (mesh.instances.length > 0) {
  60348. return false;
  60349. }
  60350. if (mesh.skeleton || mesh.hasLODLevels) {
  60351. return false;
  60352. }
  60353. if (mesh.parent) {
  60354. return false;
  60355. }
  60356. return true;
  60357. };
  60358. _this.apply = function (scene, updateSelectionTree) {
  60359. var globalPool = scene.meshes.slice(0);
  60360. var globalLength = globalPool.length;
  60361. for (var index = 0; index < globalLength; index++) {
  60362. var currentPool = new Array();
  60363. var current = globalPool[index];
  60364. // Checks
  60365. if (!_this._canBeMerged(current)) {
  60366. continue;
  60367. }
  60368. currentPool.push(current);
  60369. // Find compatible meshes
  60370. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  60371. var otherMesh = globalPool[subIndex];
  60372. if (!_this._canBeMerged(otherMesh)) {
  60373. continue;
  60374. }
  60375. if (otherMesh.material !== current.material) {
  60376. continue;
  60377. }
  60378. if (otherMesh.checkCollisions !== current.checkCollisions) {
  60379. continue;
  60380. }
  60381. currentPool.push(otherMesh);
  60382. globalLength--;
  60383. globalPool.splice(subIndex, 1);
  60384. subIndex--;
  60385. }
  60386. if (currentPool.length < 2) {
  60387. continue;
  60388. }
  60389. // Merge meshes
  60390. BABYLON.Mesh.MergeMeshes(currentPool);
  60391. }
  60392. if (updateSelectionTree != undefined) {
  60393. if (updateSelectionTree) {
  60394. scene.createOrUpdateSelectionOctree();
  60395. }
  60396. }
  60397. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  60398. scene.createOrUpdateSelectionOctree();
  60399. }
  60400. return true;
  60401. };
  60402. return _this;
  60403. }
  60404. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  60405. get: function () {
  60406. return MergeMeshesOptimization._UpdateSelectionTree;
  60407. },
  60408. set: function (value) {
  60409. MergeMeshesOptimization._UpdateSelectionTree = value;
  60410. },
  60411. enumerable: true,
  60412. configurable: true
  60413. });
  60414. return MergeMeshesOptimization;
  60415. }(SceneOptimization));
  60416. MergeMeshesOptimization._UpdateSelectionTree = false;
  60417. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  60418. // Options
  60419. var SceneOptimizerOptions = (function () {
  60420. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  60421. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  60422. if (trackerDuration === void 0) { trackerDuration = 2000; }
  60423. this.targetFrameRate = targetFrameRate;
  60424. this.trackerDuration = trackerDuration;
  60425. this.optimizations = new Array();
  60426. }
  60427. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  60428. var result = new SceneOptimizerOptions(targetFrameRate);
  60429. var priority = 0;
  60430. result.optimizations.push(new MergeMeshesOptimization(priority));
  60431. result.optimizations.push(new ShadowsOptimization(priority));
  60432. result.optimizations.push(new LensFlaresOptimization(priority));
  60433. // Next priority
  60434. priority++;
  60435. result.optimizations.push(new PostProcessesOptimization(priority));
  60436. result.optimizations.push(new ParticlesOptimization(priority));
  60437. // Next priority
  60438. priority++;
  60439. result.optimizations.push(new TextureOptimization(priority, 1024));
  60440. return result;
  60441. };
  60442. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  60443. var result = new SceneOptimizerOptions(targetFrameRate);
  60444. var priority = 0;
  60445. result.optimizations.push(new MergeMeshesOptimization(priority));
  60446. result.optimizations.push(new ShadowsOptimization(priority));
  60447. result.optimizations.push(new LensFlaresOptimization(priority));
  60448. // Next priority
  60449. priority++;
  60450. result.optimizations.push(new PostProcessesOptimization(priority));
  60451. result.optimizations.push(new ParticlesOptimization(priority));
  60452. // Next priority
  60453. priority++;
  60454. result.optimizations.push(new TextureOptimization(priority, 512));
  60455. // Next priority
  60456. priority++;
  60457. result.optimizations.push(new RenderTargetsOptimization(priority));
  60458. // Next priority
  60459. priority++;
  60460. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  60461. return result;
  60462. };
  60463. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  60464. var result = new SceneOptimizerOptions(targetFrameRate);
  60465. var priority = 0;
  60466. result.optimizations.push(new MergeMeshesOptimization(priority));
  60467. result.optimizations.push(new ShadowsOptimization(priority));
  60468. result.optimizations.push(new LensFlaresOptimization(priority));
  60469. // Next priority
  60470. priority++;
  60471. result.optimizations.push(new PostProcessesOptimization(priority));
  60472. result.optimizations.push(new ParticlesOptimization(priority));
  60473. // Next priority
  60474. priority++;
  60475. result.optimizations.push(new TextureOptimization(priority, 256));
  60476. // Next priority
  60477. priority++;
  60478. result.optimizations.push(new RenderTargetsOptimization(priority));
  60479. // Next priority
  60480. priority++;
  60481. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  60482. return result;
  60483. };
  60484. return SceneOptimizerOptions;
  60485. }());
  60486. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  60487. // Scene optimizer tool
  60488. var SceneOptimizer = (function () {
  60489. function SceneOptimizer() {
  60490. }
  60491. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  60492. // TODO: add an epsilon
  60493. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  60494. if (onSuccess) {
  60495. onSuccess();
  60496. }
  60497. return;
  60498. }
  60499. // Apply current level of optimizations
  60500. var allDone = true;
  60501. var noOptimizationApplied = true;
  60502. for (var index = 0; index < options.optimizations.length; index++) {
  60503. var optimization = options.optimizations[index];
  60504. if (optimization.priority === currentPriorityLevel) {
  60505. noOptimizationApplied = false;
  60506. allDone = allDone && optimization.apply(scene);
  60507. }
  60508. }
  60509. // If no optimization was applied, this is a failure :(
  60510. if (noOptimizationApplied) {
  60511. if (onFailure) {
  60512. onFailure();
  60513. }
  60514. return;
  60515. }
  60516. // If all optimizations were done, move to next level
  60517. if (allDone) {
  60518. currentPriorityLevel++;
  60519. }
  60520. // Let's the system running for a specific amount of time before checking FPS
  60521. scene.executeWhenReady(function () {
  60522. setTimeout(function () {
  60523. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  60524. }, options.trackerDuration);
  60525. });
  60526. };
  60527. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  60528. if (!options) {
  60529. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  60530. }
  60531. // Let's the system running for a specific amount of time before checking FPS
  60532. scene.executeWhenReady(function () {
  60533. setTimeout(function () {
  60534. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  60535. }, options.trackerDuration);
  60536. });
  60537. };
  60538. return SceneOptimizer;
  60539. }());
  60540. BABYLON.SceneOptimizer = SceneOptimizer;
  60541. })(BABYLON || (BABYLON = {}));
  60542. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  60543. var BABYLON;
  60544. (function (BABYLON) {
  60545. var OutlineRenderer = (function () {
  60546. function OutlineRenderer(scene) {
  60547. this._scene = scene;
  60548. }
  60549. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  60550. var _this = this;
  60551. if (useOverlay === void 0) { useOverlay = false; }
  60552. var scene = this._scene;
  60553. var engine = this._scene.getEngine();
  60554. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  60555. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  60556. return;
  60557. }
  60558. var mesh = subMesh.getRenderingMesh();
  60559. var material = subMesh.getMaterial();
  60560. engine.enableEffect(this._effect);
  60561. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  60562. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  60563. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  60564. // Bones
  60565. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60566. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  60567. }
  60568. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  60569. // Alpha test
  60570. if (material && material.needAlphaTesting()) {
  60571. var alphaTexture = material.getAlphaTestTexture();
  60572. this._effect.setTexture("diffuseSampler", alphaTexture);
  60573. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  60574. }
  60575. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  60576. };
  60577. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  60578. var defines = [];
  60579. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  60580. var mesh = subMesh.getMesh();
  60581. var material = subMesh.getMaterial();
  60582. // Alpha test
  60583. if (material && material.needAlphaTesting()) {
  60584. defines.push("#define ALPHATEST");
  60585. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60586. attribs.push(BABYLON.VertexBuffer.UVKind);
  60587. defines.push("#define UV1");
  60588. }
  60589. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60590. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60591. defines.push("#define UV2");
  60592. }
  60593. }
  60594. // Bones
  60595. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60596. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60597. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60598. if (mesh.numBoneInfluencers > 4) {
  60599. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60600. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60601. }
  60602. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60603. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60604. }
  60605. else {
  60606. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60607. }
  60608. // Instances
  60609. if (useInstances) {
  60610. defines.push("#define INSTANCES");
  60611. attribs.push("world0");
  60612. attribs.push("world1");
  60613. attribs.push("world2");
  60614. attribs.push("world3");
  60615. }
  60616. // Get correct effect
  60617. var join = defines.join("\n");
  60618. if (this._cachedDefines !== join) {
  60619. this._cachedDefines = join;
  60620. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  60621. }
  60622. return this._effect.isReady();
  60623. };
  60624. return OutlineRenderer;
  60625. }());
  60626. BABYLON.OutlineRenderer = OutlineRenderer;
  60627. })(BABYLON || (BABYLON = {}));
  60628. //# sourceMappingURL=babylon.outlineRenderer.js.map
  60629. var BABYLON;
  60630. (function (BABYLON) {
  60631. var FaceAdjacencies = (function () {
  60632. function FaceAdjacencies() {
  60633. this.edges = new Array();
  60634. this.edgesConnectedCount = 0;
  60635. }
  60636. return FaceAdjacencies;
  60637. }());
  60638. var EdgesRenderer = (function () {
  60639. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  60640. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  60641. if (epsilon === void 0) { epsilon = 0.95; }
  60642. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  60643. this.edgesWidthScalerForOrthographic = 1000.0;
  60644. this.edgesWidthScalerForPerspective = 50.0;
  60645. this._linesPositions = new Array();
  60646. this._linesNormals = new Array();
  60647. this._linesIndices = new Array();
  60648. this._buffers = {};
  60649. this._checkVerticesInsteadOfIndices = false;
  60650. this._source = source;
  60651. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  60652. this._epsilon = epsilon;
  60653. this._prepareRessources();
  60654. this._generateEdgesLines();
  60655. }
  60656. EdgesRenderer.prototype._prepareRessources = function () {
  60657. if (this._lineShader) {
  60658. return;
  60659. }
  60660. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  60661. attributes: ["position", "normal"],
  60662. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  60663. });
  60664. this._lineShader.disableDepthWrite = true;
  60665. this._lineShader.backFaceCulling = false;
  60666. };
  60667. EdgesRenderer.prototype.dispose = function () {
  60668. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  60669. if (buffer) {
  60670. buffer.dispose();
  60671. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  60672. }
  60673. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  60674. if (buffer) {
  60675. buffer.dispose();
  60676. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  60677. }
  60678. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  60679. this._lineShader.dispose();
  60680. };
  60681. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  60682. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  60683. return 0;
  60684. }
  60685. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  60686. return 1;
  60687. }
  60688. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  60689. return 2;
  60690. }
  60691. return -1;
  60692. };
  60693. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  60694. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  60695. return 0;
  60696. }
  60697. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  60698. return 1;
  60699. }
  60700. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  60701. return 2;
  60702. }
  60703. return -1;
  60704. };
  60705. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  60706. var needToCreateLine;
  60707. if (edge === undefined) {
  60708. needToCreateLine = true;
  60709. }
  60710. else {
  60711. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  60712. needToCreateLine = dotProduct < this._epsilon;
  60713. }
  60714. if (needToCreateLine) {
  60715. var offset = this._linesPositions.length / 3;
  60716. var normal = p0.subtract(p1);
  60717. normal.normalize();
  60718. // Positions
  60719. this._linesPositions.push(p0.x);
  60720. this._linesPositions.push(p0.y);
  60721. this._linesPositions.push(p0.z);
  60722. this._linesPositions.push(p0.x);
  60723. this._linesPositions.push(p0.y);
  60724. this._linesPositions.push(p0.z);
  60725. this._linesPositions.push(p1.x);
  60726. this._linesPositions.push(p1.y);
  60727. this._linesPositions.push(p1.z);
  60728. this._linesPositions.push(p1.x);
  60729. this._linesPositions.push(p1.y);
  60730. this._linesPositions.push(p1.z);
  60731. // Normals
  60732. this._linesNormals.push(p1.x);
  60733. this._linesNormals.push(p1.y);
  60734. this._linesNormals.push(p1.z);
  60735. this._linesNormals.push(-1);
  60736. this._linesNormals.push(p1.x);
  60737. this._linesNormals.push(p1.y);
  60738. this._linesNormals.push(p1.z);
  60739. this._linesNormals.push(1);
  60740. this._linesNormals.push(p0.x);
  60741. this._linesNormals.push(p0.y);
  60742. this._linesNormals.push(p0.z);
  60743. this._linesNormals.push(-1);
  60744. this._linesNormals.push(p0.x);
  60745. this._linesNormals.push(p0.y);
  60746. this._linesNormals.push(p0.z);
  60747. this._linesNormals.push(1);
  60748. // Indices
  60749. this._linesIndices.push(offset);
  60750. this._linesIndices.push(offset + 1);
  60751. this._linesIndices.push(offset + 2);
  60752. this._linesIndices.push(offset);
  60753. this._linesIndices.push(offset + 2);
  60754. this._linesIndices.push(offset + 3);
  60755. }
  60756. };
  60757. EdgesRenderer.prototype._generateEdgesLines = function () {
  60758. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60759. var indices = this._source.getIndices();
  60760. // First let's find adjacencies
  60761. var adjacencies = new Array();
  60762. var faceNormals = new Array();
  60763. var index;
  60764. var faceAdjacencies;
  60765. // Prepare faces
  60766. for (index = 0; index < indices.length; index += 3) {
  60767. faceAdjacencies = new FaceAdjacencies();
  60768. var p0Index = indices[index];
  60769. var p1Index = indices[index + 1];
  60770. var p2Index = indices[index + 2];
  60771. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  60772. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  60773. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  60774. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  60775. faceNormal.normalize();
  60776. faceNormals.push(faceNormal);
  60777. adjacencies.push(faceAdjacencies);
  60778. }
  60779. // Scan
  60780. for (index = 0; index < adjacencies.length; index++) {
  60781. faceAdjacencies = adjacencies[index];
  60782. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  60783. var otherFaceAdjacencies = adjacencies[otherIndex];
  60784. if (faceAdjacencies.edgesConnectedCount === 3) {
  60785. break;
  60786. }
  60787. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  60788. continue;
  60789. }
  60790. var otherP0 = indices[otherIndex * 3];
  60791. var otherP1 = indices[otherIndex * 3 + 1];
  60792. var otherP2 = indices[otherIndex * 3 + 2];
  60793. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  60794. var otherEdgeIndex;
  60795. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  60796. continue;
  60797. }
  60798. switch (edgeIndex) {
  60799. case 0:
  60800. if (this._checkVerticesInsteadOfIndices) {
  60801. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  60802. }
  60803. else {
  60804. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  60805. }
  60806. break;
  60807. case 1:
  60808. if (this._checkVerticesInsteadOfIndices) {
  60809. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  60810. }
  60811. else {
  60812. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  60813. }
  60814. break;
  60815. case 2:
  60816. if (this._checkVerticesInsteadOfIndices) {
  60817. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  60818. }
  60819. else {
  60820. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  60821. }
  60822. break;
  60823. }
  60824. if (otherEdgeIndex === -1) {
  60825. continue;
  60826. }
  60827. faceAdjacencies.edges[edgeIndex] = otherIndex;
  60828. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  60829. faceAdjacencies.edgesConnectedCount++;
  60830. otherFaceAdjacencies.edgesConnectedCount++;
  60831. if (faceAdjacencies.edgesConnectedCount === 3) {
  60832. break;
  60833. }
  60834. }
  60835. }
  60836. }
  60837. // Create lines
  60838. for (index = 0; index < adjacencies.length; index++) {
  60839. // 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
  60840. var current = adjacencies[index];
  60841. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  60842. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  60843. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  60844. }
  60845. // Merge into a single mesh
  60846. var engine = this._source.getScene().getEngine();
  60847. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  60848. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  60849. this._ib = engine.createIndexBuffer(this._linesIndices);
  60850. this._indicesCount = this._linesIndices.length;
  60851. };
  60852. EdgesRenderer.prototype.render = function () {
  60853. if (!this._lineShader.isReady()) {
  60854. return;
  60855. }
  60856. var scene = this._source.getScene();
  60857. var engine = scene.getEngine();
  60858. this._lineShader._preBind();
  60859. // VBOs
  60860. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  60861. scene.resetCachedMaterial();
  60862. this._lineShader.setColor4("color", this._source.edgesColor);
  60863. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  60864. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  60865. }
  60866. else {
  60867. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  60868. }
  60869. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  60870. this._lineShader.bind(this._source.getWorldMatrix());
  60871. // Draw order
  60872. engine.draw(true, 0, this._indicesCount);
  60873. this._lineShader.unbind();
  60874. engine.setDepthWrite(true);
  60875. };
  60876. return EdgesRenderer;
  60877. }());
  60878. BABYLON.EdgesRenderer = EdgesRenderer;
  60879. })(BABYLON || (BABYLON = {}));
  60880. //# sourceMappingURL=babylon.edgesRenderer.js.map
  60881. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  60882. /// <reference path="..\Math\babylon.math.ts" />
  60883. var BABYLON;
  60884. (function (BABYLON) {
  60885. /**
  60886. * Special Glow Blur post process only blurring the alpha channel
  60887. * It enforces keeping the most luminous color in the color channel.
  60888. */
  60889. var GlowBlurPostProcess = (function (_super) {
  60890. __extends(GlowBlurPostProcess, _super);
  60891. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  60892. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60893. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  60894. _this.direction = direction;
  60895. _this.blurWidth = blurWidth;
  60896. _this.onApplyObservable.add(function (effect) {
  60897. effect.setFloat2("screenSize", _this.width, _this.height);
  60898. effect.setVector2("direction", _this.direction);
  60899. effect.setFloat("blurWidth", _this.blurWidth);
  60900. });
  60901. return _this;
  60902. }
  60903. return GlowBlurPostProcess;
  60904. }(BABYLON.PostProcess));
  60905. /**
  60906. * The highlight layer Helps adding a glow effect around a mesh.
  60907. *
  60908. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  60909. * glowy meshes to your scene.
  60910. *
  60911. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  60912. */
  60913. var HighlightLayer = (function () {
  60914. /**
  60915. * Instantiates a new highlight Layer and references it to the scene..
  60916. * @param name The name of the layer
  60917. * @param scene The scene to use the layer in
  60918. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  60919. */
  60920. function HighlightLayer(name, scene, options) {
  60921. this.name = name;
  60922. this._vertexBuffers = {};
  60923. this._mainTextureDesiredSize = { width: 0, height: 0 };
  60924. this._meshes = {};
  60925. this._maxSize = 0;
  60926. this._shouldRender = false;
  60927. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  60928. this._excludedMeshes = {};
  60929. /**
  60930. * Specifies whether or not the inner glow is ACTIVE in the layer.
  60931. */
  60932. this.innerGlow = true;
  60933. /**
  60934. * Specifies whether or not the outer glow is ACTIVE in the layer.
  60935. */
  60936. this.outerGlow = true;
  60937. /**
  60938. * Specifies wether the highlight layer is enabled or not.
  60939. */
  60940. this.isEnabled = true;
  60941. /**
  60942. * An event triggered when the highlight layer has been disposed.
  60943. * @type {BABYLON.Observable}
  60944. */
  60945. this.onDisposeObservable = new BABYLON.Observable();
  60946. /**
  60947. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  60948. * @type {BABYLON.Observable}
  60949. */
  60950. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  60951. /**
  60952. * An event triggered when the highlight layer is being blurred.
  60953. * @type {BABYLON.Observable}
  60954. */
  60955. this.onBeforeBlurObservable = new BABYLON.Observable();
  60956. /**
  60957. * An event triggered when the highlight layer has been blurred.
  60958. * @type {BABYLON.Observable}
  60959. */
  60960. this.onAfterBlurObservable = new BABYLON.Observable();
  60961. /**
  60962. * An event triggered when the glowing blurred texture is being merged in the scene.
  60963. * @type {BABYLON.Observable}
  60964. */
  60965. this.onBeforeComposeObservable = new BABYLON.Observable();
  60966. /**
  60967. * An event triggered when the glowing blurred texture has been merged in the scene.
  60968. * @type {BABYLON.Observable}
  60969. */
  60970. this.onAfterComposeObservable = new BABYLON.Observable();
  60971. /**
  60972. * An event triggered when the highlight layer changes its size.
  60973. * @type {BABYLON.Observable}
  60974. */
  60975. this.onSizeChangedObservable = new BABYLON.Observable();
  60976. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60977. var engine = scene.getEngine();
  60978. this._engine = engine;
  60979. this._maxSize = this._engine.getCaps().maxTextureSize;
  60980. this._scene.highlightLayers.push(this);
  60981. // Warn on stencil.
  60982. if (!this._engine.isStencilEnable) {
  60983. BABYLON.Tools.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new BABYLON.Engine(canvas, antialias, { stencil: true }");
  60984. }
  60985. // Adapt options
  60986. this._options = options || {
  60987. mainTextureRatio: 0.25,
  60988. blurTextureSizeRatio: 0.5,
  60989. blurHorizontalSize: 1,
  60990. blurVerticalSize: 1,
  60991. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  60992. };
  60993. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  60994. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  60995. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  60996. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  60997. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  60998. // VBO
  60999. var vertices = [];
  61000. vertices.push(1, 1);
  61001. vertices.push(-1, 1);
  61002. vertices.push(-1, -1);
  61003. vertices.push(1, -1);
  61004. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  61005. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  61006. // Indices
  61007. var indices = [];
  61008. indices.push(0);
  61009. indices.push(1);
  61010. indices.push(2);
  61011. indices.push(0);
  61012. indices.push(2);
  61013. indices.push(3);
  61014. this._indexBuffer = engine.createIndexBuffer(indices);
  61015. // Effect
  61016. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  61017. // Render target
  61018. this.setMainTextureSize();
  61019. // Create Textures and post processes
  61020. this.createTextureAndPostProcesses();
  61021. }
  61022. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  61023. /**
  61024. * Gets the horizontal size of the blur.
  61025. */
  61026. get: function () {
  61027. return this._horizontalBlurPostprocess.blurWidth;
  61028. },
  61029. /**
  61030. * Specifies the horizontal size of the blur.
  61031. */
  61032. set: function (value) {
  61033. this._horizontalBlurPostprocess.blurWidth = value;
  61034. },
  61035. enumerable: true,
  61036. configurable: true
  61037. });
  61038. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  61039. /**
  61040. * Gets the vertical size of the blur.
  61041. */
  61042. get: function () {
  61043. return this._verticalBlurPostprocess.blurWidth;
  61044. },
  61045. /**
  61046. * Specifies the vertical size of the blur.
  61047. */
  61048. set: function (value) {
  61049. this._verticalBlurPostprocess.blurWidth = value;
  61050. },
  61051. enumerable: true,
  61052. configurable: true
  61053. });
  61054. Object.defineProperty(HighlightLayer.prototype, "camera", {
  61055. /**
  61056. * Gets the camera attached to the layer.
  61057. */
  61058. get: function () {
  61059. return this._options.camera;
  61060. },
  61061. enumerable: true,
  61062. configurable: true
  61063. });
  61064. /**
  61065. * Creates the render target textures and post processes used in the highlight layer.
  61066. */
  61067. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  61068. var _this = this;
  61069. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  61070. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  61071. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  61072. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  61073. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  61074. width: this._mainTextureDesiredSize.width,
  61075. height: this._mainTextureDesiredSize.height
  61076. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61077. this._mainTexture.activeCamera = this._options.camera;
  61078. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61079. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61080. this._mainTexture.anisotropicFilteringLevel = 1;
  61081. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61082. this._mainTexture.renderParticles = false;
  61083. this._mainTexture.renderList = null;
  61084. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  61085. width: blurTextureWidth,
  61086. height: blurTextureHeight
  61087. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61088. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61089. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61090. this._blurTexture.anisotropicFilteringLevel = 16;
  61091. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  61092. this._blurTexture.renderParticles = false;
  61093. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  61094. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  61095. effect.setTexture("textureSampler", _this._mainTexture);
  61096. });
  61097. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  61098. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  61099. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  61100. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  61101. });
  61102. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  61103. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  61104. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  61105. });
  61106. }
  61107. else {
  61108. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  61109. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  61110. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  61111. });
  61112. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  61113. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  61114. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  61115. });
  61116. }
  61117. this._mainTexture.onAfterUnbindObservable.add(function () {
  61118. _this.onBeforeBlurObservable.notifyObservers(_this);
  61119. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  61120. _this.onAfterBlurObservable.notifyObservers(_this);
  61121. });
  61122. // Custom render function
  61123. var renderSubMesh = function (subMesh) {
  61124. var mesh = subMesh.getRenderingMesh();
  61125. var scene = _this._scene;
  61126. var engine = scene.getEngine();
  61127. // Culling
  61128. engine.setState(subMesh.getMaterial().backFaceCulling);
  61129. // Managing instances
  61130. var batch = mesh._getInstancesRenderList(subMesh._id);
  61131. if (batch.mustReturn) {
  61132. return;
  61133. }
  61134. // Excluded Mesh
  61135. if (_this._excludedMeshes[mesh.uniqueId]) {
  61136. return;
  61137. }
  61138. ;
  61139. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  61140. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  61141. var material = subMesh.getMaterial();
  61142. var emissiveTexture = null;
  61143. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  61144. emissiveTexture = material.emissiveTexture;
  61145. }
  61146. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  61147. engine.enableEffect(_this._glowMapGenerationEffect);
  61148. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  61149. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  61150. if (highlightLayerMesh) {
  61151. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  61152. }
  61153. else {
  61154. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  61155. }
  61156. // Alpha test
  61157. if (material && material.needAlphaTesting()) {
  61158. var alphaTexture = material.getAlphaTestTexture();
  61159. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  61160. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  61161. }
  61162. // Glow emissive only
  61163. if (emissiveTexture) {
  61164. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  61165. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  61166. }
  61167. // Bones
  61168. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61169. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  61170. }
  61171. // Draw
  61172. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  61173. }
  61174. else {
  61175. // Need to reset refresh rate of the shadowMap
  61176. _this._mainTexture.resetRefreshCounter();
  61177. }
  61178. };
  61179. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  61180. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  61181. var index;
  61182. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61183. renderSubMesh(opaqueSubMeshes.data[index]);
  61184. }
  61185. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61186. renderSubMesh(alphaTestSubMeshes.data[index]);
  61187. }
  61188. for (index = 0; index < transparentSubMeshes.length; index++) {
  61189. renderSubMesh(transparentSubMeshes.data[index]);
  61190. }
  61191. };
  61192. this._mainTexture.onClearObservable.add(function (engine) {
  61193. engine.clear(HighlightLayer.neutralColor, true, true, true);
  61194. });
  61195. };
  61196. /**
  61197. * Checks for the readiness of the element composing the layer.
  61198. * @param subMesh the mesh to check for
  61199. * @param useInstances specify wether or not to use instances to render the mesh
  61200. * @param emissiveTexture the associated emissive texture used to generate the glow
  61201. * @return true if ready otherwise, false
  61202. */
  61203. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  61204. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  61205. return false;
  61206. }
  61207. var defines = [];
  61208. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61209. var mesh = subMesh.getMesh();
  61210. var material = subMesh.getMaterial();
  61211. var uv1 = false;
  61212. var uv2 = false;
  61213. // Alpha test
  61214. if (material && material.needAlphaTesting()) {
  61215. var alphaTexture = material.getAlphaTestTexture();
  61216. if (alphaTexture) {
  61217. defines.push("#define ALPHATEST");
  61218. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  61219. alphaTexture.coordinatesIndex === 1) {
  61220. defines.push("#define DIFFUSEUV2");
  61221. uv2 = true;
  61222. }
  61223. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61224. defines.push("#define DIFFUSEUV1");
  61225. uv1 = true;
  61226. }
  61227. }
  61228. }
  61229. // Emissive
  61230. if (emissiveTexture) {
  61231. defines.push("#define EMISSIVE");
  61232. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  61233. emissiveTexture.coordinatesIndex === 1) {
  61234. defines.push("#define EMISSIVEUV2");
  61235. uv2 = true;
  61236. }
  61237. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61238. defines.push("#define EMISSIVEUV1");
  61239. uv1 = true;
  61240. }
  61241. }
  61242. if (uv1) {
  61243. attribs.push(BABYLON.VertexBuffer.UVKind);
  61244. defines.push("#define UV1");
  61245. }
  61246. if (uv2) {
  61247. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61248. defines.push("#define UV2");
  61249. }
  61250. // Bones
  61251. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61252. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61253. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61254. if (mesh.numBoneInfluencers > 4) {
  61255. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61256. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61257. }
  61258. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61259. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  61260. }
  61261. else {
  61262. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61263. }
  61264. // Instances
  61265. if (useInstances) {
  61266. defines.push("#define INSTANCES");
  61267. attribs.push("world0");
  61268. attribs.push("world1");
  61269. attribs.push("world2");
  61270. attribs.push("world3");
  61271. }
  61272. // Get correct effect
  61273. var join = defines.join("\n");
  61274. if (this._cachedDefines !== join) {
  61275. this._cachedDefines = join;
  61276. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  61277. }
  61278. return this._glowMapGenerationEffect.isReady();
  61279. };
  61280. /**
  61281. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  61282. */
  61283. HighlightLayer.prototype.render = function () {
  61284. var currentEffect = this._glowMapMergeEffect;
  61285. // Check
  61286. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  61287. return;
  61288. var engine = this._scene.getEngine();
  61289. this.onBeforeComposeObservable.notifyObservers(this);
  61290. // Render
  61291. engine.enableEffect(currentEffect);
  61292. engine.setState(false);
  61293. // Cache
  61294. var previousStencilBuffer = engine.getStencilBuffer();
  61295. var previousStencilFunction = engine.getStencilFunction();
  61296. var previousStencilMask = engine.getStencilMask();
  61297. var previousAlphaMode = engine.getAlphaMode();
  61298. // Texture
  61299. currentEffect.setTexture("textureSampler", this._blurTexture);
  61300. // VBOs
  61301. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  61302. // Draw order
  61303. engine.setAlphaMode(this._options.alphaBlendingMode);
  61304. engine.setStencilMask(0x00);
  61305. engine.setStencilBuffer(true);
  61306. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  61307. if (this.outerGlow) {
  61308. currentEffect.setFloat("offset", 0);
  61309. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  61310. engine.draw(true, 0, 6);
  61311. }
  61312. if (this.innerGlow) {
  61313. currentEffect.setFloat("offset", 1);
  61314. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  61315. engine.draw(true, 0, 6);
  61316. }
  61317. // Restore Cache
  61318. engine.setStencilFunction(previousStencilFunction);
  61319. engine.setStencilMask(previousStencilMask);
  61320. engine.setAlphaMode(previousAlphaMode);
  61321. engine.setStencilBuffer(previousStencilBuffer);
  61322. this.onAfterComposeObservable.notifyObservers(this);
  61323. // Handle size changes.
  61324. var size = this._mainTexture.getSize();
  61325. this.setMainTextureSize();
  61326. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  61327. // Recreate RTT and post processes on size change.
  61328. this.onSizeChangedObservable.notifyObservers(this);
  61329. this.disposeTextureAndPostProcesses();
  61330. this.createTextureAndPostProcesses();
  61331. }
  61332. };
  61333. /**
  61334. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  61335. * @param mesh The mesh to exclude from the highlight layer
  61336. */
  61337. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  61338. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  61339. if (!meshExcluded) {
  61340. this._excludedMeshes[mesh.uniqueId] = {
  61341. mesh: mesh,
  61342. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  61343. mesh.getEngine().setStencilBuffer(false);
  61344. }),
  61345. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  61346. mesh.getEngine().setStencilBuffer(true);
  61347. }),
  61348. };
  61349. }
  61350. };
  61351. /**
  61352. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  61353. * @param mesh The mesh to highlight
  61354. */
  61355. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  61356. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  61357. if (meshExcluded) {
  61358. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  61359. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  61360. }
  61361. this._excludedMeshes[mesh.uniqueId] = undefined;
  61362. };
  61363. /**
  61364. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  61365. * @param mesh The mesh to highlight
  61366. * @param color The color of the highlight
  61367. * @param glowEmissiveOnly Extract the glow from the emissive texture
  61368. */
  61369. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  61370. var _this = this;
  61371. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  61372. var meshHighlight = this._meshes[mesh.uniqueId];
  61373. if (meshHighlight) {
  61374. meshHighlight.color = color;
  61375. }
  61376. else {
  61377. this._meshes[mesh.uniqueId] = {
  61378. mesh: mesh,
  61379. color: color,
  61380. // Lambda required for capture due to Observable this context
  61381. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  61382. if (_this._excludedMeshes[mesh.uniqueId]) {
  61383. _this.defaultStencilReference(mesh);
  61384. }
  61385. else {
  61386. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  61387. }
  61388. }),
  61389. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  61390. glowEmissiveOnly: glowEmissiveOnly
  61391. };
  61392. }
  61393. this._shouldRender = true;
  61394. };
  61395. /**
  61396. * Remove a mesh from the highlight layer in order to make it stop glowing.
  61397. * @param mesh The mesh to highlight
  61398. */
  61399. HighlightLayer.prototype.removeMesh = function (mesh) {
  61400. var meshHighlight = this._meshes[mesh.uniqueId];
  61401. if (meshHighlight) {
  61402. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  61403. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  61404. }
  61405. this._meshes[mesh.uniqueId] = undefined;
  61406. this._shouldRender = false;
  61407. for (var meshHighlightToCheck in this._meshes) {
  61408. if (meshHighlightToCheck) {
  61409. this._shouldRender = true;
  61410. break;
  61411. }
  61412. }
  61413. };
  61414. /**
  61415. * Returns true if the layer contains information to display, otherwise false.
  61416. */
  61417. HighlightLayer.prototype.shouldRender = function () {
  61418. return this.isEnabled && this._shouldRender;
  61419. };
  61420. /**
  61421. * Sets the main texture desired size which is the closest power of two
  61422. * of the engine canvas size.
  61423. */
  61424. HighlightLayer.prototype.setMainTextureSize = function () {
  61425. if (this._options.mainTextureFixedSize) {
  61426. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  61427. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  61428. }
  61429. else {
  61430. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  61431. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  61432. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  61433. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  61434. }
  61435. };
  61436. /**
  61437. * Force the stencil to the normal expected value for none glowing parts
  61438. */
  61439. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  61440. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  61441. };
  61442. /**
  61443. * Dispose only the render target textures and post process.
  61444. */
  61445. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  61446. this._blurTexture.dispose();
  61447. this._mainTexture.dispose();
  61448. this._downSamplePostprocess.dispose();
  61449. this._horizontalBlurPostprocess.dispose();
  61450. this._verticalBlurPostprocess.dispose();
  61451. };
  61452. /**
  61453. * Dispose the highlight layer and free resources.
  61454. */
  61455. HighlightLayer.prototype.dispose = function () {
  61456. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61457. if (vertexBuffer) {
  61458. vertexBuffer.dispose();
  61459. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  61460. }
  61461. if (this._indexBuffer) {
  61462. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  61463. this._indexBuffer = null;
  61464. }
  61465. // Clean textures and post processes
  61466. this.disposeTextureAndPostProcesses();
  61467. // Clean mesh references
  61468. for (var id in this._meshes) {
  61469. var meshHighlight = this._meshes[id];
  61470. if (meshHighlight && meshHighlight.mesh) {
  61471. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  61472. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  61473. }
  61474. }
  61475. this._meshes = null;
  61476. for (var id in this._excludedMeshes) {
  61477. var meshHighlight = this._excludedMeshes[id];
  61478. if (meshHighlight) {
  61479. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  61480. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  61481. }
  61482. }
  61483. this._excludedMeshes = null;
  61484. // Remove from scene
  61485. var index = this._scene.highlightLayers.indexOf(this, 0);
  61486. if (index > -1) {
  61487. this._scene.highlightLayers.splice(index, 1);
  61488. }
  61489. // Callback
  61490. this.onDisposeObservable.notifyObservers(this);
  61491. this.onDisposeObservable.clear();
  61492. this.onBeforeRenderMainTextureObservable.clear();
  61493. this.onBeforeBlurObservable.clear();
  61494. this.onBeforeComposeObservable.clear();
  61495. this.onAfterComposeObservable.clear();
  61496. this.onSizeChangedObservable.clear();
  61497. };
  61498. return HighlightLayer;
  61499. }());
  61500. /**
  61501. * The neutral color used during the preparation of the glow effect.
  61502. * This is black by default as the blend operation is a blend operation.
  61503. */
  61504. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  61505. /**
  61506. * Stencil value used for glowing meshes.
  61507. */
  61508. HighlightLayer.glowingMeshStencilReference = 0x02;
  61509. /**
  61510. * Stencil value used for the other meshes in the scene.
  61511. */
  61512. HighlightLayer.normalMeshStencilReference = 0x01;
  61513. BABYLON.HighlightLayer = HighlightLayer;
  61514. })(BABYLON || (BABYLON = {}));
  61515. //# sourceMappingURL=babylon.highlightlayer.js.map
  61516. var BABYLON;
  61517. (function (BABYLON) {
  61518. var MeshAssetTask = (function () {
  61519. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  61520. this.name = name;
  61521. this.meshesNames = meshesNames;
  61522. this.rootUrl = rootUrl;
  61523. this.sceneFilename = sceneFilename;
  61524. this.isCompleted = false;
  61525. }
  61526. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61527. var _this = this;
  61528. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  61529. _this.loadedMeshes = meshes;
  61530. _this.loadedParticleSystems = particleSystems;
  61531. _this.loadedSkeletons = skeletons;
  61532. _this.isCompleted = true;
  61533. if (_this.onSuccess) {
  61534. _this.onSuccess(_this);
  61535. }
  61536. onSuccess();
  61537. }, null, function () {
  61538. if (_this.onError) {
  61539. _this.onError(_this);
  61540. }
  61541. onError();
  61542. });
  61543. };
  61544. return MeshAssetTask;
  61545. }());
  61546. BABYLON.MeshAssetTask = MeshAssetTask;
  61547. var TextFileAssetTask = (function () {
  61548. function TextFileAssetTask(name, url) {
  61549. this.name = name;
  61550. this.url = url;
  61551. this.isCompleted = false;
  61552. }
  61553. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61554. var _this = this;
  61555. BABYLON.Tools.LoadFile(this.url, function (data) {
  61556. _this.text = data;
  61557. _this.isCompleted = true;
  61558. if (_this.onSuccess) {
  61559. _this.onSuccess(_this);
  61560. }
  61561. onSuccess();
  61562. }, null, scene.database, false, function () {
  61563. if (_this.onError) {
  61564. _this.onError(_this);
  61565. }
  61566. onError();
  61567. });
  61568. };
  61569. return TextFileAssetTask;
  61570. }());
  61571. BABYLON.TextFileAssetTask = TextFileAssetTask;
  61572. var BinaryFileAssetTask = (function () {
  61573. function BinaryFileAssetTask(name, url) {
  61574. this.name = name;
  61575. this.url = url;
  61576. this.isCompleted = false;
  61577. }
  61578. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61579. var _this = this;
  61580. BABYLON.Tools.LoadFile(this.url, function (data) {
  61581. _this.data = data;
  61582. _this.isCompleted = true;
  61583. if (_this.onSuccess) {
  61584. _this.onSuccess(_this);
  61585. }
  61586. onSuccess();
  61587. }, null, scene.database, true, function () {
  61588. if (_this.onError) {
  61589. _this.onError(_this);
  61590. }
  61591. onError();
  61592. });
  61593. };
  61594. return BinaryFileAssetTask;
  61595. }());
  61596. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  61597. var ImageAssetTask = (function () {
  61598. function ImageAssetTask(name, url) {
  61599. this.name = name;
  61600. this.url = url;
  61601. this.isCompleted = false;
  61602. }
  61603. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61604. var _this = this;
  61605. var img = new Image();
  61606. BABYLON.Tools.SetCorsBehavior(this.url, img);
  61607. img.onload = function () {
  61608. _this.image = img;
  61609. _this.isCompleted = true;
  61610. if (_this.onSuccess) {
  61611. _this.onSuccess(_this);
  61612. }
  61613. onSuccess();
  61614. };
  61615. img.onerror = function () {
  61616. if (_this.onError) {
  61617. _this.onError(_this);
  61618. }
  61619. onError();
  61620. };
  61621. img.src = this.url;
  61622. };
  61623. return ImageAssetTask;
  61624. }());
  61625. BABYLON.ImageAssetTask = ImageAssetTask;
  61626. var TextureAssetTask = (function () {
  61627. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  61628. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61629. this.name = name;
  61630. this.url = url;
  61631. this.noMipmap = noMipmap;
  61632. this.invertY = invertY;
  61633. this.samplingMode = samplingMode;
  61634. this.isCompleted = false;
  61635. }
  61636. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61637. var _this = this;
  61638. var onload = function () {
  61639. _this.isCompleted = true;
  61640. if (_this.onSuccess) {
  61641. _this.onSuccess(_this);
  61642. }
  61643. onSuccess();
  61644. };
  61645. var onerror = function () {
  61646. if (_this.onError) {
  61647. _this.onError(_this);
  61648. }
  61649. onError();
  61650. };
  61651. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  61652. };
  61653. return TextureAssetTask;
  61654. }());
  61655. BABYLON.TextureAssetTask = TextureAssetTask;
  61656. var CubeTextureAssetTask = (function () {
  61657. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  61658. this.name = name;
  61659. this.url = url;
  61660. this.extensions = extensions;
  61661. this.noMipmap = noMipmap;
  61662. this.files = files;
  61663. this.isCompleted = false;
  61664. }
  61665. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61666. var _this = this;
  61667. var onload = function () {
  61668. _this.isCompleted = true;
  61669. if (_this.onSuccess) {
  61670. _this.onSuccess(_this);
  61671. }
  61672. onSuccess();
  61673. };
  61674. var onerror = function () {
  61675. if (_this.onError) {
  61676. _this.onError(_this);
  61677. }
  61678. onError();
  61679. };
  61680. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  61681. };
  61682. return CubeTextureAssetTask;
  61683. }());
  61684. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  61685. var HDRCubeTextureAssetTask = (function () {
  61686. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  61687. if (noMipmap === void 0) { noMipmap = false; }
  61688. if (generateHarmonics === void 0) { generateHarmonics = true; }
  61689. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  61690. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  61691. this.name = name;
  61692. this.url = url;
  61693. this.size = size;
  61694. this.noMipmap = noMipmap;
  61695. this.generateHarmonics = generateHarmonics;
  61696. this.useInGammaSpace = useInGammaSpace;
  61697. this.usePMREMGenerator = usePMREMGenerator;
  61698. this.isCompleted = false;
  61699. }
  61700. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61701. var _this = this;
  61702. var onload = function () {
  61703. _this.isCompleted = true;
  61704. if (_this.onSuccess) {
  61705. _this.onSuccess(_this);
  61706. }
  61707. onSuccess();
  61708. };
  61709. var onerror = function () {
  61710. if (_this.onError) {
  61711. _this.onError(_this);
  61712. }
  61713. onError();
  61714. };
  61715. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  61716. };
  61717. return HDRCubeTextureAssetTask;
  61718. }());
  61719. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  61720. var AssetsManager = (function () {
  61721. function AssetsManager(scene) {
  61722. this.tasks = new Array();
  61723. this.waitingTasksCount = 0;
  61724. this.useDefaultLoadingScreen = true;
  61725. this._scene = scene;
  61726. }
  61727. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  61728. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  61729. this.tasks.push(task);
  61730. return task;
  61731. };
  61732. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  61733. var task = new TextFileAssetTask(taskName, url);
  61734. this.tasks.push(task);
  61735. return task;
  61736. };
  61737. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  61738. var task = new BinaryFileAssetTask(taskName, url);
  61739. this.tasks.push(task);
  61740. return task;
  61741. };
  61742. AssetsManager.prototype.addImageTask = function (taskName, url) {
  61743. var task = new ImageAssetTask(taskName, url);
  61744. this.tasks.push(task);
  61745. return task;
  61746. };
  61747. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  61748. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61749. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  61750. this.tasks.push(task);
  61751. return task;
  61752. };
  61753. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  61754. this.waitingTasksCount--;
  61755. if (this.waitingTasksCount === 0) {
  61756. if (this.onFinish) {
  61757. this.onFinish(this.tasks);
  61758. }
  61759. this._scene.getEngine().hideLoadingUI();
  61760. }
  61761. };
  61762. AssetsManager.prototype._runTask = function (task) {
  61763. var _this = this;
  61764. task.run(this._scene, function () {
  61765. if (_this.onTaskSuccess) {
  61766. _this.onTaskSuccess(task);
  61767. }
  61768. _this._decreaseWaitingTasksCount();
  61769. }, function () {
  61770. if (_this.onTaskError) {
  61771. _this.onTaskError(task);
  61772. }
  61773. _this._decreaseWaitingTasksCount();
  61774. });
  61775. };
  61776. AssetsManager.prototype.reset = function () {
  61777. this.tasks = new Array();
  61778. return this;
  61779. };
  61780. AssetsManager.prototype.load = function () {
  61781. this.waitingTasksCount = this.tasks.length;
  61782. if (this.waitingTasksCount === 0) {
  61783. if (this.onFinish) {
  61784. this.onFinish(this.tasks);
  61785. }
  61786. return this;
  61787. }
  61788. if (this.useDefaultLoadingScreen) {
  61789. this._scene.getEngine().displayLoadingUI();
  61790. }
  61791. for (var index = 0; index < this.tasks.length; index++) {
  61792. var task = this.tasks[index];
  61793. this._runTask(task);
  61794. }
  61795. return this;
  61796. };
  61797. return AssetsManager;
  61798. }());
  61799. BABYLON.AssetsManager = AssetsManager;
  61800. })(BABYLON || (BABYLON = {}));
  61801. //# sourceMappingURL=babylon.assetsManager.js.map
  61802. var BABYLON;
  61803. (function (BABYLON) {
  61804. var MapTexture = (function (_super) {
  61805. __extends(MapTexture, _super);
  61806. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  61807. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61808. if (useMipMap === void 0) { useMipMap = false; }
  61809. if (margin === void 0) { margin = 0; }
  61810. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  61811. _this.name = name;
  61812. _this._size = size;
  61813. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61814. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61815. // Create the rectPackMap that will allocate portion of the texture
  61816. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  61817. // Create the texture that will store the content
  61818. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  61819. return _this;
  61820. }
  61821. /**
  61822. * Allocate a rectangle of a given size in the texture map
  61823. * @param size the size of the rectangle to allocation
  61824. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  61825. */
  61826. MapTexture.prototype.allocateRect = function (size) {
  61827. return this._rectPackingMap.addRect(size);
  61828. };
  61829. /**
  61830. * Free a given rectangle from the texture map
  61831. * @param rectInfo the instance corresponding to the rect to free.
  61832. */
  61833. MapTexture.prototype.freeRect = function (rectInfo) {
  61834. if (rectInfo) {
  61835. rectInfo.freeContent();
  61836. }
  61837. };
  61838. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  61839. /**
  61840. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  61841. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  61842. * @returns {}
  61843. */
  61844. get: function () {
  61845. return this._rectPackingMap.freeSpace;
  61846. },
  61847. enumerable: true,
  61848. configurable: true
  61849. });
  61850. /**
  61851. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  61852. * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
  61853. * Don't forget to call unbindTexture when you're done rendering
  61854. * @param rect the zone to render to
  61855. * @param clear true to clear the portion's color/depth data
  61856. */
  61857. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  61858. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  61859. };
  61860. /**
  61861. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  61862. * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
  61863. * Don't forget to call unbindTexture when you're done rendering
  61864. * @param pos the position into the texture
  61865. * @param size the portion to fit the clip space to
  61866. * @param clear true to clear the portion's color/depth data
  61867. */
  61868. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  61869. var engine = this.getScene().getEngine();
  61870. engine.bindFramebuffer(this._texture);
  61871. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  61872. if (clear) {
  61873. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  61874. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  61875. }
  61876. };
  61877. /**
  61878. * Unbind the texture map from the rendering engine.
  61879. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  61880. * @param dumpForDebug if set to true the content of the texture map will be dumped to a picture file that will be sent to the internet browser.
  61881. */
  61882. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  61883. // Dump ?
  61884. if (dumpForDebug) {
  61885. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  61886. }
  61887. var engine = this.getScene().getEngine();
  61888. if (this._replacedViewport) {
  61889. engine.setViewport(this._replacedViewport);
  61890. this._replacedViewport = null;
  61891. }
  61892. engine.unBindFramebuffer(this._texture);
  61893. };
  61894. Object.defineProperty(MapTexture.prototype, "canRescale", {
  61895. get: function () {
  61896. return false;
  61897. },
  61898. enumerable: true,
  61899. configurable: true
  61900. });
  61901. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  61902. // Anyway, there's not much point to use this method for this kind of texture I guess
  61903. MapTexture.prototype.clone = function () {
  61904. return null;
  61905. };
  61906. return MapTexture;
  61907. }(BABYLON.Texture));
  61908. BABYLON.MapTexture = MapTexture;
  61909. })(BABYLON || (BABYLON = {}));
  61910. //# sourceMappingURL=babylon.mapTexture.js.map
  61911. var BABYLON;
  61912. (function (BABYLON) {
  61913. /**
  61914. * This class describe a rectangle that were added to the map.
  61915. * You have access to its coordinates either in pixel or normalized (UV)
  61916. */
  61917. var PackedRect = (function () {
  61918. function PackedRect(root, parent, pos, size) {
  61919. this._pos = pos;
  61920. this._size = size;
  61921. this._root = root;
  61922. this._parent = parent;
  61923. this._contentSize = null;
  61924. this._bottomNode = null;
  61925. this._leftNode = null;
  61926. this._initialSize = null;
  61927. this._rightNode = null;
  61928. }
  61929. Object.defineProperty(PackedRect.prototype, "pos", {
  61930. /**
  61931. * @returns the position of this node into the map
  61932. */
  61933. get: function () {
  61934. return this._pos;
  61935. },
  61936. enumerable: true,
  61937. configurable: true
  61938. });
  61939. Object.defineProperty(PackedRect.prototype, "contentSize", {
  61940. /**
  61941. * @returns the size of the rectangle this node handles
  61942. */
  61943. get: function () {
  61944. return this._contentSize;
  61945. },
  61946. enumerable: true,
  61947. configurable: true
  61948. });
  61949. /**
  61950. * Retrieve the inner position (considering the margin) and stores it into the res object
  61951. * @param res must be a valid Vector2 that will contain the inner position after this call
  61952. */
  61953. PackedRect.prototype.getInnerPosToRef = function (res) {
  61954. var m = this._root._margin;
  61955. res.x = this._pos.x + m;
  61956. res.y = this._pos.y + m;
  61957. };
  61958. /**
  61959. * Retrieve the inner size (considering the margin) and stores it into the res object
  61960. * @param res must be a valid Size that will contain the inner size after this call
  61961. */
  61962. PackedRect.prototype.getInnerSizeToRef = function (res) {
  61963. var m = this._root._margin;
  61964. res.width = this._contentSize.width - (m * 2);
  61965. res.height = this._contentSize.height - (m * 2);
  61966. };
  61967. Object.defineProperty(PackedRect.prototype, "UVs", {
  61968. /**
  61969. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  61970. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  61971. */
  61972. get: function () {
  61973. if (!this._contentSize) {
  61974. throw new Error("Can't compute UVs for this object because it's nor allocated");
  61975. }
  61976. return this.getUVsForCustomSize(this._contentSize);
  61977. },
  61978. enumerable: true,
  61979. configurable: true
  61980. });
  61981. /**
  61982. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  61983. * and then using only a part of the PackRect.
  61984. * This method will return the UVs for this part by given the custom size of what you really use
  61985. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  61986. */
  61987. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  61988. var mainWidth = this._root._size.width;
  61989. var mainHeight = this._root._size.height;
  61990. var margin = this._root._margin;
  61991. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  61992. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  61993. var uvs = new Array();
  61994. uvs.push(topLeft);
  61995. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  61996. uvs.push(rightBottom);
  61997. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  61998. return uvs;
  61999. };
  62000. /**
  62001. * Free this rectangle from the map.
  62002. * Call this method when you no longer need the rectangle to be in the map.
  62003. */
  62004. PackedRect.prototype.freeContent = function () {
  62005. if (!this.contentSize) {
  62006. return;
  62007. }
  62008. this._contentSize = null;
  62009. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  62010. this.attemptDefrag();
  62011. };
  62012. Object.defineProperty(PackedRect.prototype, "isUsed", {
  62013. get: function () {
  62014. return this._contentSize != null || this._leftNode != null;
  62015. },
  62016. enumerable: true,
  62017. configurable: true
  62018. });
  62019. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  62020. var node = this.findNode(contentSize);
  62021. // Not enough space...
  62022. if (!node) {
  62023. return null;
  62024. }
  62025. node.splitNode(contentSize);
  62026. return node;
  62027. };
  62028. PackedRect.prototype.findNode = function (size) {
  62029. var resNode = null;
  62030. var margin = this._root._margin * 2;
  62031. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  62032. if (this.isUsed) {
  62033. if (this._leftNode) {
  62034. resNode = this._leftNode.findNode(size);
  62035. }
  62036. if (!resNode && this._rightNode) {
  62037. resNode = this._rightNode.findNode(size);
  62038. }
  62039. if (!resNode && this._bottomNode) {
  62040. resNode = this._bottomNode.findNode(size);
  62041. }
  62042. }
  62043. else if (this._initialSize) {
  62044. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  62045. resNode = this;
  62046. }
  62047. else {
  62048. return null;
  62049. }
  62050. }
  62051. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  62052. resNode = this;
  62053. }
  62054. return resNode;
  62055. };
  62056. PackedRect.prototype.splitNode = function (contentSize) {
  62057. var cs = PackedRect.TpsSize;
  62058. var margin = this._root._margin * 2;
  62059. cs.copyFrom(contentSize);
  62060. cs.width += margin;
  62061. cs.height += margin;
  62062. // If there's no contentSize but an initialSize it means this node were previously allocated, but freed, we need to create a _leftNode as subNode and use to allocate the space we need (and this node will have a right/bottom subNode for the space left as this._initialSize may be greater than contentSize)
  62063. if (!this._contentSize && this._initialSize) {
  62064. this._contentSize = cs.clone();
  62065. this._leftNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y), new BABYLON.Size(this._initialSize.width, this._initialSize.height));
  62066. return this._leftNode.splitNode(contentSize);
  62067. }
  62068. else {
  62069. this._contentSize = cs.clone();
  62070. this._initialSize = cs.clone();
  62071. if (cs.width !== this._size.width) {
  62072. this._rightNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x + cs.width, this._pos.y), new BABYLON.Size(this._size.width - cs.width, cs.height));
  62073. }
  62074. if (cs.height !== this._size.height) {
  62075. this._bottomNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y + cs.height), new BABYLON.Size(this._size.width, this._size.height - cs.height));
  62076. }
  62077. return this;
  62078. }
  62079. };
  62080. PackedRect.prototype.attemptDefrag = function () {
  62081. if (!this.isUsed && this.isRecursiveFree) {
  62082. this.clearNode();
  62083. if (this._parent) {
  62084. this._parent.attemptDefrag();
  62085. }
  62086. }
  62087. };
  62088. PackedRect.prototype.clearNode = function () {
  62089. this._initialSize = null;
  62090. this._rightNode = null;
  62091. this._bottomNode = null;
  62092. };
  62093. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  62094. get: function () {
  62095. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  62096. },
  62097. enumerable: true,
  62098. configurable: true
  62099. });
  62100. PackedRect.prototype.evalFreeSize = function (size) {
  62101. var levelSize = 0;
  62102. if (!this.isUsed) {
  62103. var margin = this._root._margin;
  62104. var is = this._initialSize;
  62105. if (is) {
  62106. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  62107. }
  62108. else {
  62109. var size_1 = this._size;
  62110. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  62111. }
  62112. }
  62113. if (this._rightNode) {
  62114. levelSize += this._rightNode.evalFreeSize(0);
  62115. }
  62116. if (this._bottomNode) {
  62117. levelSize += this._bottomNode.evalFreeSize(0);
  62118. }
  62119. return levelSize + size;
  62120. };
  62121. return PackedRect;
  62122. }());
  62123. PackedRect.TpsSize = BABYLON.Size.Zero();
  62124. BABYLON.PackedRect = PackedRect;
  62125. /**
  62126. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  62127. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  62128. * Note that this class allows allocated Rectangles to be freed: that is the map is dynamically maintained so you can add/remove rectangle based on their life-cycle.
  62129. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  62130. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  62131. */
  62132. var RectPackingMap = (function (_super) {
  62133. __extends(RectPackingMap, _super);
  62134. /**
  62135. * Create an instance of the object with a dimension using the given size
  62136. * @param size The dimension of the rectangle that will contain all the sub ones.
  62137. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  62138. */
  62139. function RectPackingMap(size, margin) {
  62140. if (margin === void 0) { margin = 0; }
  62141. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  62142. _this._margin = margin;
  62143. _this._root = _this;
  62144. return _this;
  62145. }
  62146. /**
  62147. * Add a rectangle, finding the best location to store it into the map
  62148. * @param size the dimension of the rectangle to store
  62149. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  62150. */
  62151. RectPackingMap.prototype.addRect = function (size) {
  62152. var node = this.findAndSplitNode(size);
  62153. return node;
  62154. };
  62155. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  62156. /**
  62157. * Return the current space free normalized between [0;1]
  62158. * @returns {}
  62159. */
  62160. get: function () {
  62161. var freeSize = 0;
  62162. freeSize = this.evalFreeSize(freeSize);
  62163. return freeSize / (this._size.width * this._size.height);
  62164. },
  62165. enumerable: true,
  62166. configurable: true
  62167. });
  62168. return RectPackingMap;
  62169. }(PackedRect));
  62170. BABYLON.RectPackingMap = RectPackingMap;
  62171. })(BABYLON || (BABYLON = {}));
  62172. //# sourceMappingURL=babylon.rectPackingMap.js.map
  62173. var BABYLON;
  62174. (function (BABYLON) {
  62175. var DynamicFloatArrayElementInfo = (function () {
  62176. function DynamicFloatArrayElementInfo() {
  62177. }
  62178. return DynamicFloatArrayElementInfo;
  62179. }());
  62180. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  62181. /**
  62182. * The purpose of this class is to store float32 based elements of a given size (defined by the stride argument) in a dynamic fashion, that is, you can add/free elements. You can then access to a defragmented/packed version of the underlying Float32Array by calling the pack() method.
  62183. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  62184. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  62185. * Allocating an Element will return a instance of DynamicFloatArrayElement which contains the offset into the Float32Array of where the element starts, you are then responsible to copy your data using this offset.
  62186. * Beware, calling pack() may change the offset of some Entries because this method will defragment the Float32Array to replace empty elements by moving allocated ones at their location.
  62187. * This method will return an ArrayBufferView on the existing Float32Array that describes the used elements. Use this View to update the WebGLBuffer and NOT the "buffer" field of the class. The pack() method won't shrink/reallocate the buffer to keep it GC friendly, all the empty space will be put at the end of the buffer, the method just ensure there are no "free holes".
  62188. */
  62189. var DynamicFloatArray = (function () {
  62190. /**
  62191. * Construct an instance of the dynamic float array
  62192. * @param stride size of one element in float (i.e. not bytes!)
  62193. * @param initialElementCount the number of available entries at construction
  62194. */
  62195. function DynamicFloatArray(stride, initialElementCount) {
  62196. this.compareValueOffset = null;
  62197. this.sortingAscending = true;
  62198. this._stride = stride;
  62199. this.buffer = new Float32Array(stride * initialElementCount);
  62200. this._lastUsed = 0;
  62201. this._firstFree = 0;
  62202. this._allEntries = new Array(initialElementCount);
  62203. this._freeEntries = new Array(initialElementCount);
  62204. for (var i = 0; i < initialElementCount; i++) {
  62205. var element = new DynamicFloatArrayElementInfo();
  62206. element.offset = i * stride;
  62207. this._allEntries[i] = element;
  62208. this._freeEntries[initialElementCount - i - 1] = element;
  62209. }
  62210. }
  62211. /**
  62212. * Allocate an element in the array.
  62213. * @return the element info instance that contains the offset into the main buffer of the element's location.
  62214. * Beware, this offset may change when you call pack()
  62215. */
  62216. DynamicFloatArray.prototype.allocElement = function () {
  62217. if (this._freeEntries.length === 0) {
  62218. this._growBuffer();
  62219. }
  62220. var el = this._freeEntries.pop();
  62221. this._lastUsed = Math.max(el.offset, this._lastUsed);
  62222. if (el.offset === this._firstFree) {
  62223. if (this._freeEntries.length > 0) {
  62224. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  62225. }
  62226. else {
  62227. this._firstFree += this._stride;
  62228. }
  62229. }
  62230. return el;
  62231. };
  62232. /**
  62233. * Free the element corresponding to the given element info
  62234. * @param elInfo the element that describe the allocated element
  62235. */
  62236. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  62237. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  62238. this._freeEntries.push(elInfo);
  62239. };
  62240. /**
  62241. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  62242. * Instances of DynamicFloatArrayElement may have their 'offset' member changed as data could be copied from one location to another, so be sure to read/write your data based on the value inside this member after you called pack().
  62243. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  62244. */
  62245. DynamicFloatArray.prototype.pack = function () {
  62246. // no free slot? no need to pack
  62247. if (this._freeEntries.length === 0) {
  62248. return this.buffer;
  62249. }
  62250. // If the buffer is already packed the last used will always be lower than the first free
  62251. // The opposite may not be true, we can have a lastUsed greater than firstFree but the array still packed, because when an element is freed, lastUsed is not updated (for speed reason) so we may have a lastUsed of a freed element. But that's ok, well soon realize this case.
  62252. if (this._lastUsed < this._firstFree) {
  62253. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  62254. return elementsBuffer_1;
  62255. }
  62256. var s = this._stride;
  62257. // Make sure there's a free element at the very end, we need it to create a range where we'll move the used elements that may appear before
  62258. var lastFree = new DynamicFloatArrayElementInfo();
  62259. lastFree.offset = this.totalElementCount * s;
  62260. this._freeEntries.push(lastFree);
  62261. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  62262. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  62263. var firstFreeSlotOffset = sortedFree[0].offset;
  62264. var freeZoneSize = 1;
  62265. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  62266. var prevOffset = sortedFree[0].offset;
  62267. for (var i = 1; i < sortedFree.length; i++) {
  62268. // If the first free (which means everything before is occupied) is greater or equal the occupied zone size, it means everything is defragmented, we can quit
  62269. if (firstFreeSlotOffset >= occupiedZoneSize) {
  62270. break;
  62271. }
  62272. var curFree = sortedFree[i];
  62273. var curOffset = curFree.offset;
  62274. // Compute the distance between this offset and the previous
  62275. var distance = curOffset - prevOffset;
  62276. // If the distance is the stride size, they are adjacent, it good, move to the next
  62277. if (distance === s) {
  62278. // Free zone is one element bigger
  62279. ++freeZoneSize;
  62280. // as we're about to iterate to the next, the cur becomes the previous...
  62281. prevOffset = curOffset;
  62282. continue;
  62283. }
  62284. // Distance is bigger, which means there's x element between the previous free and this one
  62285. var usedRange = (distance / s) - 1;
  62286. // Two cases the free zone is smaller than the data to move or bigger
  62287. // Copy what can fit in the free zone
  62288. var curMoveOffset = curOffset - s;
  62289. var copyCount = Math.min(freeZoneSize, usedRange);
  62290. for (var j = 0; j < copyCount; j++) {
  62291. var freeI = firstFreeSlotOffset / s;
  62292. var curI = curMoveOffset / s;
  62293. var moveEl = sortedAll[curI];
  62294. this._moveElement(moveEl, firstFreeSlotOffset);
  62295. var replacedEl = sortedAll[freeI];
  62296. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  62297. replacedEl.offset = curMoveOffset;
  62298. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  62299. sortedAll[freeI] = moveEl;
  62300. sortedAll[curI] = replacedEl;
  62301. curMoveOffset -= s;
  62302. firstFreeSlotOffset += s;
  62303. }
  62304. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  62305. if (freeZoneSize <= usedRange) {
  62306. firstFreeSlotOffset = curMoveOffset + s;
  62307. freeZoneSize = 1 + copyCount;
  62308. }
  62309. else {
  62310. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  62311. }
  62312. // as we're about to iterate to the next, the cur becomes the previous...
  62313. prevOffset = curOffset;
  62314. }
  62315. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  62316. this._lastUsed = firstFreeSlotOffset - s;
  62317. this._firstFree = firstFreeSlotOffset;
  62318. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  62319. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  62320. this._allEntries = sortedAll;
  62321. return elementsBuffer;
  62322. };
  62323. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  62324. for (var i = 0; i < this._stride; i++) {
  62325. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  62326. }
  62327. element.offset = destOffset;
  62328. };
  62329. DynamicFloatArray.prototype._growBuffer = function () {
  62330. // Allocate the new buffer with 50% more entries, copy the content of the current one
  62331. var newElCount = Math.floor(this.totalElementCount * 1.5);
  62332. var newBuffer = new Float32Array(newElCount * this._stride);
  62333. newBuffer.set(this.buffer);
  62334. var curCount = this.totalElementCount;
  62335. var addedCount = newElCount - this.totalElementCount;
  62336. for (var i = 0; i < addedCount; i++) {
  62337. var element = new DynamicFloatArrayElementInfo();
  62338. element.offset = (curCount + i) * this.stride;
  62339. this._allEntries.push(element);
  62340. this._freeEntries[addedCount - i - 1] = element;
  62341. }
  62342. this._firstFree = curCount * this.stride;
  62343. this.buffer = newBuffer;
  62344. };
  62345. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  62346. /**
  62347. * Get the total count of entries that can fit in the current buffer
  62348. * @returns the elements count
  62349. */
  62350. get: function () {
  62351. return this._allEntries.length;
  62352. },
  62353. enumerable: true,
  62354. configurable: true
  62355. });
  62356. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  62357. /**
  62358. * Get the count of free entries that can still be allocated without resizing the buffer
  62359. * @returns the free elements count
  62360. */
  62361. get: function () {
  62362. return this._freeEntries.length;
  62363. },
  62364. enumerable: true,
  62365. configurable: true
  62366. });
  62367. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  62368. /**
  62369. * Get the count of allocated elements
  62370. * @returns the allocated elements count
  62371. */
  62372. get: function () {
  62373. return this._allEntries.length - this._freeEntries.length;
  62374. },
  62375. enumerable: true,
  62376. configurable: true
  62377. });
  62378. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  62379. /**
  62380. * Return the size of one element in float
  62381. * @returns the size in float
  62382. */
  62383. get: function () {
  62384. return this._stride;
  62385. },
  62386. enumerable: true,
  62387. configurable: true
  62388. });
  62389. DynamicFloatArray.prototype.sort = function () {
  62390. var _this = this;
  62391. if (!this.compareValueOffset) {
  62392. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  62393. }
  62394. var count = this.usedElementCount;
  62395. // Do we have to (re)create the sort table?
  62396. if (!this._sortTable || this._sortTable.length < count) {
  62397. // Small heuristic... We don't want to allocate totalElementCount right away because it may have 50 for 3 used elements, but on the other side we don't want to allocate just 3 when we just need 2, so double this value to give us some air to breath...
  62398. var newCount = Math.min(this.totalElementCount, count * 2);
  62399. this._sortTable = new Array(newCount);
  62400. }
  62401. if (!this._sortedTable || this._sortedTable.length !== count) {
  62402. this._sortedTable = new Array(count);
  62403. }
  62404. // Because, you know...
  62405. this.pack();
  62406. //let stride = this.stride;
  62407. //for (let i = 0; i < count; i++) {
  62408. // let si = this._sortTable[i];
  62409. // if (!si) {
  62410. // si = new SortInfo();
  62411. // this._sortTable[i] = si;
  62412. // }
  62413. // si.entry = this._allEntries[i];
  62414. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  62415. // si.swapedOffset = null;
  62416. // this._sortedTable[i] = si;
  62417. //}
  62418. var curOffset = 0;
  62419. var stride = this.stride;
  62420. for (var i = 0; i < count; i++, curOffset += stride) {
  62421. var si = this._sortTable[i];
  62422. if (!si) {
  62423. si = new SortInfo();
  62424. this._sortTable[i] = si;
  62425. }
  62426. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  62427. si.offset = curOffset;
  62428. si.swapedOffset = null;
  62429. this._sortedTable[i] = si;
  62430. }
  62431. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  62432. if (this.sortingAscending) {
  62433. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  62434. }
  62435. else {
  62436. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  62437. }
  62438. var swapElements = function (src, dst) {
  62439. for (var i = 0; i < stride; i++) {
  62440. var tps = _this.buffer[dst + i];
  62441. _this.buffer[dst + i] = _this.buffer[src + i];
  62442. _this.buffer[src + i] = tps;
  62443. }
  62444. };
  62445. // The fun part begin, sortedTable give us the ordered layout to obtain, to get that we have to move elements, but when we move an element:
  62446. // it replaces an existing one.I don't want to allocate a new Float32Array and do a raw copy, because it's awful (GC - wise),
  62447. // and I still want something with a good algorithm complexity.
  62448. // So here's the deal: we are going to swap elements, but we have to track the change of location of the element being replaced,
  62449. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  62450. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  62451. // When we'll look for and element, we'll check if its swapedOffset is set, if so we reiterate the operation with the one there
  62452. // until we find a SortInfo object without a swapedOffset which means we got the right location
  62453. // Yes, we may have to do multiple iterations to find the right location, but hey, it won't be huge: <3 in most cases, and it's better
  62454. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  62455. for (var i = 0; i < count; i++) {
  62456. // Get the element to move
  62457. var sourceSI = this._sortedTable[i];
  62458. var destSI = this._sortTable[i];
  62459. var sourceOff = sourceSI.offset;
  62460. // If the source changed location, find the new one
  62461. if (sourceSI.swapedOffset) {
  62462. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  62463. var curSI = sourceSI;
  62464. while (curSI.swapedOffset) {
  62465. curSI = this._sortTable[curSI.swapedOffset / stride];
  62466. }
  62467. // Finally get the right location
  62468. sourceOff = curSI.offset;
  62469. }
  62470. // Tag the element being replaced with its new location
  62471. destSI.swapedOffset = sourceOff;
  62472. // Swap elements (only if needed)
  62473. if (sourceOff !== destSI.offset) {
  62474. swapElements(sourceOff, destSI.offset);
  62475. }
  62476. // Update the offset in the corresponding DFAE
  62477. //sourceSI.entry.offset = destSI.entry.offset;
  62478. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  62479. }
  62480. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  62481. return true;
  62482. };
  62483. return DynamicFloatArray;
  62484. }());
  62485. BABYLON.DynamicFloatArray = DynamicFloatArray;
  62486. var SortInfo = (function () {
  62487. function SortInfo() {
  62488. this.compareData = this.offset = this.swapedOffset = null;
  62489. }
  62490. return SortInfo;
  62491. }());
  62492. })(BABYLON || (BABYLON = {}));
  62493. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  62494. var BABYLON;
  62495. (function (BABYLON) {
  62496. var serializedGeometries = [];
  62497. var serializeGeometry = function (geometry, serializationGeometries) {
  62498. if (serializedGeometries[geometry.id]) {
  62499. return;
  62500. }
  62501. if (geometry.doNotSerialize) {
  62502. return;
  62503. }
  62504. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  62505. serializationGeometries.boxes.push(geometry.serialize());
  62506. }
  62507. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  62508. serializationGeometries.spheres.push(geometry.serialize());
  62509. }
  62510. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  62511. serializationGeometries.cylinders.push(geometry.serialize());
  62512. }
  62513. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  62514. serializationGeometries.toruses.push(geometry.serialize());
  62515. }
  62516. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  62517. serializationGeometries.grounds.push(geometry.serialize());
  62518. }
  62519. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  62520. serializationGeometries.planes.push(geometry.serialize());
  62521. }
  62522. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  62523. serializationGeometries.torusKnots.push(geometry.serialize());
  62524. }
  62525. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  62526. throw new Error("Unknown primitive type");
  62527. }
  62528. else {
  62529. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  62530. }
  62531. serializedGeometries[geometry.id] = true;
  62532. };
  62533. var serializeMesh = function (mesh, serializationScene) {
  62534. var serializationObject = {};
  62535. // Geometry
  62536. var geometry = mesh._geometry;
  62537. if (geometry) {
  62538. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  62539. // 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
  62540. serializeGeometry(geometry, serializationScene.geometries);
  62541. }
  62542. }
  62543. // Custom
  62544. if (mesh.serialize) {
  62545. mesh.serialize(serializationObject);
  62546. }
  62547. return serializationObject;
  62548. };
  62549. var finalizeSingleMesh = function (mesh, serializationObject) {
  62550. //only works if the mesh is already loaded
  62551. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  62552. //serialize material
  62553. if (mesh.material) {
  62554. if (mesh.material instanceof BABYLON.StandardMaterial) {
  62555. serializationObject.materials = serializationObject.materials || [];
  62556. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  62557. serializationObject.materials.push(mesh.material.serialize());
  62558. }
  62559. }
  62560. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  62561. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  62562. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  62563. serializationObject.multiMaterials.push(mesh.material.serialize());
  62564. }
  62565. }
  62566. }
  62567. //serialize geometry
  62568. var geometry = mesh._geometry;
  62569. if (geometry) {
  62570. if (!serializationObject.geometries) {
  62571. serializationObject.geometries = {};
  62572. serializationObject.geometries.boxes = [];
  62573. serializationObject.geometries.spheres = [];
  62574. serializationObject.geometries.cylinders = [];
  62575. serializationObject.geometries.toruses = [];
  62576. serializationObject.geometries.grounds = [];
  62577. serializationObject.geometries.planes = [];
  62578. serializationObject.geometries.torusKnots = [];
  62579. serializationObject.geometries.vertexData = [];
  62580. }
  62581. serializeGeometry(geometry, serializationObject.geometries);
  62582. }
  62583. // Skeletons
  62584. if (mesh.skeleton) {
  62585. serializationObject.skeletons = serializationObject.skeletons || [];
  62586. serializationObject.skeletons.push(mesh.skeleton.serialize());
  62587. }
  62588. //serialize the actual mesh
  62589. serializationObject.meshes = serializationObject.meshes || [];
  62590. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  62591. }
  62592. };
  62593. var SceneSerializer = (function () {
  62594. function SceneSerializer() {
  62595. }
  62596. SceneSerializer.ClearCache = function () {
  62597. serializedGeometries = [];
  62598. };
  62599. SceneSerializer.Serialize = function (scene) {
  62600. var serializationObject = {};
  62601. SceneSerializer.ClearCache();
  62602. // Scene
  62603. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  62604. serializationObject.autoClear = scene.autoClear;
  62605. serializationObject.clearColor = scene.clearColor.asArray();
  62606. serializationObject.ambientColor = scene.ambientColor.asArray();
  62607. serializationObject.gravity = scene.gravity.asArray();
  62608. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  62609. serializationObject.workerCollisions = scene.workerCollisions;
  62610. // Fog
  62611. if (scene.fogMode && scene.fogMode !== 0) {
  62612. serializationObject.fogMode = scene.fogMode;
  62613. serializationObject.fogColor = scene.fogColor.asArray();
  62614. serializationObject.fogStart = scene.fogStart;
  62615. serializationObject.fogEnd = scene.fogEnd;
  62616. serializationObject.fogDensity = scene.fogDensity;
  62617. }
  62618. //Physics
  62619. if (scene.isPhysicsEnabled()) {
  62620. serializationObject.physicsEnabled = true;
  62621. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  62622. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  62623. }
  62624. // Metadata
  62625. if (scene.metadata) {
  62626. serializationObject.metadata = scene.metadata;
  62627. }
  62628. // Morph targets
  62629. serializationObject.morphTargetManagers = [];
  62630. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  62631. var abstractMesh = _a[_i];
  62632. var manager = abstractMesh.morphTargetManager;
  62633. if (manager) {
  62634. serializationObject.morphTargetManagers.push(manager.serialize());
  62635. }
  62636. }
  62637. // Lights
  62638. serializationObject.lights = [];
  62639. var index;
  62640. var light;
  62641. for (index = 0; index < scene.lights.length; index++) {
  62642. light = scene.lights[index];
  62643. if (!light.doNotSerialize) {
  62644. serializationObject.lights.push(light.serialize());
  62645. }
  62646. }
  62647. // Cameras
  62648. serializationObject.cameras = [];
  62649. for (index = 0; index < scene.cameras.length; index++) {
  62650. var camera = scene.cameras[index];
  62651. if (!camera.doNotSerialize) {
  62652. serializationObject.cameras.push(camera.serialize());
  62653. }
  62654. }
  62655. if (scene.activeCamera) {
  62656. serializationObject.activeCameraID = scene.activeCamera.id;
  62657. }
  62658. // Animations
  62659. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  62660. // Materials
  62661. serializationObject.materials = [];
  62662. serializationObject.multiMaterials = [];
  62663. var material;
  62664. for (index = 0; index < scene.materials.length; index++) {
  62665. material = scene.materials[index];
  62666. if (!material.doNotSerialize) {
  62667. serializationObject.materials.push(material.serialize());
  62668. }
  62669. }
  62670. // MultiMaterials
  62671. serializationObject.multiMaterials = [];
  62672. for (index = 0; index < scene.multiMaterials.length; index++) {
  62673. var multiMaterial = scene.multiMaterials[index];
  62674. serializationObject.multiMaterials.push(multiMaterial.serialize());
  62675. }
  62676. // Skeletons
  62677. serializationObject.skeletons = [];
  62678. for (index = 0; index < scene.skeletons.length; index++) {
  62679. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  62680. }
  62681. // Geometries
  62682. serializationObject.geometries = {};
  62683. serializationObject.geometries.boxes = [];
  62684. serializationObject.geometries.spheres = [];
  62685. serializationObject.geometries.cylinders = [];
  62686. serializationObject.geometries.toruses = [];
  62687. serializationObject.geometries.grounds = [];
  62688. serializationObject.geometries.planes = [];
  62689. serializationObject.geometries.torusKnots = [];
  62690. serializationObject.geometries.vertexData = [];
  62691. serializedGeometries = [];
  62692. var geometries = scene.getGeometries();
  62693. for (index = 0; index < geometries.length; index++) {
  62694. var geometry = geometries[index];
  62695. if (geometry.isReady()) {
  62696. serializeGeometry(geometry, serializationObject.geometries);
  62697. }
  62698. }
  62699. // Meshes
  62700. serializationObject.meshes = [];
  62701. for (index = 0; index < scene.meshes.length; index++) {
  62702. var abstractMesh = scene.meshes[index];
  62703. if (abstractMesh instanceof BABYLON.Mesh) {
  62704. var mesh = abstractMesh;
  62705. if (!mesh.doNotSerialize) {
  62706. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  62707. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  62708. }
  62709. }
  62710. }
  62711. }
  62712. // Particles Systems
  62713. serializationObject.particleSystems = [];
  62714. for (index = 0; index < scene.particleSystems.length; index++) {
  62715. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  62716. }
  62717. // Lens flares
  62718. serializationObject.lensFlareSystems = [];
  62719. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  62720. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  62721. }
  62722. // Shadows
  62723. serializationObject.shadowGenerators = [];
  62724. for (index = 0; index < scene.lights.length; index++) {
  62725. light = scene.lights[index];
  62726. var shadowGenerator = light.getShadowGenerator();
  62727. // Only support serialization for official generator so far.
  62728. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  62729. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  62730. }
  62731. }
  62732. // Action Manager
  62733. if (scene.actionManager) {
  62734. serializationObject.actions = scene.actionManager.serialize("scene");
  62735. }
  62736. // Audio
  62737. serializationObject.sounds = [];
  62738. for (index = 0; index < scene.soundTracks.length; index++) {
  62739. var soundtrack = scene.soundTracks[index];
  62740. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  62741. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  62742. }
  62743. }
  62744. return serializationObject;
  62745. };
  62746. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  62747. if (withParents === void 0) { withParents = false; }
  62748. if (withChildren === void 0) { withChildren = false; }
  62749. var serializationObject = {};
  62750. SceneSerializer.ClearCache();
  62751. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  62752. if (withParents || withChildren) {
  62753. //deliberate for loop! not for each, appended should be processed as well.
  62754. for (var i = 0; i < toSerialize.length; ++i) {
  62755. if (withChildren) {
  62756. toSerialize[i].getDescendants().forEach(function (node) {
  62757. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  62758. toSerialize.push(node);
  62759. }
  62760. });
  62761. }
  62762. //make sure the array doesn't contain the object already
  62763. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  62764. toSerialize.push(toSerialize[i].parent);
  62765. }
  62766. }
  62767. }
  62768. toSerialize.forEach(function (mesh) {
  62769. finalizeSingleMesh(mesh, serializationObject);
  62770. });
  62771. return serializationObject;
  62772. };
  62773. return SceneSerializer;
  62774. }());
  62775. BABYLON.SceneSerializer = SceneSerializer;
  62776. })(BABYLON || (BABYLON = {}));
  62777. //# sourceMappingURL=babylon.sceneSerializer.js.map
  62778. var BABYLON;
  62779. (function (BABYLON) {
  62780. var ReflectionProbe = (function () {
  62781. function ReflectionProbe(name, size, scene, generateMipMaps) {
  62782. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62783. var _this = this;
  62784. this.name = name;
  62785. this._viewMatrix = BABYLON.Matrix.Identity();
  62786. this._target = BABYLON.Vector3.Zero();
  62787. this._add = BABYLON.Vector3.Zero();
  62788. this.invertYAxis = false;
  62789. this.position = BABYLON.Vector3.Zero();
  62790. this._scene = scene;
  62791. this._scene.reflectionProbes.push(this);
  62792. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  62793. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  62794. switch (faceIndex) {
  62795. case 0:
  62796. _this._add.copyFromFloats(1, 0, 0);
  62797. break;
  62798. case 1:
  62799. _this._add.copyFromFloats(-1, 0, 0);
  62800. break;
  62801. case 2:
  62802. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  62803. break;
  62804. case 3:
  62805. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  62806. break;
  62807. case 4:
  62808. _this._add.copyFromFloats(0, 0, 1);
  62809. break;
  62810. case 5:
  62811. _this._add.copyFromFloats(0, 0, -1);
  62812. break;
  62813. }
  62814. if (_this._attachedMesh) {
  62815. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  62816. }
  62817. _this.position.addToRef(_this._add, _this._target);
  62818. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  62819. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  62820. });
  62821. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  62822. scene.updateTransformMatrix(true);
  62823. });
  62824. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  62825. }
  62826. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  62827. get: function () {
  62828. return this._renderTargetTexture.samples;
  62829. },
  62830. set: function (value) {
  62831. this._renderTargetTexture.samples = value;
  62832. },
  62833. enumerable: true,
  62834. configurable: true
  62835. });
  62836. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  62837. get: function () {
  62838. return this._renderTargetTexture.refreshRate;
  62839. },
  62840. set: function (value) {
  62841. this._renderTargetTexture.refreshRate = value;
  62842. },
  62843. enumerable: true,
  62844. configurable: true
  62845. });
  62846. ReflectionProbe.prototype.getScene = function () {
  62847. return this._scene;
  62848. };
  62849. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  62850. get: function () {
  62851. return this._renderTargetTexture;
  62852. },
  62853. enumerable: true,
  62854. configurable: true
  62855. });
  62856. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  62857. get: function () {
  62858. return this._renderTargetTexture.renderList;
  62859. },
  62860. enumerable: true,
  62861. configurable: true
  62862. });
  62863. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  62864. this._attachedMesh = mesh;
  62865. };
  62866. ReflectionProbe.prototype.dispose = function () {
  62867. var index = this._scene.reflectionProbes.indexOf(this);
  62868. if (index !== -1) {
  62869. // Remove from the scene if found
  62870. this._scene.reflectionProbes.splice(index, 1);
  62871. }
  62872. if (this._renderTargetTexture) {
  62873. this._renderTargetTexture.dispose();
  62874. this._renderTargetTexture = null;
  62875. }
  62876. };
  62877. return ReflectionProbe;
  62878. }());
  62879. BABYLON.ReflectionProbe = ReflectionProbe;
  62880. })(BABYLON || (BABYLON = {}));
  62881. //# sourceMappingURL=babylon.reflectionProbe.js.map
  62882. var BABYLON;
  62883. (function (BABYLON) {
  62884. var Layer = (function () {
  62885. function Layer(name, imgUrl, scene, isBackground, color) {
  62886. this.name = name;
  62887. this.scale = new BABYLON.Vector2(1, 1);
  62888. this.offset = new BABYLON.Vector2(0, 0);
  62889. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  62890. this._vertexBuffers = {};
  62891. // Events
  62892. /**
  62893. * An event triggered when the layer is disposed.
  62894. * @type {BABYLON.Observable}
  62895. */
  62896. this.onDisposeObservable = new BABYLON.Observable();
  62897. /**
  62898. * An event triggered before rendering the scene
  62899. * @type {BABYLON.Observable}
  62900. */
  62901. this.onBeforeRenderObservable = new BABYLON.Observable();
  62902. /**
  62903. * An event triggered after rendering the scene
  62904. * @type {BABYLON.Observable}
  62905. */
  62906. this.onAfterRenderObservable = new BABYLON.Observable();
  62907. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  62908. this.isBackground = isBackground === undefined ? true : isBackground;
  62909. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  62910. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62911. this._scene.layers.push(this);
  62912. var engine = this._scene.getEngine();
  62913. // VBO
  62914. var vertices = [];
  62915. vertices.push(1, 1);
  62916. vertices.push(-1, 1);
  62917. vertices.push(-1, -1);
  62918. vertices.push(1, -1);
  62919. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  62920. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  62921. // Indices
  62922. var indices = [];
  62923. indices.push(0);
  62924. indices.push(1);
  62925. indices.push(2);
  62926. indices.push(0);
  62927. indices.push(2);
  62928. indices.push(3);
  62929. this._indexBuffer = engine.createIndexBuffer(indices);
  62930. // Effects
  62931. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  62932. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  62933. }
  62934. Object.defineProperty(Layer.prototype, "onDispose", {
  62935. set: function (callback) {
  62936. if (this._onDisposeObserver) {
  62937. this.onDisposeObservable.remove(this._onDisposeObserver);
  62938. }
  62939. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  62940. },
  62941. enumerable: true,
  62942. configurable: true
  62943. });
  62944. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  62945. set: function (callback) {
  62946. if (this._onBeforeRenderObserver) {
  62947. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  62948. }
  62949. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  62950. },
  62951. enumerable: true,
  62952. configurable: true
  62953. });
  62954. Object.defineProperty(Layer.prototype, "onAfterRender", {
  62955. set: function (callback) {
  62956. if (this._onAfterRenderObserver) {
  62957. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  62958. }
  62959. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  62960. },
  62961. enumerable: true,
  62962. configurable: true
  62963. });
  62964. Layer.prototype.render = function () {
  62965. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  62966. // Check
  62967. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  62968. return;
  62969. var engine = this._scene.getEngine();
  62970. this.onBeforeRenderObservable.notifyObservers(this);
  62971. // Render
  62972. engine.enableEffect(currentEffect);
  62973. engine.setState(false);
  62974. // Texture
  62975. currentEffect.setTexture("textureSampler", this.texture);
  62976. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  62977. // Color
  62978. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  62979. // Scale / offset
  62980. currentEffect.setVector2("offset", this.offset);
  62981. currentEffect.setVector2("scale", this.scale);
  62982. // VBOs
  62983. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  62984. // Draw order
  62985. if (!this.alphaTest) {
  62986. engine.setAlphaMode(this.alphaBlendingMode);
  62987. engine.draw(true, 0, 6);
  62988. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  62989. }
  62990. else {
  62991. engine.draw(true, 0, 6);
  62992. }
  62993. this.onAfterRenderObservable.notifyObservers(this);
  62994. };
  62995. Layer.prototype.dispose = function () {
  62996. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62997. if (vertexBuffer) {
  62998. vertexBuffer.dispose();
  62999. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63000. }
  63001. if (this._indexBuffer) {
  63002. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  63003. this._indexBuffer = null;
  63004. }
  63005. if (this.texture) {
  63006. this.texture.dispose();
  63007. this.texture = null;
  63008. }
  63009. // Remove from scene
  63010. var index = this._scene.layers.indexOf(this);
  63011. this._scene.layers.splice(index, 1);
  63012. // Callback
  63013. this.onDisposeObservable.notifyObservers(this);
  63014. this.onDisposeObservable.clear();
  63015. this.onAfterRenderObservable.clear();
  63016. this.onBeforeRenderObservable.clear();
  63017. };
  63018. return Layer;
  63019. }());
  63020. BABYLON.Layer = Layer;
  63021. })(BABYLON || (BABYLON = {}));
  63022. //# sourceMappingURL=babylon.layer.js.map
  63023. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\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>\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,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<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#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;\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<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\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#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\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+uvOffset).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+uvOffset);\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#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\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+uvOffset).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#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\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\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\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>\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,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) || defined(METALLICWORKFLOW) \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 MICROSURFACEMAP\nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*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<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP)|| !defined(NORMAL)\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;\n#include<__decl__pbrFragment>\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\nvarying vec2 vMicroSurfaceSamplerUV;\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<helperFunctions>\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\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV+uvOffset);\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\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE \nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#ifdef OVERLOADEDVALUES\nambientOcclusionColor.rgb=mix(ambientOcclusionColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a*vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#else\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#endif\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef METALLICMAP\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED \nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo.rgb;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo.rgb=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#else\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface=microSurfaceTexel.r;\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.; \n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\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 ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\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 ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\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 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\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).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=lightDiffuseContribution*surfaceAlbedoContribution;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=(lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=(shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution;\n#endif\n#else\nvec3 finalDiffuse=lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor;\n#endif\n#endif\n#endif\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution+=vAmbientColor;\nshadowedOnlyLightDiffuseContribution*=surfaceAlbedo.rgb;\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution,0.0);\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\nfinalDiffuse=(finalDiffuse*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance)*ambientOcclusionColor;\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\nvec4 finalColor=vec4(finalDiffuse+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#ifdef EMISSIVEASILLUMINATION\nfinalColor.rgb+=(surfaceEmissiveColor*vLightingIntensity.y);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\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#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\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\nvFogDistance=viewPos;\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}","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}","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}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\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}","shadowMapPixelShader":"#ifndef FULLFLOAT\nvec4 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#endif\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\nuniform vec2 biasAndScale;\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\ndepth+=biasAndScale.x;\n#ifdef ESM\ndepth=exp(-min(87.,biasAndScale.y*depth));\n#endif\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\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}","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}","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}","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}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\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;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\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#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\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","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}","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}","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","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\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(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\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(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float blurWidth;\nvoid main(void)\n{\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]*blurWidth,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\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;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\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(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\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()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\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","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}","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}","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}","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}","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":"varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 sampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nvec2 sampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nvec2 sampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nvec2 sampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nvec2 sampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nvec2 sampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nvec2 sampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nvec2 sampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.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 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\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","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}","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}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\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}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","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}","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}","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}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\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{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\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 DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\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}","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}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\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","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}","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}","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}"};
  63024. 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","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\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","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 normalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\nvec3 tangentW=normalize(vec3(finalWorld*vec4(tangentUpdated.xyz,0.0)));\nvec3 bitangentW=cross(normalW,tangentW)*tangentUpdated.w;\nvTBN=mat3(tangentW,bitangentW,normalW);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\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}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\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,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}\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","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec3 shadowsInfo;\n} light{X};\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\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\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_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\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#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,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;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\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 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\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\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}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample-darkness,0.,1.); \n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,esm,vOverloadedShadowIntensity.x);\n#else\nreturn esm;\n#endif\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,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}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\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 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\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<depth.z) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<depth.z) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,min(1.0,visibility+darkness),vOverloadedShadowIntensity.x);\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float depthScale)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 depth=0.5*clipSpace+vec3(0.5);\nvec2 uv=depth.xy;\nfloat shadowPixelDepth=depth.z;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample-darkness,0.,1.); \n\n\n\n\n\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,esm,vOverloadedShadowIntensity.x);\n#else\nreturn esm;\n#endif\n}\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","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_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;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\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}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","colorGrading":"vec4 colorGrades(vec4 color) \n{ \n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","colorCurves":"const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\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(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\n#ifdef INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\nmap.y=1.0-map.y;\n#endif\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","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\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 vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWESM{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.x);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\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\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\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\n#else\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec2 vMicrosurfaceTextureLods;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform vec4 opacityParts;\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\nuniform vec4 vOverloadedShadowIntensity;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","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,vec3 reflectance90)\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,reflectance90);\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#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\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}\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","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","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,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=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,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,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=max(0.00000000001,dot(vNormal,directionToLightCenterW));\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,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,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,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWESM{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z);\n#else\nnotShadowLevel=computeShadowWithESM(light{X}.vPositionFromLight,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z);\n#endif\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.x);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\nlightDiffuseContribution+=lightmapColor*notShadowLevel;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nlightSpecularContribution+=info.specular*notShadowLevel*lightmapColor;\n#endif\n#endif\n#else\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\n#endif"};
  63025. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  63026. module.exports = BABYLON;
  63027. };